diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-cookies/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-cookies/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6188e042dc7fc948babeaf2491c9c636a9fd9c4a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-cookies/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-http-cookies + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-cookies/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-cookies/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-cookies/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..df8a5c2ebba2494b0e402e63f5aef63f9cc31aa3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-http-daemon via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-http-daemon -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-http-daemon_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-http-daemon_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-http-daemon_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/app/perl-http-daemon_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/app/perl-http-daemon_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2dc1f39f2a1fb2b44018504aa250fddf1e47a9be --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/app/perl-http-daemon_server.py @@ -0,0 +1,184 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +@mcp.tool() +def run_perl_interpreter( + program_file: Optional[Path] = None, + program_arguments: Optional[List[str]] = None, + record_separator_octal: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debug_flags: Optional[str] = None, + program_string: Optional[List[str]] = None, + program_string_extended: Optional[List[str]] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing_terminator: Optional[str] = None, + use_modules: Optional[List[str]] = None, + no_modules: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + rudimentary_switch_parsing: bool = False, + look_for_programfile_in_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core_after_parsing: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary_variable: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang_directory: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> dict: + """ + Executes a Perl script or one-liner using the Perl interpreter. + + This tool wraps the generic 'perl' interpreter command, providing access to its + various command-line switches. While the request was for 'perl-http-daemon', + 'HTTP::Daemon' is a Perl module, not a standalone executable. The provided + CLI help is for the 'perl' interpreter itself. This function allows running + any Perl script, including those that might utilize the 'HTTP::Daemon' module, + with full control over interpreter options. + """ + command = ["perl"] + output_files = [] + + # --- Input validation --- + if program_file: + if not program_file.is_file(): + raise FileNotFoundError(f"Program file not found: {program_file}") + if program_string or program_string_extended: + raise ValueError("Cannot specify both a program file and program string(s) (-e/-E).") + + if program_string and program_string_extended: + raise ValueError("Cannot specify both -e and -E program strings simultaneously.") + + if loop_around_program and loop_and_print: + raise ValueError("Cannot specify both -n and -p simultaneously.") + + warning_flags_set = sum([enable_warnings, enable_all_warnings, disable_all_warnings]) + if warning_flags_set > 1: + raise ValueError("Cannot specify more than one of -w, -W, or -X simultaneously.") + + if include_directories: + for d in include_directories: + if not d.is_dir(): + raise NotADirectoryError(f"Include directory not found or is not a directory: {d}") + + if ignore_text_before_shebang_directory: + if not ignore_text_before_shebang_directory.is_dir(): + raise NotADirectoryError(f"Directory for -x not found or is not a directory: {ignore_text_before_shebang_directory}") + + # --- Build command --- + if record_separator_octal is not None: + command.append(f"-0{record_separator_octal}") + if autosplit: + command.append("-a") + if unicode_features is not None: + command.append(f"-C{unicode_features}") + if check_syntax_only: + command.append("-c") + if debugger is not None: + command.append(f"-d:{debugger}" if debugger else "-d") + if debug_flags is not None: + command.append(f"-D{debug_flags}") + if program_string: + for p_str in program_string: + command.extend(["-e", p_str]) + if program_string_extended: + for p_str in program_string_extended: + command.extend(["-E", p_str]) + if no_sitecustomize: + command.append("-f") + if split_pattern is not None: + command.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + command.append(f"-i{edit_in_place_extension}") + if include_directories: + for d in include_directories: + command.extend(["-I", str(d)]) + if line_ending_processing_terminator is not None: + command.append(f"-l{line_ending_processing_terminator}") + if use_modules: + for module in use_modules: + command.extend(["-M", module]) + if no_modules: + for module in no_modules: + command.extend(["-m-", module]) + if loop_around_program: + command.append("-n") + if loop_and_print: + command.append("-p") + if rudimentary_switch_parsing: + command.append("-s") + if look_for_programfile_in_path: + command.append("-S") + if tainting_warnings: + command.append("-t") + if tainting_checks: + command.append("-T") + if dump_core_after_parsing: + command.append("-u") + if allow_unsafe_operations: + command.append("-U") + if print_version: + command.append("-v") + if print_config_summary_variable is not None: + command.append(f"-V:{print_config_summary_variable}" if print_config_summary_variable else "-V") + if enable_warnings: + command.append("-w") + if enable_all_warnings: + command.append("-W") + if ignore_text_before_shebang_directory is not None: + command.append(f"-x{ignore_text_before_shebang_directory}") + if disable_all_warnings: + command.append("-X") + + # Add program file and its arguments (positional) + if program_file: + command.append(str(program_file)) + + if program_arguments: + command.extend(program_arguments) + + # --- Execute command --- + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"Perl command failed with exit code {e.returncode}.", + "returncode": e.returncode, + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and accessible in your PATH.", + "output_files": [], + "error": "Perl executable not found.", + "returncode": 127, + } + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/app/perl-http-daemon_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/app/perl-http-daemon_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..345ebbdc27f3407841784eeff468a47b316a7d71 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/app/perl-http-daemon_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/app/perl-http-daemon_server.py') +SERVER_NAME = 'biosci_perl_http_daemon' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..506e8d6a356a6d3e367cb06948f1a9720dff0088 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-http-daemon: + build: . + image: mcp-perl-http-daemon:latest + container_name: mcp-perl-http-daemon + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-http-daemon + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..53d8291c5725145eeb629aabe9d7d1a13dbc61f6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-http-daemon + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-daemon/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5bdca216be47b186b08ec6224d6ae0e0e377f84f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-http-date via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-http-date -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-http-date_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-http-date_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-http-date_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/app/perl-http-date_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/app/perl-http-date_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0c6dc1f75c45f0813c595348a909df8274886909 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/app/perl-http-date_server.py @@ -0,0 +1,289 @@ +import subprocess +import sys +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Mock decorator for standalone execution +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def time2str(time: Optional[int] = None) -> Dict[str, Any]: + """ + Converts a machine time (seconds since epoch) to an HTTP-formatted string. + + This function wraps the `time2str()` function from the Perl HTTP::Date module. + The string returned is in the format preferred for the HTTP protocol (RFC 1123), + represented in Universal Time (GMT). Example: Sun, 06 Nov 1994 08:49:37 GMT. + + Args: + time: The time in seconds since the epoch. If not provided or None, + the current time will be used. + + Returns: + A dictionary containing the command executed, stdout (the formatted date string), + stderr, and a list of output files (which is always empty). + """ + command = ["perl", "-MHTTP::Date", "-e"] + if time is not None: + if not isinstance(time, int): + raise TypeError("The 'time' parameter must be an integer.") + script = f'print HTTP::Date::time2str({time})' + else: + script = 'print HTTP::Date::time2str()' + + command.append(script) + + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: 'perl' executable not found. Please ensure Perl is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "output_files": [] + } + +@mcp.tool +def str2time(date_string: str, zone: Optional[str] = None) -> Dict[str, Any]: + """ + Converts a date string to machine time (seconds since epoch). + + This function wraps the `str2time()` function from the Perl HTTP::Date module. + It returns the machine time if the format is recognized, otherwise it may return an empty string. + Note: If the zone is not 'GMT' or numerical (e.g., '-0800'), the Time::Zone Perl module + must be installed for the date to be recognized. + + Args: + date_string: The date string to convert. + zone: The default time zone to use if the date string does not contain one. + + Returns: + A dictionary containing the command executed, stdout (the machine time), + stderr, and a list of output files (which is always empty). + """ + if not date_string: + raise ValueError("The 'date_string' parameter cannot be empty.") + + command = ["perl", "-MHTTP::Date", "-e"] + + if zone: + script = 'print HTTP::Date::str2time(shift, shift)' + command.extend([script, date_string, zone]) + else: + script = 'print HTTP::Date::str2time(shift)' + command.extend([script, date_string]) + + command_str = " ".join(f"'{arg}'" if " " in arg else arg for arg in command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: 'perl' executable not found. Please ensure Perl is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "output_files": [] + } + +@mcp.tool +def parse_date(date_string: str) -> Dict[str, Any]: + """ + Parses a date string and returns its components. + + This function wraps the `parse_date()` function from the Perl HTTP::Date module. + It returns a comma-separated string of numerical values: + year,month,day,hour,min,sec,timezone. The year will be the full 4-digit year, + and month numbers start with 1 for January. + + Args: + date_string: The date string to parse. + + Returns: + A dictionary containing the command executed, stdout (the parsed date components), + stderr, and a list of output files (which is always empty). + """ + if not date_string: + raise ValueError("The 'date_string' parameter cannot be empty.") + + script = 'my @parts = HTTP::Date::parse_date(shift); print join(",", @parts);' + command = ["perl", "-MHTTP::Date", "-e", script, date_string] + command_str = " ".join(f"'{arg}'" if " " in arg else arg for arg in command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: 'perl' executable not found. Please ensure Perl is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "output_files": [] + } + +@mcp.tool +def time2iso(time: Optional[int] = None) -> Dict[str, Any]: + """ + Converts machine time to a 'YYYY-MM-DD hh:mm:ss' formatted string in the local time zone. + + This function wraps the `time2iso()` function from the Perl HTTP::Date module. + + Args: + time: The time in seconds since the epoch. If not provided or None, + the current time will be used. + + Returns: + A dictionary containing the command executed, stdout (the formatted date string), + stderr, and a list of output files (which is always empty). + """ + command = ["perl", "-MHTTP::Date", "-e"] + if time is not None: + if not isinstance(time, int): + raise TypeError("The 'time' parameter must be an integer.") + script = f'print HTTP::Date::time2iso({time})' + else: + script = 'print HTTP::Date::time2iso()' + + command.append(script) + + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: 'perl' executable not found. Please ensure Perl is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "output_files": [] + } + +@mcp.tool +def time2isoz(time: Optional[int] = None) -> Dict[str, Any]: + """ + Converts machine time to a 'YYYY-MM-DD hh:mm:ssZ' formatted string in Universal Time. + + This function wraps the `time2isoz()` function from the Perl HTTP::Date module. + + Args: + time: The time in seconds since the epoch. If not provided or None, + the current time will be used. + + Returns: + A dictionary containing the command executed, stdout (the formatted date string), + stderr, and a list of output files (which is always empty). + """ + command = ["perl", "-MHTTP::Date", "-e"] + if time is not None: + if not isinstance(time, int): + raise TypeError("The 'time' parameter must be an integer.") + script = f'print HTTP::Date::time2isoz({time})' + else: + script = 'print HTTP::Date::time2isoz()' + + command.append(script) + + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: 'perl' executable not found. Please ensure Perl is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/app/perl-http-date_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/app/perl-http-date_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..94c8102e12a08d33824ba7b7b06d3d98c9cf72d6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/app/perl-http-date_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/app/perl-http-date_server.py') +SERVER_NAME = 'biosci_perl_http_date' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e7959f3bed2e3def9a44804f7a4da596ea00eefb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-http-date: + build: . + image: mcp-perl-http-date:latest + container_name: mcp-perl-http-date + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-http-date + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2106b65b2b52c30950736ca80067f61210cd50c6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-http-date + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-date/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..650353651fd8fa4a451fe587578c9d97a902f282 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-http-message via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-http-message -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-http-message_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-http-message_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-http-message_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/app/perl-http-message_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/app/perl-http-message_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8fb445ebff3400cd4105995ac21b74d2023a25d1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/app/perl-http-message_server.py @@ -0,0 +1,292 @@ +import subprocess +from typing import Optional, List +from pathlib import Path + +@mcp.tool() +def http_message_as_string( + raw_message: str, + eol: Optional[str] = None, +): + """ + Parses a raw HTTP message string and returns it formatted as a single string. + + Args: + raw_message: The raw HTTP message string to parse. + eol: Optional line ending sequence to use (default is "\\n"). + """ + # Construct Perl one-liner + # We use base64 or escaping to pass the raw message safely, + # but for simplicity in this environment, we'll use a temporary file or stdin. + + perl_code = 'use HTTP::Message; my $m = HTTP::Message->parse($ARGV[0]);' + if eol: + perl_code += 'print $m->as_string($ARGV[1]);' + args = [raw_message, eol] + else: + perl_code += 'print $m->as_string;' + args = [raw_message] + + try: + result = subprocess.run( + ["perl", "-MHTTP::Message", "-e", perl_code, "--"] + args, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"perl -MHTTP::Message -e '{perl_code}'", + "stdout": result.stdout, + "stderr": result.stderr, + "output": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def http_message_dump( + raw_message: str, + maxlength: int = 512, + no_content: str = "(no content)", + prefix: str = "" +): + """ + Returns a detailed dump of the HTTP message, escaping non-printable bytes. + Useful for debugging raw HTTP traffic. + + Args: + raw_message: The raw HTTP message string. + maxlength: How much of the content to show. Set to 0 for unlimited. + no_content: String to display if there is no content. + prefix: String to prefix to each line of the dump. + """ + perl_code = ( + 'use HTTP::Message; ' + 'my $m = HTTP::Message->parse($ARGV[0]); ' + 'print $m->dump(maxlength => $ARGV[1], no_content => $ARGV[2], prefix => $ARGV[3]);' + ) + + try: + result = subprocess.run( + ["perl", "-MHTTP::Message", "-e", perl_code, "--", raw_message, str(maxlength), no_content, prefix], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "HTTP::Message->dump", + "stdout": result.stdout, + "stderr": result.stderr, + "dump": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def http_message_decoded_content( + raw_message: str, + charset: Optional[str] = None, + default_charset: str = "ISO-8859-1", + alt_charset: Optional[str] = None, + charset_strict: bool = False, + raise_error: bool = False +): + """ + Returns the content of the message with Content-Encoding undone and character sets decoded. + + Args: + raw_message: The raw HTTP message string. + charset: Overrides the charset parameter for text content. + default_charset: Overrides the default guessed charset. + alt_charset: Fallback charset if the primary one fails. + charset_strict: If True, abort decoding on malformed characters. + raise_error: If True, raise an exception on failure. + """ + # Build options hash for Perl + options = [] + if charset: options.append(f'charset => "{charset}"') + options.append(f'default_charset => "{default_charset}"') + if alt_charset: options.append(f'alt_charset => "{alt_charset}"') + options.append(f'charset_strict => {"1" if charset_strict else "0"}') + options.append(f'raise_error => {"1" if raise_error else "0"}') + + opt_str = ", ".join(options) + perl_code = ( + 'use HTTP::Message; ' + 'my $m = HTTP::Message->parse($ARGV[0]); ' + f'my $c = $m->decoded_content({opt_str}); ' + 'print $c if defined $c;' + ) + + try: + result = subprocess.run( + ["perl", "-MHTTP::Message", "-e", perl_code, "--", raw_message], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "HTTP::Message->decoded_content", + "stdout": result.stdout, + "stderr": result.stderr, + "decoded_content": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def http_message_encode( + raw_message: str, + encoding: str = "gzip" +): + """ + Applies a specific encoding (e.g., gzip, deflate, base64) to the message content. + Returns the full message with the new encoding and updated headers. + + Args: + raw_message: The raw HTTP message string. + encoding: The encoding to apply (gzip, deflate, x-bzip2, base64, or br). + """ + valid_encodings = ["gzip", "deflate", "x-bzip2", "base64", "br", "identity"] + if encoding not in valid_encodings: + return {"error": f"Invalid encoding. Must be one of: {', '.join(valid_encodings)}"} + + perl_code = ( + 'use HTTP::Message; ' + 'my $m = HTTP::Message->parse($ARGV[0]); ' + 'if ($m->encode($ARGV[1])) { print $m->as_string; } ' + 'else { die "Encoding failed"; }' + ) + + try: + result = subprocess.run( + ["perl", "-MHTTP::Message", "-e", perl_code, "--", raw_message, encoding], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"HTTP::Message->encode('{encoding}')", + "stdout": result.stdout, + "stderr": result.stderr, + "encoded_message": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "error": "Encoding failed. Note: multipart/* or message/* cannot be encoded.", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def http_message_get_parts( + raw_message: str +): + """ + For composite messages (multipart/* or message/*), extracts and returns each part as a separate string. + + Args: + raw_message: The raw HTTP message string. + """ + perl_code = ( + 'use HTTP::Message; ' + 'my $m = HTTP::Message->parse($ARGV[0]); ' + 'my @parts = $m->parts; ' + 'foreach my $p (@parts) { print "---PART_BOUNDARY---\\n"; print $p->as_string; }' + ) + + try: + result = subprocess.run( + ["perl", "-MHTTP::Message", "-e", perl_code, "--", raw_message], + capture_output=True, + text=True, + check=True + ) + + parts = [] + if result.stdout: + # Split by boundary and filter out empty strings + parts = [p.strip() for p in result.stdout.split("---PART_BOUNDARY---\n") if p.strip()] + + return { + "command_executed": "HTTP::Message->parts", + "stdout": result.stdout, + "stderr": result.stderr, + "parts_count": len(parts), + "parts": parts + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def http_message_header_operations( + raw_message: str, + operation: str, + header_field: str, + header_value: Optional[str] = None +): + """ + Performs header manipulations on an HTTP message. + + Args: + raw_message: The raw HTTP message string. + operation: The operation to perform: 'get', 'set', 'push', 'remove'. + header_field: The name of the header field (e.g., 'Content-Type'). + header_value: The value to set or push (required for 'set' and 'push'). + """ + if operation not in ["get", "set", "push", "remove"]: + return {"error": "Invalid operation. Use 'get', 'set', 'push', or 'remove'."} + + if operation in ["set", "push"] and header_value is None: + return {"error": f"header_value is required for operation '{operation}'"} + + perl_logic = "" + if operation == "get": + perl_logic = 'print $m->header($ARGV[1]);' + elif operation == "set": + perl_logic = '$m->header($ARGV[1] => $ARGV[2]); print $m->as_string;' + elif operation == "push": + perl_logic = '$m->push_header($ARGV[1] => $ARGV[2]); print $m->as_string;' + elif operation == "remove": + perl_logic = '$m->remove_header($ARGV[1]); print $m->as_string;' + + perl_code = f'use HTTP::Message; my $m = HTTP::Message->parse($ARGV[0]); {perl_logic}' + + args = [raw_message, header_field] + if header_value: + args.append(header_value) + + try: + result = subprocess.run( + ["perl", "-MHTTP::Message", "-e", perl_code, "--"] + args, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"HTTP::Message header {operation}", + "stdout": result.stdout, + "stderr": result.stderr, + "result": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/app/perl-http-message_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/app/perl-http-message_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..31def820835675a8eae01e0bc0eb12baf8875f91 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/app/perl-http-message_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/app/perl-http-message_server.py') +SERVER_NAME = 'biosci_perl_http_message' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ba896d28a9571fb30ad68c3e44a7d18eade531a5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-http-message: + build: . + image: mcp-perl-http-message:latest + container_name: mcp-perl-http-message + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-http-message + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7e9d1da8d7bef49f854c85522090e0b102903509 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-http-message + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-message/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6b8d5bb23c9620ee247d54cb37141589c3b78733 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-http-negotiate via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-http-negotiate -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-http-negotiate_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-http-negotiate_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-http-negotiate_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/app/perl-http-negotiate_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/app/perl-http-negotiate_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9d25d730710ce2999a9472d5148f0920ffda563f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/app/perl-http-negotiate_server.py @@ -0,0 +1,186 @@ +import subprocess +import shlex +from pathlib import Path +from typing import Optional, List + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be imported. +def mcp_tool_placeholder(): + def decorator(func): + return func + return decorator + +mcp = type('MCP', (), {'tool': mcp_tool_placeholder}) + +@mcp.tool() +def run_perl( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + execute_program: Optional[List[str]] = None, + execute_program_with_features: Optional[List[str]] = None, + check_syntax_only: bool = False, + print_version: bool = False, + print_config: Optional[str] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + split_pattern: Optional[str] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + in_place_edit: Optional[str] = None, + line_ending_processing: Optional[str] = None, + include_directory: Optional[List[Path]] = None, + use_module: Optional[List[str]] = None, + no_module: Optional[List[str]] = None, + use_module_m: Optional[List[str]] = None, + no_module_m: Optional[List[str]] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + unicode_features: Optional[str] = None, + run_under_debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + parse_switches: bool = False, + search_path: bool = False, + dump_core: bool = False, + unsafe_operations: bool = False, + ignore_pre_hashbang_text: Optional[str] = None, +): + """ + Executes a script or command using the Perl interpreter. + + This tool is a wrapper for the generic 'perl' executable. The provided + documentation for 'perl-http-negotiate' indicates it is a library, not a + standalone command-line tool. This function therefore exposes the underlying + 'perl' interpreter, within an environment where 'perl-http-negotiate' is + available for use in scripts (e.g., 'use HTTP::Negotiate;'). + + Args: + programfile: Path to the Perl program file to execute. + arguments: A list of arguments to be passed to the program file. + execute_program: One or more lines of a program to be executed. Omit programfile. + execute_program_with_features: Like execute_program, but enables all optional features. + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). Corresponds to -c. + print_version: Print version, patchlevel, and license. Corresponds to -v. + print_config: Print configuration summary. Provide a variable name to see a single value. Corresponds to -V[:variable]. + record_separator: Specify record separator (e.g., an octal number). Corresponds to -0[octal]. + autosplit: Enable autosplit mode with -n or -p (splits $_ into @F). Corresponds to -a. + split_pattern: The pattern to use for splitting in autosplit mode. Corresponds to -F/pattern/. + loop_around_program: Assume "while (<>) { ... }" loop around the program. Corresponds to -n. + loop_and_print: Assume a loop like -n but also print the line, similar to sed. Corresponds to -p. + in_place_edit: Edit <> files in place. Provide an extension to make a backup. Corresponds to -i[extension]. + line_ending_processing: Enable line ending processing and specify the line terminator. Corresponds to -l[octal]. + include_directory: Specify @INC/#include directories. Multiple paths can be provided. Corresponds to -I. + use_module: Execute "use module..." before the program. Corresponds to -Mmodule. + no_module: Execute "no module..." before the program. Corresponds to -M-module. + use_module_m: Execute "use module..." before the program. Corresponds to -mmodule. + no_module_m: Execute "no module..." before the program. Corresponds to -m-module. + enable_warnings: Enable many useful warnings. Corresponds to -w. + enable_all_warnings: Enable all warnings. Corresponds to -W. + disable_all_warnings: Disable all warnings. Corresponds to -X. + tainting_warnings: Enable tainting warnings. Corresponds to -t. + tainting_checks: Enable tainting checks. Corresponds to -T. + unicode_features: Enable the listed Unicode features. Corresponds to -C[number/list]. + run_under_debugger: Run the program under the debugger. Provide a debugger name if needed. Corresponds to -d[:debugger]. + debugging_flags: Set debugging flags (argument is a bit mask or alphabets). Corresponds to -D[number/list]. + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. Corresponds to -f. + parse_switches: Enable rudimentary parsing for switches after the programfile. Corresponds to -s. + search_path: Look for the programfile using the PATH environment variable. Corresponds to -S. + dump_core: Dump core after parsing the program. Corresponds to -u. + unsafe_operations: Allow unsafe operations. Corresponds to -U. + ignore_pre_hashbang_text: Ignore text before #!perl line. Optionally provide a directory to cd into. Corresponds to -x[directory]. + """ + # --- Input Validation --- + execution_target_count = sum([ + programfile is not None, + execute_program is not None, + execute_program_with_features is not None, + print_version, + print_config is not None + ]) + if execution_target_count == 0: + raise ValueError("An execution target is required. Please provide one of 'programfile', 'execute_program', 'execute_program_with_features', 'print_version', or 'print_config'.") + if execution_target_count > 1 and not (print_version and programfile): # perl -v script.pl is valid + if not (print_version and (execute_program or execute_program_with_features)): + raise ValueError("Only one primary execution target ('programfile', 'execute_program', 'execute_program_with_features', 'print_config') can be specified at a time.") + + if programfile and not programfile.exists(): + raise FileNotFoundError(f"The specified program file does not exist: {programfile}") + + # --- Command Construction --- + cmd = ["perl"] + + if record_separator is not None: cmd.append(f"-0{record_separator}") + if autosplit: cmd.append("-a") + if unicode_features is not None: cmd.append(f"-C{unicode_features}") + if check_syntax_only: cmd.append("-c") + if run_under_debugger is not None: cmd.append(f"-d{':' if run_under_debugger else ''}{run_under_debugger}") + if debugging_flags is not None: cmd.append(f"-D{debugging_flags}") + if execute_program: + for prog_line in execute_program: cmd.extend(["-e", prog_line]) + if execute_program_with_features: + for prog_line in execute_program_with_features: cmd.extend(["-E", prog_line]) + if no_sitecustomize: cmd.append("-f") + if split_pattern is not None: cmd.append(f"-F{split_pattern}") + if in_place_edit is not None: cmd.append(f"-i{in_place_edit}") + if include_directory: + for directory in include_directory: cmd.extend(["-I", str(directory)]) + if line_ending_processing is not None: cmd.append(f"-l{line_ending_processing}") + if use_module: + for module in use_module: cmd.extend(["-M", module]) + if no_module: + for module in no_module: cmd.extend(["-M-", module]) + if use_module_m: + for module in use_module_m: cmd.extend(["-m", module]) + if no_module_m: + for module in no_module_m: cmd.extend(["-m-", module]) + if loop_around_program: cmd.append("-n") + if loop_and_print: cmd.append("-p") + if parse_switches: cmd.append("-s") + if search_path: cmd.append("-S") + if tainting_warnings: cmd.append("-t") + if tainting_checks: cmd.append("-T") + if dump_core: cmd.append("-u") + if unsafe_operations: cmd.append("-U") + if print_version: cmd.append("-v") + if print_config is not None: cmd.append(f"-V{':' if print_config else ''}{print_config}") + if enable_warnings: cmd.append("-w") + if enable_all_warnings: cmd.append("-W") + if ignore_pre_hashbang_text is not None: cmd.append(f"-x{ignore_pre_hashbang_text}") + if disable_all_warnings: cmd.append("-X") + + if programfile: + cmd.append(str(programfile)) + + if arguments: + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = shlex.join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + raise RuntimeError("The 'perl' executable was not found. Please ensure it is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + # Non-zero exit code is not necessarily an error for tools like this, + # but we return it structured for the user to decide. + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed with return code {e.returncode}.", + "output_files": [] + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/app/perl-http-negotiate_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/app/perl-http-negotiate_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..67332377ae551a7365da845050c44291ca920241 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/app/perl-http-negotiate_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/app/perl-http-negotiate_server.py') +SERVER_NAME = 'biosci_perl_http_negotiate' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e6b9a1b636ebe48f3f2ef3bd385afaa72df6295e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-http-negotiate: + build: . + image: mcp-perl-http-negotiate:latest + container_name: mcp-perl-http-negotiate + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-http-negotiate + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..82c6f3445aa230c6ff9baf1e4fc14bca2456ad4b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-http-negotiate + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-http-negotiate/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..01051f3910d24337130099ec8055312365ee7680 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-image-info via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-image-info -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-image-info_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-image-info_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-image-info_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/app/perl-image-info_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/app/perl-image-info_server.py new file mode 100644 index 0000000000000000000000000000000000000000..64d20737776db0ff996de8982898d5ec79ed266f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/app/perl-image-info_server.py @@ -0,0 +1,160 @@ +import subprocess +import tempfile +import json +from pathlib import Path +from typing import Dict, Any, List + +# Note: The execution of these tools requires a Perl environment with the +# Image::Info and JSON modules installed. The conda package `perl-image-info` +# provides Image::Info, and `perl-json` is a standard module usually +# available in modern Perl installations. + +@mcp.tool() +def get_image_info( + image_file: Path, +) -> Dict[str, Any]: + """ + Extracts detailed meta information from an image file using Perl's Image::Info module. + + This function wraps the `image_info` subroutine, returning a dictionary of metadata + including dimensions, color type, resolution, and format-specific information + (e.g., EXIF data for JPEGs). + + Args: + image_file: The path to the input image file. Supported formats include + AVIF, BMP, GIF, ICO, JPEG, PNG, PBM/PGM/PPM, SVG, TIFF, + WBMP, WEBP, XBM, and XPM. + + Returns: + A dictionary containing the command execution details and the extracted image metadata. + """ + if not image_file.is_file(): + raise FileNotFoundError(f"Input file not found: {image_file}") + + perl_script_content = f""" + use strict; + use warnings; + use Image::Info qw(image_info); + use JSON; + + my $file = shift @ARGV; + die "Usage: $0 \\n" unless defined $file; + + my $info = image_info($file); + + # Encode the resulting Perl hash reference to JSON for easy parsing in Python. + print encode_json($info); + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".pl", delete=True) as tmp_script: + tmp_script.write(perl_script_content) + tmp_script.flush() + + cmd = ["perl", tmp_script.name, str(image_file)] + command_executed = " ".join(cmd) + + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + + try: + metadata = json.loads(process.stdout) + except json.JSONDecodeError: + # This case handles if the script runs but outputs non-JSON text + raise ValueError(f"Failed to parse JSON output from Perl script. stdout: {process.stdout}") + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [], + "image_metadata": metadata + } + + except subprocess.CalledProcessError as e: + # This case handles if the perl script itself fails (e.g., file not found, module missing) + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"Perl script execution failed with return code {e.returncode}." + } + +@mcp.tool() +def get_image_type( + image_file: Path, +) -> Dict[str, Any]: + """ + Quickly determines the type of an image file using Perl's Image::Info module. + + This function wraps the `image_type` subroutine, which is a faster alternative + to get_image_info. It only identifies the file type (e.g., 'GIF', 'JPEG', 'PNG') + without parsing the full image structure. + + Args: + image_file: The path to the input image file. + + Returns: + A dictionary containing the command execution details and the determined image type. + """ + if not image_file.is_file(): + raise FileNotFoundError(f"Input file not found: {image_file}") + + perl_script_content = f""" + use strict; + use warnings; + use Image::Info qw(image_type); + use JSON; + + my $file = shift @ARGV; + die "Usage: $0 \\n" unless defined $file; + + my $type_info = image_type($file); + + # Encode the resulting Perl hash reference to JSON for easy parsing in Python. + print encode_json($type_info); + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".pl", delete=True) as tmp_script: + tmp_script.write(perl_script_content) + tmp_script.flush() + + cmd = ["perl", tmp_script.name, str(image_file)] + command_executed = " ".join(cmd) + + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + + try: + type_info = json.loads(process.stdout) + except json.JSONDecodeError: + raise ValueError(f"Failed to parse JSON output from Perl script. stdout: {process.stdout}") + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [], + "image_type_info": type_info + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"Perl script execution failed with return code {e.returncode}." + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/app/perl-image-info_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/app/perl-image-info_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ac1b4cd13bc025414c4ea78e2c21cd3663037b6b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/app/perl-image-info_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/app/perl-image-info_server.py') +SERVER_NAME = 'biosci_perl_image_info' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8fcc40e647a8a607d4a141d9f946b8a37b541da2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-image-info: + build: . + image: mcp-perl-image-info:latest + container_name: mcp-perl-image-info + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-image-info + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a62f79b1dba34d53737252beba75f1a48533dda9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-image-info + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-info/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e85541f17667c010fbbaada30c170c150858da9f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-image-size via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-image-size -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-image-size_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-image-size_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-image-size_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/app/perl-image-size_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/app/perl-image-size_server.py new file mode 100644 index 0000000000000000000000000000000000000000..da5781bf93a3735081bd6289a9e39226f46187c8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/app/perl-image-size_server.py @@ -0,0 +1,114 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, Any, Optional + +# from mcp import mcp + +@mcp.tool() +def image_size( + image_file: Path +) -> Dict[str, Any]: + """ + Determines the width and height of an image file using the Perl Image::Size library. + + This tool acts as a wrapper around the Perl 'Image::Size' module, which does not + provide a direct command-line executable. It dynamically creates and executes a + Perl script to extract the dimensions from the specified image file. + + Args: + image_file: The path to the input image file (e.g., JPG, PNG, GIF, etc.). + + Returns: + A dictionary containing the command executed, stdout, stderr, and the + parsed width and height of the image. + """ + # 1. Input validation + if not image_file.is_file(): + raise FileNotFoundError(f"Input file not found: {image_file}") + + # 2. Perl script content + # This script uses the Image::Size module to get dimensions and prints them + # to stdout in a "width,height" format for easy parsing. + perl_script_content = r""" + use strict; + use warnings; + use Image::Size; + + # Get the image file path from the command line arguments + my $file = shift @ARGV; + + # Basic validation within the script + die "Usage: $0 \n" unless defined $file; + die "File not found or is not a regular file: $file\n" unless -f $file; + + # Get the image size + my ($width, $height) = imgsize($file); + + # Print the result in a machine-readable format if successful + if (defined $width && defined $height) { + print "$width,$height\n"; + } else { + # Print a descriptive error message to stderr if size could not be determined + my $error_msg = Image::Size::errormsg(); + print STDERR "Could not determine size for '$file': $error_msg\n"; + exit 1; + } + """ + + command_to_run = [] + try: + # 3. Create a temporary file for the Perl script + with tempfile.NamedTemporaryFile(mode='w', delete=True, suffix=".pl", encoding='utf-8') as tmp_script: + tmp_script.write(perl_script_content) + tmp_script.flush() # Ensure all content is written to disk + + command_to_run = ['perl', tmp_script.name, str(image_file)] + + # 4. Subprocess execution + process = subprocess.run( + command_to_run, + capture_output=True, + text=True, + check=True + ) + + # 5. Parse the output + stdout_clean = process.stdout.strip() + if not stdout_clean: + raise ValueError("Perl script produced no output to stdout.") + + width_str, height_str = stdout_clean.split(',') + width = int(width_str) + height = int(height_str) + + # 6. Return structured result + return { + "command_executed": " ".join(command_to_run), + "stdout": process.stdout, + "stderr": process.stderr, + "width": width, + "height": height, + "output_files": [] + } + + except FileNotFoundError: + raise RuntimeError("The 'perl' command was not found. Is Perl installed and in your system's PATH?") + except subprocess.CalledProcessError as e: + # This catches errors when the Perl script returns a non-zero exit code + return { + "command_executed": " ".join(command_to_run), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Perl script execution failed with a non-zero exit code.", + "output_files": [] + } + except (ValueError, IndexError) as e: + # This catches errors if the stdout format is not "width,height" + return { + "command_executed": " ".join(command_to_run), + "stdout": process.stdout if 'process' in locals() else "", + "stderr": process.stderr if 'process' in locals() else "", + "error": f"Failed to parse Perl script output. Expected 'width,height', got '{stdout_clean}'. Details: {e}", + "output_files": [] + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/app/perl-image-size_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/app/perl-image-size_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7482dbe5f10b8cc0f202e65791230bd618d9aeac --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/app/perl-image-size_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/app/perl-image-size_server.py') +SERVER_NAME = 'biosci_perl_image_size' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ea360db949a356123325255905d6a1df2c49c518 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-image-size: + build: . + image: mcp-perl-image-size:latest + container_name: mcp-perl-image-size + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-image-size + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..957f2faa5f1ec2947f7e6cd91f6db1fb23184444 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-image-size + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-image-size/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e21e934802aaef34656fed68839e1e5f53b1ca62 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-importer via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-importer -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-importer_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-importer_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-importer_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/app/perl-importer_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/app/perl-importer_server.py new file mode 100644 index 0000000000000000000000000000000000000000..102ce12d0de381d066ed0f060c678c61b7cc8e70 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/app/perl-importer_server.py @@ -0,0 +1,237 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def install_perl_module( + module_name: str, + notest: bool = True, + force: bool = False, + local_lib: Optional[str] = None, + sudo: bool = False, +): + """ + Installs Perl modules using cpanm (App::cpanminus), a common requirement for + bioinformatics pipelines (e.g., BioPerl, VCFtools). + """ + # Input validation + if not module_name: + return {"error": "Module name must be provided"} + + command = [] + if sudo: + command.append("sudo") + + command.extend(["cpanm", module_name]) + + if notest: + command.append("--notest") + if force: + command.append("--force") + if local_lib: + lib_path = Path(local_lib) + command.extend(["-l", str(lib_path.absolute())]) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Installation failed with exit code {e.returncode}" + } + except FileNotFoundError: + return {"error": "cpanm is not installed on the system. Please install App::cpanminus."} + +@mcp.tool() +def execute_perl_script( + script_path: str, + args: Optional[List[str]] = None, + perl5lib: Optional[str] = None, + include_path: Optional[str] = None, + warnings: bool = True, +): + """ + Executes a Perl script with specified arguments and environment variables. + Commonly used for running BioPerl scripts or custom bioinformatics parsers. + """ + script = Path(script_path) + if not script.exists(): + return {"error": f"Script not found at {script_path}"} + + command = ["perl"] + if warnings: + command.append("-w") + if include_path: + command.extend(["-I", include_path]) + + command.append(str(script.absolute())) + + if args: + command.extend(args) + + env = {} + if perl5lib: + env["PERL5LIB"] = perl5lib + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + env=env if env else None + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] # Perl scripts often output to stdout unless redirected + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Script execution failed with exit code {e.returncode}" + } + +@mcp.tool() +def check_perl_syntax( + script_path: str, + include_path: Optional[str] = None, +): + """ + Performs a syntax check on a Perl script (perl -c). + Useful for validating bioinformatics scripts before long-running pipeline execution. + """ + script = Path(script_path) + if not script.exists(): + return {"error": f"Script not found at {script_path}"} + + command = ["perl", "-c"] + if include_path: + command.extend(["-I", include_path]) + command.append(str(script.absolute())) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "valid": True + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "valid": False, + "error": "Syntax check failed" + } + +@mcp.tool() +def list_installed_perl_modules( + search_term: Optional[str] = None, +): + """ + Lists installed Perl modules or searches for a specific module. + Helps verify if bioinformatics dependencies like Bio::Seq or Bio::DB::Fasta are available. + """ + # Using perldoc -l is a reliable way to find module paths + if search_term: + command = ["perldoc", "-l", search_term] + else: + # Fallback to listing all modules via instmodsh (part of ExtUtils::Installed) + # This is a bit complex in shell, so we use a perl one-liner + command = ["perl", "-MExtUtils::Installed", "-e", "print join('\\n', ExtUtils::Installed->new()->modules())"] + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(command), + "installed_modules": result.stdout.splitlines(), + "stdout": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stderr": e.stderr, + "error": "Could not retrieve module list. Ensure ExtUtils::Installed is available." + } + +@mcp.tool() +def bioperl_load_gff( + gff_file: str, + database_name: str, + db_type: str = "sqlite", + create: bool = True, + user: Optional[str] = None, + password: Optional[str] = None, +): + """ + Specialized importer tool for BioPerl's bp_seqfeature_load.pl. + Imports GFF3/GTF files into a SeqFeature database (SQLite, MySQL, or PostgreSQL). + """ + gff_path = Path(gff_file) + if not gff_path.exists(): + return {"error": f"GFF file not found: {gff_file}"} + + # Constructing the bp_seqfeature_load.pl command + command = ["bp_seqfeature_load.pl", "-d", database_name, "-f", db_type] + + if create: + command.append("-c") + if user: + command.extend(["-u", user]) + if password: + command.extend(["-p", password]) + + command.append(str(gff_path.absolute())) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "database": database_name, + "status": "Import completed" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"BioPerl GFF import failed: {e.stderr}" + } + except FileNotFoundError: + return {"error": "bp_seqfeature_load.pl not found. Is BioPerl installed?"} \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/app/perl-importer_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/app/perl-importer_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..84653a6bf5148647b48f5b2fbdd2b8ebad452605 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/app/perl-importer_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/app/perl-importer_server.py') +SERVER_NAME = 'biosci_perl_importer' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c7567e20b08ae22c47460f9f6c83554e2dc65c3f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-importer: + build: . + image: mcp-perl-importer:latest + container_name: mcp-perl-importer + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-importer + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dadb85fc3ebe13a606226fe218ba4cde9de05a44 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-importer + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-importer/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d8711dd8bd631915008f7a7fa77f05f19914ce98 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-io-compress via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-io-compress -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-io-compress_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-io-compress_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-io-compress_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/app/perl-io-compress_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/app/perl-io-compress_server.py new file mode 100644 index 0000000000000000000000000000000000000000..74ddcdc48af992fbd360ac3e57453bb6216a3588 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/app/perl-io-compress_server.py @@ -0,0 +1,225 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Union + +# This is a placeholder for the actual decorator. +# In a real MCP environment, you would use: +# from mcp import tool as mcp_tool +def mcp_tool_placeholder(): + def decorator(f): + return f + return decorator + +mcp = type("MCP", (), {"tool": mcp_tool_placeholder}) + + +@mcp.tool() +def run_perl( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + program: Optional[str] = None, + program_e_features: Optional[str] = None, + check_syntax_only: bool = False, + print_version: bool = False, + print_config: Optional[str] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + in_place_edit: Optional[str] = None, + include_dirs: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + use_module: Optional[List[str]] = None, + no_module: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + parse_switches: bool = False, + search_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core: bool = False, + unsafe_operations: bool = False, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + ignore_text_before_hashbang: Optional[Path] = None, +) -> Dict[str, Union[str, List[str]]]: + """ + Executes a Perl program using an environment that includes the IO::Compress library. + + This tool is a wrapper for the Perl interpreter. It allows you to run Perl scripts + or one-liners, leveraging the installed Perl modules like IO::Compress for tasks + such as file compression and decompression. + + Args: + programfile: Path to the Perl program file to execute. + arguments: A list of arguments to pass to the program file. + program: A one-liner program string to execute (equivalent to -e). + program_e_features: Like 'program', but enables all optional features (-E). + check_syntax_only: Check syntax only; runs BEGIN and CHECK blocks (-c). + print_version: Print Perl version, patchlevel, and license (-v). + print_config: Print configuration summary or a single variable (-V[:variable]). + record_separator: Specify record separator, e.g., '0777' for slurp mode (-0). + autosplit: Enable autosplit mode with -n or -p (splits $_ into @F) (-a). + unicode_features: Enable listed Unicode features (-C). + debugger: Run the program under the specified debugger (-d[:debugger]). + debugging_flags: Set debugging flags (-D). + no_sitecustomize: Don't run $sitelib/sitecustomize.pl at startup (-f). + split_pattern: Specify the split() pattern for the -a switch (-F). + in_place_edit: Edit files in place. Provide an extension for backup (-i). + include_dirs: List of directories to add to @INC (-I). + line_ending_processing: Enable line ending processing (-l). + use_module: Execute 'use module...' before the program (-M). + no_module: Execute 'no module...' before the program (-m). + loop_around_program: Assume 'while (<>) { ... }' loop around the program (-n). + loop_and_print: Like -n, but also prints the line (-p). + parse_switches: Enable rudimentary parsing for switches after programfile (-s). + search_path: Look for programfile using the PATH environment variable (-S). + tainting_warnings: Enable tainting warnings (-t). + tainting_checks: Enable tainting checks (-T). + dump_core: Dump core after parsing the program (-u). + unsafe_operations: Allow unsafe operations (-U). + enable_warnings: Enable many useful warnings (-w). + enable_all_warnings: Enable all warnings (-W). + disable_all_warnings: Disable all warnings (-X). + ignore_text_before_hashbang: Ignore text before #!perl line and optionally cd (-x). + + Returns: + A dictionary containing the executed command, stdout, stderr, and output files. + """ + # --- Input Validation --- + program_sources = [programfile, program, program_e_features] + if sum(p is not None for p in program_sources) > 1: + raise ValueError("Only one of 'programfile', 'program', or 'program_e_features' can be specified.") + + is_action = any([ + programfile, + program, + program_e_features, + check_syntax_only, + print_version, + print_config is not None + ]) + if not is_action: + raise ValueError("No action specified. Provide a script, or set an action like 'check_syntax_only' or 'print_version'.") + + warning_flags = [enable_warnings, enable_all_warnings, disable_all_warnings] + if sum(warning_flags) > 1: + raise ValueError("The warning flags -w, -W, and -X are mutually exclusive.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"Program file not found: {programfile}") + + if include_dirs: + for directory in include_dirs: + if not directory.is_dir(): + raise NotADirectoryError(f"Include directory not found: {directory}") + + # --- Command Construction --- + cmd = ["perl"] + + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if debugger is not None: + cmd.append(f"-d{debugger}") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if program: + cmd.extend(["-e", program]) + if program_e_features: + cmd.extend(["-E", program_e_features]) + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.extend(["-F", split_pattern]) + if in_place_edit is not None: + cmd.append(f"-i{in_place_edit}") + if include_dirs: + for directory in include_dirs: + cmd.extend(["-I", str(directory)]) + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + if use_module: + for mod in use_module: + cmd.extend(["-M", mod]) + if no_module: + for mod in no_module: + cmd.extend(["-m", mod]) + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if parse_switches: + cmd.append("-s") + if search_path: + cmd.append("-S") + if tainting_warnings: + cmd.append("-t") + if tainting_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config is not None: + cmd.append(f"-V{print_config}") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if ignore_text_before_hashbang: + cmd.extend(["-x", str(ignore_text_before_hashbang)]) + if disable_all_warnings: + cmd.append("-X") + + if programfile: + cmd.append(str(programfile)) + + if arguments: + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + return { + "error": "Perl executable not found. Please ensure it is in your PATH.", + "command_executed": command_executed, + "stdout": "", + "stderr": "", + } + except subprocess.CalledProcessError as e: + return { + "error": "Perl script execution failed.", + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [] # This tool primarily operates on stdout/stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/app/perl-io-compress_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/app/perl-io-compress_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e334965b1e14794348bb7fd28569680370ee8cef --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/app/perl-io-compress_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/app/perl-io-compress_server.py') +SERVER_NAME = 'biosci_perl_io_compress' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..71acefbee1b4cd952c256b97fcb42ad88c57a27f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-io-compress: + build: . + image: mcp-perl-io-compress:latest + container_name: mcp-perl-io-compress + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-io-compress + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ec64a2665abe6dae6725c976c0ecf9c8d492fffe --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-io-compress + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..89d3c482c3ba55f7d1334e2163d7c54cea9ad674 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-io-html via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-io-html -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-io-html_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-io-html_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-io-html_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/app/perl-io-html_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/app/perl-io-html_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f8025ab5c8ca377b4a6afd432832e723906c2aed --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/app/perl-io-html_server.py @@ -0,0 +1,165 @@ +import subprocess +from pathlib import Path +from typing import Optional, Dict, Any + +@mcp.tool() +def io_html_get_encoding( + file_path: str, +) -> Dict[str, Any]: + """ + Detects the character encoding of an HTML file using the HTML5 sniffing algorithm. + This is equivalent to the IO::HTML::html_file_and_encoding function. + + Args: + file_path: Path to the HTML file to analyze. + """ + path = Path(file_path) + if not path.exists(): + return {"error": f"File not found: {file_path}"} + if not path.is_file(): + return {"error": f"Path is not a file: {file_path}"} + + # Perl script to extract encoding and BOM status + # html_file_and_encoding returns ($filehandle, $encoding, $bom) + perl_cmd = [ + "perl", + "-MIO::HTML", + "-e", + 'my ($fh, $enc, $bom) = IO::HTML::html_file_and_encoding($ARGV[0]); ' + 'print "encoding:$enc\\n"; ' + 'print "bom:" . ($bom ? "true" : "false") . "\\n";', + str(path) + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(perl_cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "detected_info": result.stdout.strip().split('\n') + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(perl_cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def io_html_read_content( + file_path: str, +) -> Dict[str, Any]: + """ + Opens an HTML file with the correctly detected encoding and returns its content. + This ensures that the HTML is read using the charset specified in the tags or BOM. + + Args: + file_path: Path to the HTML file to read. + """ + path = Path(file_path) + if not path.exists(): + return {"error": f"File not found: {file_path}"} + + # Perl script to open file with IO::HTML and print content to stdout + # We use binmode STDOUT :utf8 to ensure the output is passed correctly to the shell + perl_cmd = [ + "perl", + "-MIO::HTML", + "-e", + 'my $fh = IO::HTML::html_file($ARGV[0]); ' + 'binmode(STDOUT, ":utf8"); ' + 'while(<$fh>){ print $_; }', + str(path) + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(perl_cmd), + "content": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(perl_cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def io_html_sniff_encoding( + html_content: str, +) -> Dict[str, Any]: + """ + Sniffs the encoding from a string of HTML content. + Useful for detecting encoding of HTML data already in memory or from a stream. + + Args: + html_content: The raw HTML string/bytes to analyze for encoding. + """ + # We pass the content via a temporary file or stdin to avoid shell argument length limits + # Here we use a simple perl one-liner that takes the string as an argument + perl_cmd = [ + "perl", + "-MIO::HTML", + "-e", + 'my $encoding = IO::HTML::sniff_encoding($ARGV[0]); ' + 'print $encoding;', + html_content + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return { + "command_executed": "perl -MIO::HTML -e '...sniff_encoding...'", + "detected_encoding": result.stdout.strip(), + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": "perl -MIO::HTML -e '...sniff_encoding...'", + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def io_html_check_compatibility( + file_path: str, +) -> Dict[str, Any]: + """ + Checks if the IO::HTML module is correctly installed and can process the target file. + This is a diagnostic tool for the environment. + + Args: + file_path: Path to a sample HTML file. + """ + path = Path(file_path) + + perl_cmd = [ + "perl", + "-MIO::HTML", + "-e", + 'print "IO::HTML version: $IO::HTML::VERSION\\n"; ' + 'eval { IO::HTML::html_file($ARGV[0]) }; ' + 'if ($@) { print "Error: $@"; exit 1; } else { print "Status: OK\\n"; }', + str(path) if path.exists() else "" + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(perl_cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(perl_cmd), + "error": "Module IO::HTML might not be installed or file is inaccessible.", + "stdout": e.stdout, + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/app/perl-io-html_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/app/perl-io-html_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c98d8db73ac65e4d292dee2e347084b53269f4bd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/app/perl-io-html_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/app/perl-io-html_server.py') +SERVER_NAME = 'biosci_perl_io_html' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e8d588e44df8502d977f5fa6820119ac52ee8318 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-io-html: + build: . + image: mcp-perl-io-html:latest + container_name: mcp-perl-io-html + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-io-html + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cac91f069c11d84b42c72b87cfe6d73303945a06 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-io-html + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-html/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..442a78cf3d70630f6fcba6328976befb2d742ad4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-io-sessiondata via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-io-sessiondata -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-io-sessiondata_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-io-sessiondata_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-io-sessiondata_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/app/perl-io-sessiondata_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/app/perl-io-sessiondata_server.py new file mode 100644 index 0000000000000000000000000000000000000000..eac6d2e3dc8c219594f05d59684f4b384a1f4862 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/app/perl-io-sessiondata_server.py @@ -0,0 +1,255 @@ +from typing import Optional, List +import subprocess +from pathlib import Path + +@mcp.tool() +def perl_execute_script( + script_path: str, + arguments: Optional[str] = None, + modules: Optional[str] = None, + include_dirs: Optional[str] = None, + warning_level: str = "none", + taint_check: str = "none", + autosplit: bool = False, + split_pattern: Optional[str] = None, + inplace_extension: Optional[str] = None, + loop_mode: str = "none", + line_ending_processing: bool = False, + record_separator: Optional[str] = None, +): + """ + Executes a Perl script file. This tool can be used to run scripts that utilize + the perl-io-sessiondata (IO::SessionData) module. + + Args: + script_path: Path to the Perl script (.pl) to execute. + arguments: Command-line arguments to pass to the script. + modules: Comma-separated list of modules to load (e.g., "IO::SessionData,JSON"). + include_dirs: Comma-separated list of directories to add to @INC. + warning_level: Warning level to set ('none', 'many' [-w], 'all' [-W], 'disable' [-X]). + taint_check: Taint checking mode ('none', 'warnings' [-t], 'checks' [-T]). + autosplit: Enable autosplit mode [-a] (used with loop_mode). + split_pattern: Pattern for autosplit [-F]. + inplace_extension: Extension for in-place editing backup [-i]. + loop_mode: Iteration mode ('none', 'n' [while(<>)], 'p' [while(<>) + print]). + line_ending_processing: Enable line ending processing [-l]. + record_separator: Specify record separator [-0]. + """ + script_file = Path(script_path) + if not script_file.exists(): + return {"error": f"Script file not found: {script_path}"} + + cmd = ["perl"] + + # Warning levels + if warning_level == "many": + cmd.append("-w") + elif warning_level == "all": + cmd.append("-W") + elif warning_level == "disable": + cmd.append("-X") + + # Taint checks + if taint_check == "warnings": + cmd.append("-t") + elif taint_check == "checks": + cmd.append("-T") + + # Modules (-M) + if modules: + for mod in modules.split(","): + cmd.extend(["-M", mod.strip()]) + + # Include directories (-I) + if include_dirs: + for d in include_dirs.split(","): + cmd.append(f"-I{d.strip()}") + + # Loop modes and autosplit + if loop_mode == "n": + cmd.append("-n") + elif loop_mode == "p": + cmd.append("-p") + + if autosplit: + cmd.append("-a") + if split_pattern: + cmd.append(f"-F{split_pattern}") + + # File processing + if inplace_extension is not None: + cmd.append(f"-i{inplace_extension}") + if line_ending_processing: + cmd.append("-l") + if record_separator: + cmd.append(f"-0{record_separator}") + + cmd.append(str(script_file)) + + if arguments: + cmd.extend(arguments.split()) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def perl_execute_inline( + code: str, + arguments: Optional[str] = None, + modules: Optional[str] = "IO::SessionData", + use_all_features: bool = False, + warning_level: str = "none", + loop_mode: str = "none", + autosplit: bool = False, +): + """ + Executes a Perl one-liner command. + + Args: + code: The Perl code to execute (passed to -e or -E). + arguments: Arguments to pass to the code. + modules: Comma-separated list of modules to load (defaults to IO::SessionData). + use_all_features: Use -E instead of -e to enable all optional features. + warning_level: Warning level ('none', 'many', 'all', 'disable'). + loop_mode: Iteration mode ('none', 'n', 'p'). + autosplit: Enable autosplit mode [-a]. + """ + cmd = ["perl"] + + if warning_level == "many": + cmd.append("-w") + elif warning_level == "all": + cmd.append("-W") + elif warning_level == "disable": + cmd.append("-X") + + if modules: + for mod in modules.split(","): + cmd.extend(["-M", mod.strip()]) + + if loop_mode == "n": + cmd.append("-n") + elif loop_mode == "p": + cmd.append("-p") + + if autosplit: + cmd.append("-a") + + if use_all_features: + cmd.extend(["-E", code]) + else: + cmd.extend(["-e", code]) + + if arguments: + cmd.extend(arguments.split()) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def perl_check_syntax( + script_path: Optional[str] = None, + code: Optional[str] = None, + modules: Optional[str] = "IO::SessionData", +): + """ + Checks the syntax of a Perl script or code string without executing it (-c). + + Args: + script_path: Path to a script file to check. + code: Inline code string to check. + modules: Modules to load during the check. + """ + cmd = ["perl", "-c"] + + if modules: + for mod in modules.split(","): + cmd.extend(["-M", mod.strip()]) + + if script_path: + script_file = Path(script_path) + if not script_file.exists(): + return {"error": f"File not found: {script_path}"} + cmd.append(str(script_file)) + elif code: + cmd.extend(["-e", code]) + else: + return {"error": "Either script_path or code must be provided."} + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "syntax_ok" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Syntax check failed", + "status": "syntax_error" + } + +@mcp.tool() +def perl_get_info( + show_config: bool = False, + config_variable: Optional[str] = None, +): + """ + Returns Perl version and configuration information. + + Args: + show_config: If True, returns full configuration summary [-V]. + config_variable: If provided, returns the value of a specific Config.pm variable [-V:var]. + """ + if config_variable: + cmd = ["perl", f"-V:{config_variable}"] + elif show_config: + cmd = ["perl", "-V"] + else: + cmd = ["perl", "-v"] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "status": "error" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/app/perl-io-sessiondata_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/app/perl-io-sessiondata_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ee660111d14213292e4d644f3b3d2fa7580a19ba --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/app/perl-io-sessiondata_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/app/perl-io-sessiondata_server.py') +SERVER_NAME = 'biosci_perl_io_sessiondata' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4209c8a4abb6f8c071a2a9fa496bfb592dc58291 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-io-sessiondata: + build: . + image: mcp-perl-io-sessiondata:latest + container_name: mcp-perl-io-sessiondata + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-io-sessiondata + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..89133a2f1489cf918344a3179aa526bd8f24ca92 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-io-sessiondata + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-sessiondata/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8c0e5e57affdf3c7ef45f13177100de2a5af8975 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-io-socket-ssl via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-io-socket-ssl -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-io-socket-ssl_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-io-socket-ssl_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-io-socket-ssl_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/app/perl-io-socket-ssl_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/app/perl-io-socket-ssl_server.py new file mode 100644 index 0000000000000000000000000000000000000000..005cd37e7106388e4e011d7aad875076f7b27c47 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/app/perl-io-socket-ssl_server.py @@ -0,0 +1,197 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be imported. +class _MCP: + def tool(self, *args, **kwargs): + def decorator(func): + return func + return decorator +mcp = _MCP() + +@mcp.tool() +def run_perl( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + execute_program: Optional[List[str]] = None, + execute_program_features: Optional[List[str]] = None, + check_syntax_only: bool = False, + record_separator: Optional[str] = None, + autosplit: bool = False, + split_pattern: Optional[str] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + line_ending_processing: Optional[str] = None, + in_place_edit: Optional[str] = None, + include_directory: Optional[List[Path]] = None, + use_modules: Optional[List[str]] = None, + no_modules: Optional[List[str]] = None, + no_sitecustomize: bool = False, + search_path: bool = False, + run_under_debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + allow_unsafe: bool = False, + print_version: bool = False, + print_config: Optional[str] = None, + unicode_features: Optional[str] = None, + enable_switch_parsing: bool = False, + dump_core: bool = False, + ignore_pre_hashbang_text: bool = False, + cd_directory_for_x: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Executes the Perl interpreter with specified options and scripts. + + This tool wraps the `perl` command-line interpreter. The `perl-io-socket-ssl` + package is a Perl module, not a standalone tool. This function provides a + way to run Perl scripts that may utilize the IO::Socket::SSL module. + + Args: + programfile: Path to the Perl program file to execute. + arguments: A list of arguments to be passed to the program file. + execute_program: One or more lines of a program to be executed (-e). + execute_program_features: Like -e, but enables all optional features (-E). + check_syntax_only: Check syntax only; does not execute the program (-c). + record_separator: Specify the record separator character, as an octal value (-0). + autosplit: Enable autosplit mode when used with -n or -p (-a). + split_pattern: Specify the pattern for splitting in autosplit mode (-F). + loop_around_program: Assume a 'while (<>) { ... }' loop around the program (-n). + loop_and_print: Assume a loop like -n but also print the line (-p). + line_ending_processing: Enable line-ending processing with an optional octal terminator (-l). + in_place_edit: Edit files in place, with an optional backup extension (-i). + include_directory: Add directories to Perl's @INC search path (-I). + use_modules: Execute 'use module...' before the program (-M). Prefix with '-' to disable default imports. + no_modules: Execute 'no module...' before the program (-m). + no_sitecustomize: Don't run $sitelib/sitecustomize.pl at startup (-f). + search_path: Look for the programfile in the PATH environment variable (-S). + run_under_debugger: Run the program under the specified debugger (-d). + debugging_flags: Set debugging flags from a bit mask or letters (-D). + enable_warnings: Enable many useful warnings (-w). + enable_all_warnings: Enable all warnings (-W). + disable_all_warnings: Disable all warnings (-X). + tainting_warnings: Enable tainting warnings (-t). + tainting_checks: Enable tainting checks for security (-T). + allow_unsafe: Allow unsafe operations (-U). + print_version: Print the version, patchlevel, and license of Perl (-v). + print_config: Print configuration summary or a single variable (-V). + unicode_features: Enable listed Unicode features (-C). + enable_switch_parsing: Enable rudimentary parsing for switches after the programfile (-s). + dump_core: Dump core after parsing the program (-u). + ignore_pre_hashbang_text: Ignore text before a #!perl line (-x). + cd_directory_for_x: When using -x, change to this directory before execution. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + # --- Input Validation --- + informational_run = print_version or (print_config is not None) + if not programfile and not execute_program and not execute_program_features and not informational_run: + raise ValueError( + "Either a programfile, an executable string (-e or -E), or an " + "informational flag (-v or -V) must be provided." + ) + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"The specified program file does not exist: {programfile}") + + if cd_directory_for_x and not cd_directory_for_x.is_dir(): + raise NotADirectoryError(f"The specified directory for -x does not exist: {cd_directory_for_x}") + + if include_directory: + for d in include_directory: + if not d.is_dir(): + raise NotADirectoryError(f"The specified include directory does not exist: {d}") + + # --- Command Construction --- + cmd = ["perl"] + + if record_separator is not None: cmd.append(f"-0{record_separator}") + if autosplit: cmd.append("-a") + if unicode_features is not None: cmd.append(f"-C{unicode_features}") + if check_syntax_only: cmd.append("-c") + if run_under_debugger is not None: cmd.append(f"-d{run_under_debugger}") + if debugging_flags is not None: cmd.append(f"-D{debugging_flags}") + if execute_program: + for prog in execute_program: cmd.extend(["-e", prog]) + if execute_program_features: + for prog in execute_program_features: cmd.extend(["-E", prog]) + if no_sitecustomize: cmd.append("-f") + if split_pattern is not None: cmd.extend(["-F", split_pattern]) + if in_place_edit is not None: cmd.append(f"-i{in_place_edit}") + if include_directory: + for d in include_directory: cmd.extend(["-I", str(d)]) + if line_ending_processing is not None: cmd.append(f"-l{line_ending_processing}") + if use_modules: + for mod in use_modules: cmd.extend(["-M", mod]) + if no_modules: + for mod in no_modules: cmd.extend(["-m", mod]) + if loop_around_program: cmd.append("-n") + if loop_and_print: cmd.append("-p") + if enable_switch_parsing: cmd.append("-s") + if search_path: cmd.append("-S") + if tainting_warnings: cmd.append("-t") + if tainting_checks: cmd.append("-T") + if dump_core: cmd.append("-u") + if allow_unsafe: cmd.append("-U") + if print_version: cmd.append("-v") + if print_config is not None: cmd.append(f"-V{print_config}") + if enable_warnings: cmd.append("-w") + if enable_all_warnings: cmd.append("-W") + if cd_directory_for_x: cmd.extend(["-x", str(cd_directory_for_x)]) + elif ignore_pre_hashbang_text: cmd.append("-x") + if disable_all_warnings: cmd.append("-X") + + if programfile: + cmd.append("--") + cmd.append(str(programfile)) + + if arguments: + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except FileNotFoundError: + raise RuntimeError("The 'perl' executable was not found. Please ensure it is installed and in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"Perl execution failed with return code {e.returncode}" + } + + # --- Structured Result Return --- + output_files = [] + if in_place_edit is not None and arguments: + for arg_str in arguments: + arg_path = Path(arg_str) + if arg_path.is_file(): + # The file that was edited in-place is an output file + output_files.append(str(arg_path)) + # If an extension was provided, a backup file may have been created + if in_place_edit: + backup_file = Path(f"{arg_str}{in_place_edit}") + if backup_file.exists(): + output_files.append(str(backup_file)) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/app/perl-io-socket-ssl_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/app/perl-io-socket-ssl_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..70d0df4b9b757b3ee9ee8f66fc0d46352bdf8d78 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/app/perl-io-socket-ssl_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/app/perl-io-socket-ssl_server.py') +SERVER_NAME = 'biosci_perl_io_socket_ssl' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3517564a3c845d50868dda4eb6e9f0f668d2ccea --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-io-socket-ssl: + build: . + image: mcp-perl-io-socket-ssl:latest + container_name: mcp-perl-io-socket-ssl + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-io-socket-ssl + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7c00a89387b71299716ed178f37aa622e99072a2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-io-socket-ssl + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-socket-ssl/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5682fd4236f0836b450b71c7d3fb5640c9176b2c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-io-string via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-io-string -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-io-string_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-io-string_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-io-string_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/app/perl-io-string_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/app/perl-io-string_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c6256d2d67b05e52cf1eb9867ec2f59d3145243b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/app/perl-io-string_server.py @@ -0,0 +1,202 @@ +from typing import Optional, List +import subprocess +from pathlib import Path +import tempfile + +@mcp.tool() +def perl_execute( + program_code: Optional[str] = None, + program_file: Optional[str] = None, + arguments: Optional[List[str]] = None, + modules: Optional[List[str]] = ["IO::String"], + autosplit: bool = False, + split_pattern: Optional[str] = None, + syntax_check_only: bool = False, + inplace_extension: Optional[str] = None, + include_dirs: Optional[List[str]] = None, + line_ending_processing: bool = False, + loop_stdin: bool = False, + loop_stdin_print: bool = False, + warnings: bool = False, + all_warnings: bool = False, + record_separator: Optional[str] = None, + unicode_features: Optional[str] = None, +): + """ + Execute Perl code with the IO::String module available. + IO::String allows emulating a file interface for in-core strings. + + Args: + program_code: One line of program (equivalent to -e). + program_file: Path to a Perl script file to execute. + arguments: Arguments passed to the script. + modules: List of modules to execute 'use module...' before the program (equivalent to -M). Defaults to ['IO::String']. + autosplit: Enable autosplit mode with -n or -p (splits $_ into @F) (equivalent to -a). + split_pattern: split() pattern for -a switch (equivalent to -F). + syntax_check_only: Check syntax only (runs BEGIN and CHECK blocks) (equivalent to -c). + inplace_extension: Edit <> files in place, optionally making a backup with the supplied extension (equivalent to -i). + include_dirs: Specify @INC/#include directories (equivalent to -I). + line_ending_processing: Enable line ending processing, specifies line terminator (equivalent to -l). + loop_stdin: Assume "while (<>) { ... }" loop around program (equivalent to -n). + loop_stdin_print: Assume loop like -n but print line also (equivalent to -p). + warnings: Enable many useful warnings (equivalent to -w). + all_warnings: Enable all warnings (equivalent to -W). + record_separator: Specify record separator (equivalent to -0). + unicode_features: Enables the listed Unicode features (equivalent to -C). + """ + + command = ["perl"] + + # Handle switches + if record_separator is not None: + command.append(f"-0{record_separator}") + + if autosplit: + command.append("-a") + + if unicode_features: + command.append(f"-C{unicode_features}") + + if syntax_check_only: + command.append("-c") + + if split_pattern: + command.append(f"-F{split_pattern}") + + if inplace_extension is not None: + command.append(f"-i{inplace_extension}") + + if include_dirs: + for d in include_dirs: + command.append(f"-I{d}") + + if line_ending_processing: + command.append("-l") + + if modules: + for m in modules: + command.append(f"-M{m}") + + if loop_stdin: + command.append("-n") + + if loop_stdin_print: + command.append("-p") + + if warnings: + command.append("-w") + + if all_warnings: + command.append("-W") + + # Handle program input + if program_code and program_file: + raise ValueError("Cannot provide both program_code and program_file.") + + if program_code: + command.extend(["-e", program_code]) + elif program_file: + p_file = Path(program_file) + if not p_file.exists(): + return {"error": f"Program file not found: {program_file}"} + command.append(str(p_file)) + else: + # If neither is provided, we might be expecting code via stdin or just checking version + # But for this tool, we'll assume at least one is needed unless it's a version check + pass + + # Append arguments + if arguments: + command.extend(arguments) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def perl_version(): + """ + Print the version, patchlevel, and license of the Perl interpreter. + """ + command = ["perl", "-v"] + try: + result = subprocess.run(command, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def perl_config_summary(variable: Optional[str] = None): + """ + Print a configuration summary for the Perl interpreter or a single Config.pm variable. + + Args: + variable: A specific Config.pm variable to query (e.g., 'archname'). + """ + command = ["perl"] + if variable: + command.append(f"-V:{variable}") + else: + command.append("-V") + + try: + result = subprocess.run(command, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def perl_io_string_example(): + """ + Returns a sample Perl snippet demonstrating how to use IO::String to treat a string as a file. + This is useful for users unfamiliar with the module's syntax. + """ + example_code = """ +use IO::String; +my $data = "Hello\\nWorld\\nBioinformatics"; +my $io = IO::String->new($data); +while (<$io>) { + print "Line $.: $_"; +} +""" + return { + "example_description": "Reading from a string as if it were a file handle.", + "code": example_code, + "usage_instruction": "Pass this code to the perl_execute tool's program_code parameter." + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/app/perl-io-string_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/app/perl-io-string_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..000c10e972b8f4e48478174d7a298ffadbc79148 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/app/perl-io-string_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/app/perl-io-string_server.py') +SERVER_NAME = 'biosci_perl_io_string' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e4f835cf8ef424fa0068cc0afb649fcfe5f8adc2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-io-string: + build: . + image: mcp-perl-io-string:latest + container_name: mcp-perl-io-string + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-io-string + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dea1437faea88d9daca340a235c91faf140f6a7c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-io-string + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-string/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bbedfa72f62bc5fb685365ada4b4471cd0dd4eaa --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-io-stringy via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-io-stringy -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-io-stringy_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-io-stringy_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-io-stringy_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/app/perl-io-stringy_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/app/perl-io-stringy_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e8d6f7aee6a12f20c4d73027e2577f2ab7a70182 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/app/perl-io-stringy_server.py @@ -0,0 +1,232 @@ +from typing import Optional, List +import subprocess +from pathlib import Path + +@mcp.tool() +def perl_execute( + script_path: Optional[str] = None, + one_liner: Optional[str] = None, + one_liner_extended: Optional[str] = None, + args: Optional[List[str]] = None, + modules: Optional[List[str]] = None, + include_dirs: Optional[List[str]] = None, + autosplit: bool = False, + split_pattern: Optional[str] = None, + loop_lines: bool = False, + loop_lines_print: bool = False, + inplace_edit_extension: Optional[str] = None, + record_separator: Optional[str] = None, + line_ending_processing: Optional[str] = None, + unicode_features: Optional[str] = None, + syntax_check_only: bool = False, + taint_checks: bool = False, + taint_warnings: bool = False, + warning_level: str = "default", + path_search: bool = False, + switch_parsing: bool = False, +): + """ + Execute Perl code or scripts using the Perl interpreter. + This tool allows running Perl logic, including modules like IO::Stringy for in-memory I/O. + + Args: + script_path: Path to the Perl script file to execute. + one_liner: One line of program (equivalent to -e). + one_liner_extended: Like -e, but enables all optional features (equivalent to -E). + args: Arguments to pass to the Perl script. + modules: List of modules to 'use' before executing (equivalent to -M). + include_dirs: List of directories to add to @INC (equivalent to -I). + autosplit: Enable autosplit mode with -n or -p (equivalent to -a). + split_pattern: Pattern for -a switch (equivalent to -F). + loop_lines: Assume "while (<>) { ... }" loop around program (equivalent to -n). + loop_lines_print: Assume loop like -n but print line also (equivalent to -p). + inplace_edit_extension: Edit files in place, optionally providing a backup extension (equivalent to -i). + record_separator: Specify record separator (equivalent to -0). + line_ending_processing: Enable line ending processing (equivalent to -l). + unicode_features: Enable listed Unicode features (equivalent to -C). + syntax_check_only: Check syntax only without executing (equivalent to -c). + taint_checks: Enable tainting checks (equivalent to -T). + taint_warnings: Enable tainting warnings (equivalent to -t). + warning_level: Warning level: 'default' (-w), 'all' (-W), or 'none' (-X). + path_search: Look for programfile using PATH environment variable (equivalent to -S). + switch_parsing: Enable rudimentary parsing for switches after programfile (equivalent to -s). + """ + cmd = ["perl"] + + # Handle Record Separator + if record_separator is not None: + cmd.append(f"-0{record_separator}") + + # Handle Autosplit + if autosplit: + cmd.append("-a") + + if split_pattern: + cmd.append(f"-F{split_pattern}") + + # Handle Unicode + if unicode_features: + cmd.append(f"-C{unicode_features}") + + # Handle Syntax Check + if syntax_check_only: + cmd.append("-c") + + # Handle Warnings + if warning_level == "all": + cmd.append("-W") + elif warning_level == "none": + cmd.append("-X") + elif warning_level == "default": + cmd.append("-w") + + # Handle Tainting + if taint_checks: + cmd.append("-T") + elif taint_warnings: + cmd.append("-t") + + # Handle In-place editing + if inplace_edit_extension is not None: + cmd.append(f"-i{inplace_edit_extension}") + + # Handle Include Directories + if include_dirs: + for d in include_dirs: + cmd.append(f"-I{d}") + + # Handle Modules + if modules: + for m in modules: + cmd.append(f"-M{m}") + + # Handle Line Ending + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + + # Handle Loops + if loop_lines: + cmd.append("-n") + if loop_lines_print: + cmd.append("-p") + + # Handle Path Search and Switch Parsing + if path_search: + cmd.append("-S") + if switch_parsing: + cmd.append("-s") + + # Handle Program Execution (One-liner vs Script) + if one_liner: + cmd.extend(["-e", one_liner]) + elif one_liner_extended: + cmd.extend(["-E", one_liner_extended]) + elif script_path: + p = Path(script_path) + if not p.exists(): + return {"error": f"Script file not found: {script_path}"} + cmd.append(str(p)) + else: + # If no script or one-liner, we might just be checking version or config + pass + + # Append arguments + if args: + cmd.extend(args) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def perl_version(): + """ + Print the Perl version, patchlevel, and license information. + """ + cmd = ["perl", "-v"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def perl_config_summary(variable: Optional[str] = None): + """ + Print a configuration summary for the Perl interpreter or a specific Config.pm variable. + + Args: + variable: Specific configuration variable to query (e.g., 'archname', 'osname'). + """ + cmd = ["perl"] + if variable: + cmd.append(f"-V:{variable}") + else: + cmd.append("-V") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def perl_io_stringy_example(): + """ + Provides a template/example of how to use IO::Scalar from the perl-io-stringy package + to treat a string as a filehandle. + """ + perl_code = ( + "use IO::Scalar;\n" + "$data = \"\";\n" + "$SH = new IO::Scalar \\$data;\n" + "$SH->print(\"Hello, this is written to a string handle!\\n\");\n" + "print \"Resulting string: $data\";" + ) + + cmd = ["perl", "-e", perl_code] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "example_code": perl_code, + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "description": "Demonstrates using IO::Scalar to write to a string variable as if it were a file." + } + except subprocess.CalledProcessError as e: + return { + "error": "Ensure perl-io-stringy is installed in the environment.", + "stderr": e.stderr, + "status": "error" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/app/perl-io-stringy_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/app/perl-io-stringy_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0e5da7080d82c6435ca904c5026e37bdaf75fa14 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/app/perl-io-stringy_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/app/perl-io-stringy_server.py') +SERVER_NAME = 'biosci_perl_io_stringy' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ab8d326c85a0bbdb6e546956235f1656ab1fce44 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-io-stringy: + build: . + image: mcp-perl-io-stringy:latest + container_name: mcp-perl-io-stringy + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-io-stringy + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..666033383081e040930ba7b08cc63a7bca04f4ee --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-io-stringy + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-stringy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..027925733250192911345e302f7353c5f931c04c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-io-tty via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-io-tty -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-io-tty_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-io-tty_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-io-tty_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/app/perl-io-tty_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/app/perl-io-tty_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9b5b08d39c166335afbc435742c36297474e1b05 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/app/perl-io-tty_server.py @@ -0,0 +1,197 @@ +import subprocess +import shlex +from pathlib import Path +from typing import Optional, List, Dict, Any + +# This is a placeholder for the mcp.tool decorator. +# In a real MCP environment, you would import it. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +@mcp.tool() +def run_perl( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + execute_line: Optional[List[str]] = None, + execute_line_with_features: Optional[List[str]] = None, + record_separator_octal: Optional[str] = None, + autosplit: bool = False, + autosplit_pattern: Optional[str] = None, + assume_while_loop: bool = False, + assume_print_loop: bool = False, + enable_line_ending_processing: Optional[str] = None, + edit_in_place_backup_ext: Optional[str] = None, + add_include_directory: Optional[List[Path]] = None, + use_module: Optional[List[str]] = None, + check_syntax_only: bool = False, + run_under_debugger: Optional[str] = None, + set_debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + enable_switch_parsing: bool = False, + search_program_in_path: bool = False, + enable_taint_warnings: bool = False, + enable_taint_checks: bool = False, + dump_core_after_parse: bool = False, + allow_unsafe_ops: bool = False, + print_version_info: bool = False, + print_config_variable: Optional[str] = None, + enable_many_warnings: bool = False, + enable_all_warnings_W: bool = False, + disable_all_warnings_X: bool = False, + extract_script_from_message: bool = False, + extract_script_cd_dir: Optional[Path] = None, + enable_unicode_features: Optional[str] = None, +) -> Dict[str, Any]: + """ + Executes a script using the Perl interpreter. + + This tool wraps the `perl` command-line interpreter. The original request was for `perl-io-tty`, + which is a Perl module and does not have its own command-line interface. This tool therefore + exposes the functionality of the `perl` executable itself, allowing for the execution of + Perl scripts and one-liners. + """ + # --- Input Validation --- + if programfile and (execute_line or execute_line_with_features): + raise ValueError("Cannot specify 'programfile' with 'execute_line' or 'execute_line_with_features'.") + if not programfile and not execute_line and not execute_line_with_features and not print_version_info and print_config_variable is None: + raise ValueError("Either 'programfile', 'execute_line', 'execute_line_with_features', 'print_version_info', or 'print_config_variable' must be provided.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"Program file not found: {programfile}") + + if add_include_directory: + for directory in add_include_directory: + if not directory.is_dir(): + raise FileNotFoundError(f"Include directory not found: {directory}") + + if autosplit_pattern and not (assume_while_loop or assume_print_loop): + raise ValueError("'autosplit_pattern' (-F) requires 'assume_while_loop' (-n) or 'assume_print_loop' (-p).") + + if extract_script_cd_dir and not extract_script_from_message: + raise ValueError("'extract_script_cd_dir' can only be used when 'extract_script_from_message' is True.") + + # --- Command Construction --- + cmd = ["perl"] + + if record_separator_octal is not None: + cmd.append(f"-0{record_separator_octal}") + if autosplit: + cmd.append("-a") + if enable_unicode_features is not None: + cmd.append(f"-C{enable_unicode_features}") + if check_syntax_only: + cmd.append("-c") + if run_under_debugger is not None: + cmd.append(f"-d{run_under_debugger}") + if set_debugging_flags is not None: + cmd.append(f"-D{set_debugging_flags}") + if no_sitecustomize: + cmd.append("-f") + if autosplit_pattern is not None: + cmd.append(f"-F{autosplit_pattern}") + if edit_in_place_backup_ext is not None: + cmd.append(f"-i{edit_in_place_backup_ext}") + if add_include_directory: + for directory in add_include_directory: + cmd.extend(["-I", str(directory)]) + if enable_line_ending_processing is not None: + cmd.append(f"-l{enable_line_ending_processing}") + if use_module: + for mod in use_module: + # Handles -Mmodule, -mmodule, -M-module, etc. + if mod.startswith('m') or mod.startswith('M'): + cmd.append(f"-{mod}") + else: + cmd.append(f"-M{mod}") + # -p overrides -n + if assume_print_loop: + cmd.append("-p") + elif assume_while_loop: + cmd.append("-n") + if enable_switch_parsing: + cmd.append("-s") + if search_program_in_path: + cmd.append("-S") + if enable_taint_warnings: + cmd.append("-t") + if enable_taint_checks: + cmd.append("-T") + if dump_core_after_parse: + cmd.append("-u") + if allow_unsafe_ops: + cmd.append("-U") + if print_version_info: + cmd.append("-v") + if print_config_variable is not None: + cmd.append(f"-V{print_config_variable}") + if enable_many_warnings: + cmd.append("-w") + if enable_all_warnings_W: + cmd.append("-W") + if extract_script_cd_dir: + cmd.extend(["-x", str(extract_script_cd_dir)]) + elif extract_script_from_message: + cmd.append("-x") + if disable_all_warnings_X: + cmd.append("-X") + + if execute_line: + for line in execute_line: + cmd.extend(["-e", line]) + if execute_line_with_features: + for line in execute_line_with_features: + cmd.extend(["-E", line]) + + if programfile: + cmd.append(str(programfile)) + + if arguments: + cmd.append("--") + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = shlex.join(cmd) + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Is Perl installed and in the system's PATH?", + "return_code": 1, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "output_files": [] + } + + # --- Output Handling --- + output_files = [] + if edit_in_place_backup_ext is not None and edit_in_place_backup_ext != "" and arguments: + for arg_file in arguments: + p = Path(arg_file) + if p.is_file(): + backup_file = p.with_name(f"{p.name}{edit_in_place_backup_ext}") + output_files.append(str(backup_file)) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "return_code": result.returncode, + "output_files": output_files + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/app/perl-io-tty_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/app/perl-io-tty_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..97c8ec6ffe505958b9b36bff721a5bd119fc1a65 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/app/perl-io-tty_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/app/perl-io-tty_server.py') +SERVER_NAME = 'biosci_perl_io_tty' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2b879424d36a9b888c2e5e67b813945cb8252b14 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-io-tty: + build: . + image: mcp-perl-io-tty:latest + container_name: mcp-perl-io-tty + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-io-tty + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3906ae0af6b53a0df5ee6307274426d6c382ac19 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-io-tty + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d0191230145a5d527c79af261975410eb25bdf6c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-io-zlib via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-io-zlib -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-io-zlib_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-io-zlib_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-io-zlib_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/app/perl-io-zlib_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/app/perl-io-zlib_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3d99a0f5f0192aadbc01ec4a979607a8504ebcbe --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/app/perl-io-zlib_server.py @@ -0,0 +1,230 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict, Any + +# In a real MCP environment, this would be: from mcp import tool +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def compress_file( + input_file: Path, + output_file: Path, + compression_level: Optional[int] = None, + use_external_gzip: Optional[bool] = None, +) -> Dict[str, Any]: + """ + Compresses a file using the IO::Zlib Perl module. + + This tool provides the core writing/compression functionality of IO::Zlib, + allowing for specified compression levels and control over using an + external gzip executable. + + Args: + input_file: Path to the input file to be compressed. + output_file: Path to the output compressed file (e.g., file.gz). + compression_level: The compression level to use, from 1 (fastest) to 9 (best). + If not provided, the default level is used. + use_external_gzip: Explicitly control the use of an external gzip command. + If True, forces use of external gzip. + If False, forces use of the internal Compress::Zlib module. + If not provided (default), IO::Zlib will attempt to use + Compress::Zlib and fall back to external gzip if needed. + """ + # --- Input Validation --- + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + if compression_level is not None and not (1 <= compression_level <= 9): + raise ValueError("compression_level must be between 1 and 9.") + + # --- Perl Script Generation --- + mode = "wb" + if compression_level is not None: + mode = f"wb{compression_level}" + + use_line = "use IO::Zlib;" + if use_external_gzip is True: + use_line = "use IO::Zlib qw(:gzip_external 1);" + elif use_external_gzip is False: + use_line = "use IO::Zlib qw(:gzip_external 0);" + + perl_script_content = f""" + use strict; + use warnings; + {use_line} + + my ($input_path, $output_path, $open_mode) = @ARGV; + die "Usage: perl_script.pl \\n" unless @ARGV == 3; + + open(my $in_fh, '<:raw', $input_path) + or die "Cannot open input file '$input_path': $!\\n"; + + my $out_fh = IO::Zlib->new($output_path, $open_mode) + or die "Cannot open output file '$output_path' for compression: $!\\n"; + + my $buffer; + while (read($in_fh, $buffer, 8192)) {{ + print $out_fh $buffer; + }} + + close $in_fh; + close $out_fh; + """ + + # --- Subprocess Execution --- + command = [] + stdout_str, stderr_str = "", "" + script_path = None + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".pl", delete=False) as temp_script: + temp_script.write(perl_script_content) + script_path = temp_script.name + + command = [ + "perl", + script_path, + str(input_file), + str(output_file), + mode, + ] + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + stdout_str = process.stdout + stderr_str = process.stderr + + except FileNotFoundError: + # This error is raised if 'perl' is not found in the system's PATH. + raise RuntimeError("Perl executable not found. Please ensure Perl is installed and in your PATH.") + except subprocess.CalledProcessError as e: + # This error is caught when the Perl script returns a non-zero exit code. + return { + "error": "Perl script execution failed.", + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + finally: + # Clean up the temporary script file + if script_path and Path(script_path).exists(): + Path(script_path).unlink() + + # --- Structured Result Return --- + return { + "command_executed": " ".join(command), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": [str(output_file)] if output_file.exists() else [], + } + +@mcp.tool +def decompress_file( + input_file: Path, + output_file: Path, + use_external_gzip: Optional[bool] = None, +) -> Dict[str, Any]: + """ + Decompresses a gzipped file using the IO::Zlib Perl module. + + This tool provides the core reading/decompression functionality of IO::Zlib, + allowing control over using an external gzip executable. + + Args: + input_file: Path to the input gzipped file (e.g., file.gz). + output_file: Path to the output decompressed file. + use_external_gzip: Explicitly control the use of an external gzip command. + If True, forces use of external gzip. + If False, forces use of the internal Compress::Zlib module. + If not provided (default), IO::Zlib will attempt to use + Compress::Zlib and fall back to external gzip if needed. + """ + # --- Input Validation --- + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + # --- Perl Script Generation --- + use_line = "use IO::Zlib;" + if use_external_gzip is True: + use_line = "use IO::Zlib qw(:gzip_external 1);" + elif use_external_gzip is False: + use_line = "use IO::Zlib qw(:gzip_external 0);" + + perl_script_content = f""" + use strict; + use warnings; + {use_line} + + my ($input_path, $output_path) = @ARGV; + die "Usage: perl_script.pl \\n" unless @ARGV == 2; + + my $in_fh = IO::Zlib->new($input_path, "rb") + or die "Cannot open input file '$input_path' for decompression: $!\\n"; + + open(my $out_fh, '>:raw', $output_path) + or die "Cannot open output file '$output_path': $!\\n"; + + my $buffer; + while (read($in_fh, $buffer, 8192)) {{ + print $out_fh $buffer; + }} + + close $in_fh; + close $out_fh; + """ + + # --- Subprocess Execution --- + command = [] + stdout_str, stderr_str = "", "" + script_path = None + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".pl", delete=False) as temp_script: + temp_script.write(perl_script_content) + script_path = temp_script.name + + command = [ + "perl", + script_path, + str(input_file), + str(output_file), + ] + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + stdout_str = process.stdout + stderr_str = process.stderr + + except FileNotFoundError: + raise RuntimeError("Perl executable not found. Please ensure Perl is installed and in your PATH.") + except subprocess.CalledProcessError as e: + return { + "error": "Perl script execution failed.", + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + finally: + # Clean up the temporary script file + if script_path and Path(script_path).exists(): + Path(script_path).unlink() + + # --- Structured Result Return --- + return { + "command_executed": " ".join(command), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": [str(output_file)] if output_file.exists() else [], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/app/perl-io-zlib_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/app/perl-io-zlib_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..03e8cf2bb784facc350297a7069ce7aa509baa2d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/app/perl-io-zlib_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/app/perl-io-zlib_server.py') +SERVER_NAME = 'biosci_perl_io_zlib' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..9eac4a4a27edbca68b3f67c081ea4e17489add26 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-io-zlib: + build: . + image: mcp-perl-io-zlib:latest + container_name: mcp-perl-io-zlib + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-io-zlib + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..50042d93782825750588e3f23c5a6cdf59c24e4f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-io-zlib + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-zlib/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6054beb464bb28305abca1b0e1a23494e1b59af0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-ipc-cmd via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-ipc-cmd -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-ipc-cmd_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-ipc-cmd_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-ipc-cmd_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/app/perl-ipc-cmd_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/app/perl-ipc-cmd_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5b38787fd18f6464c6408bc11ef30d45396bb0ad --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/app/perl-ipc-cmd_server.py @@ -0,0 +1,215 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# This is a placeholder for the MCP decorator. +# In a real environment, it would be imported. +class mcp: + def tool(name: Optional[str] = None, description: Optional[str] = None): + def decorator(f): + return f + return decorator + +@mcp.tool(name="perl-ipc-cmd.perl", description="Run the Perl interpreter with specified options and scripts.") +def perl( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + execute_lines: Optional[List[str]] = None, + execute_lines_with_features: Optional[List[str]] = None, + record_separator_octal: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + run_under_debugger: bool = False, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + autosplit_pattern: Optional[str] = None, + inplace_edit_extension: Optional[str] = None, + include_dirs: Optional[List[Path]] = None, + use_module_M: Optional[List[str]] = None, + use_module_m: Optional[List[str]] = None, + no_module_M: Optional[List[str]] = None, + no_module_m: Optional[List[str]] = None, + assume_loop: bool = False, + assume_loop_and_print: bool = False, + parse_switches_after_program: bool = False, + search_path_for_program: bool = False, + taint_warnings: bool = False, + taint_checks: bool = False, + dump_core: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_pre_shebang_text: Optional[str] = None, + disable_all_warnings: bool = False +) -> Dict[str, Any]: + """ + Executes the Perl interpreter. This tool wraps the `perl` command-line interface. + + Args: + programfile: Path to the Perl program file to execute. + arguments: A list of arguments to be passed to the program file. + execute_lines: Specifies one or more lines of a program using -e. Omit programfile. + execute_lines_with_features: Like -e, but enables all optional features (-E). Omit programfile. + record_separator_octal: Specify record separator (-0[octal]). + autosplit: Enable autosplit mode with -n or -p (-a). + unicode_features: Enable listed Unicode features (-C[number/list]). + check_syntax_only: Check syntax only; runs BEGIN and CHECK blocks (-c). + run_under_debugger: Run the program under the debugger (-d). + debugging_flags: Set debugging flags (-D[number/list]). + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup (-f). + autosplit_pattern: Specify the split() pattern for the -a switch (-F/pattern/). + inplace_edit_extension: Edit <> files in place (-i[extension]). Makes a backup if an extension is supplied. + include_dirs: Specify @INC/#include directories (-I). + use_module_M: Execute "use module..." before executing the program (-Mmodule). + use_module_m: Execute "use module..." before executing the program (-mmodule). + no_module_M: Execute "no module..." before executing the program (-M-module). + no_module_m: Execute "no module..." before executing the program (-m-module). + assume_loop: Assume a "while (<>) { ... }" loop around the program (-n). + assume_loop_and_print: Assume a loop like -n but also print the line (-p). + parse_switches_after_program: Enable rudimentary parsing for switches after the programfile (-s). + search_path_for_program: Look for the programfile using the PATH environment variable (-S). + taint_warnings: Enable tainting warnings (-t). + taint_checks: Enable tainting checks (-T). + dump_core: Dump core after parsing the program (-u). + allow_unsafe_operations: Allow unsafe operations (-U). + print_version: Print version, patchlevel, and license (-v). + print_config_summary: Print configuration summary (-V[:variable]). Provide an empty string for the full summary. + enable_warnings: Enable many useful warnings (-w). + enable_all_warnings: Enable all warnings (-W). + ignore_pre_shebang_text: Ignore text before #!perl line, optionally cd to a directory (-x[directory]). + disable_all_warnings: Disable all warnings (-X). + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if (execute_lines or execute_lines_with_features) and programfile: + raise ValueError("Cannot specify both 'programfile' and 'execute_lines'/'execute_lines_with_features'.") + + if not (execute_lines or execute_lines_with_features or programfile or print_version or print_config_summary is not None): + raise ValueError("Either a 'programfile', 'execute_lines', 'execute_lines_with_features', 'print_version', or 'print_config_summary' must be provided.") + + if programfile and not programfile.exists(): + raise FileNotFoundError(f"The specified program file does not exist: {programfile}") + + if autosplit_pattern and not autosplit: + raise ValueError("'autosplit_pattern' (-F) can only be used with 'autosplit' (-a).") + + if assume_loop and assume_loop_and_print: + raise ValueError("'assume_loop' (-n) and 'assume_loop_and_print' (-p) are mutually exclusive. -p implies -n.") + + # --- Command Construction --- + cmd = ["perl"] + + if record_separator_octal is not None: + cmd.append(f"-0{record_separator_octal}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if run_under_debugger: + cmd.append("-d") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if no_sitecustomize: + cmd.append("-f") + if autosplit_pattern is not None: + cmd.append(f"-F{autosplit_pattern}") + if inplace_edit_extension is not None: + cmd.append(f"-i{inplace_edit_extension}") + if include_dirs: + for directory in include_dirs: + cmd.extend(["-I", str(directory)]) + if use_module_M: + for module in use_module_M: + cmd.append(f"-M{module}") + if use_module_m: + for module in use_module_m: + cmd.append(f"-m{module}") + if no_module_M: + for module in no_module_M: + cmd.append(f"-M-{module}") + if no_module_m: + for module in no_module_m: + cmd.append(f"-m-{module}") + if assume_loop: + cmd.append("-n") + if assume_loop_and_print: + cmd.append("-p") + if parse_switches_after_program: + cmd.append("-s") + if search_path_for_program: + cmd.append("-S") + if taint_warnings: + cmd.append("-t") + if taint_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if allow_unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config_summary is not None: + if print_config_summary: + cmd.append(f"-V:{print_config_summary}") + else: + cmd.append("-V") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if ignore_pre_shebang_text is not None: + cmd.append(f"-x{ignore_pre_shebang_text}") + if disable_all_warnings: + cmd.append("-X") + + if execute_lines: + for line in execute_lines: + cmd.extend(["-e", line]) + if execute_lines_with_features: + for line in execute_lines_with_features: + cmd.extend(["-E", line]) + + if programfile: + cmd.append(str(programfile)) + + if arguments: + if programfile or execute_lines or execute_lines_with_features: + cmd.append("--") + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/app/perl-ipc-cmd_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/app/perl-ipc-cmd_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..217ba02d990aa0f15a55eb4d9d1d3bb5ff9ade1c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/app/perl-ipc-cmd_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/app/perl-ipc-cmd_server.py') +SERVER_NAME = 'biosci_perl_ipc_cmd' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..231f624cbd35f89e90b153d9b95d77a03a8208ab --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-ipc-cmd: + build: . + image: mcp-perl-ipc-cmd:latest + container_name: mcp-perl-ipc-cmd + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-ipc-cmd + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dacba3d974c3dcd08afaf6920241321eb6602b8a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-ipc-cmd + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-cmd/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-run/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-run/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-run/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc5746aecc6df4b80b7769aaf1371af3117e0749 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-ipc-sharelite via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-ipc-sharelite -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-ipc-sharelite_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-ipc-sharelite_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-ipc-sharelite_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/app/perl-ipc-sharelite_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/app/perl-ipc-sharelite_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1072b4411036fd4c1d976c3746f108a7abde04b7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/app/perl-ipc-sharelite_server.py @@ -0,0 +1,167 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +# IMPORTANT NOTE: +# perl-ipc-sharelite is a Perl module for inter-process communication using shared memory. +# It is NOT a standalone command-line tool with subcommands or a direct executable. +# Therefore, it cannot be "converted" into an MCP tool in the traditional sense +# of wrapping its command-line interface. +# +# The following MCP tool is a *hypothetical* wrapper for a Perl script that +# *uses* the IPC::ShareLite module. It demonstrates how one would wrap a Perl script +# if such a script were provided and exposed a command-line interface. +# This implementation assumes the existence of a Perl script that takes +# certain arguments and utilizes IPC::ShareLite internally. +# +# Since there are no command-line functions or subcommands to extract from +# the perl-ipc-sharelite module itself, a single generic function is provided +# to execute a hypothetical Perl script that would leverage this module. + +@mcp.tool() +def run_perl_sharelite_script( + perl_script_path: Path, + input_data: Optional[str] = None, + output_file: Optional[Path] = None, + shared_memory_key: Optional[int] = None, + shared_memory_size: Optional[int] = None, + additional_args: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Executes a Perl script that hypothetically uses the IPC::ShareLite module. + + This function serves as a placeholder to demonstrate how a Perl script, + which internally leverages the IPC::ShareLite module for shared memory + operations, could be wrapped as an MCP tool. It is important to note that + IPC::ShareLite itself is a Perl module and not a command-line executable. + + Args: + perl_script_path: Path to the Perl script to be executed. This script + is expected to use IPC::ShareLite internally. + input_data: Optional string data to be passed to the Perl script's stdin. + output_file: Optional path where the Perl script should write its output. + If not provided, stdout will be captured. + shared_memory_key: Optional integer key to be passed to the Perl script, + which it might use to identify a shared memory segment. + Must be a non-negative integer. + shared_memory_size: Optional integer size (in bytes) to be passed to the + Perl script, which it might use to create/resize + a shared memory segment. Must be a positive integer. + additional_args: Optional list of additional string arguments to pass + directly to the Perl script. + + Returns: + A dictionary containing the command executed, stdout, stderr, and + a list of any output files generated. + """ + # 1. Input validation + if not perl_script_path.is_file(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Perl script not found at '{perl_script_path}'.", + "output_files": [], + "error": "FileNotFoundError", + } + + if output_file: + if output_file.is_dir(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Output file path '{output_file}' is a directory.", + "output_files": [], + "error": "IsADirectoryError", + } + # Ensure the parent directory for the output file exists + output_file.parent.mkdir(parents=True, exist_ok=True) + + # 2. Construct the command + command = ["perl", str(perl_script_path)] + + if shared_memory_key is not None: + if not isinstance(shared_memory_key, int) or shared_memory_key < 0: + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Invalid shared_memory_key: {shared_memory_key}. Must be a non-negative integer.", + "output_files": [], + "error": "ValueError", + } + command.extend(["--key", str(shared_memory_key)]) + + if shared_memory_size is not None: + if not isinstance(shared_memory_size, int) or shared_memory_size <= 0: + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Invalid shared_memory_size: {shared_memory_size}. Must be a positive integer.", + "output_files": [], + "error": "ValueError", + } + command.extend(["--size", str(shared_memory_size)]) + + if output_file: + command.extend(["--output", str(output_file)]) + + if additional_args: + # Ensure all additional arguments are strings + if not all(isinstance(arg, str) for arg in additional_args): + return { + "command_executed": "", + "stdout": "", + "stderr": "Error: All elements in 'additional_args' must be strings.", + "output_files": [], + "error": "TypeError", + } + command.extend(additional_args) + + # 3. Subprocess execution + stdin_input = input_data.encode("utf-8") if input_data else None + + try: + process = subprocess.run( + command, + input=stdin_input, + capture_output=True, + text=True, # Decode stdout/stderr as text + check=True, # Raise CalledProcessError for non-zero exit codes + ) + stdout = process.stdout + stderr = process.stderr + output_files_generated: List[str] = [] + if output_file and output_file.is_file(): + output_files_generated.append(str(output_file)) + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files_generated, + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your system's PATH.", + "output_files": [], + "error": "PerlNotFound", + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr if e.stderr else f"Perl script exited with non-zero status {e.returncode}.", + "output_files": [], + "error": "CalledProcessError", + "returncode": e.returncode, + } + except Exception as e: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": f"An unexpected error occurred: {str(e)}", + "output_files": [], + "error": "UnexpectedError", + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/app/perl-ipc-sharelite_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/app/perl-ipc-sharelite_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3b95b23f643d57df771bc142f7e0050c1511c074 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/app/perl-ipc-sharelite_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/app/perl-ipc-sharelite_server.py') +SERVER_NAME = 'biosci_perl_ipc_sharelite' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..bca5e10f6e7e872a9026dfaf110dd03b8c3f376d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-ipc-sharelite: + build: . + image: mcp-perl-ipc-sharelite:latest + container_name: mcp-perl-ipc-sharelite + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-ipc-sharelite + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3907162055b2119ce854df7a7da2325fbff5ef39 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-ipc-sharelite + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ipc-sharelite/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cb0f5a69f6c618662b2242272b953dbc1e5124b7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-jcode via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-jcode -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-jcode_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-jcode_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-jcode_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/app/perl-jcode_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/app/perl-jcode_server.py new file mode 100644 index 0000000000000000000000000000000000000000..88a9e06d9489dea3f7568a83a311a6ca61e8129b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/app/perl-jcode_server.py @@ -0,0 +1,232 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +# No need to import mcp, as per instructions. + +@mcp.tool() +def execute_perl_program( + program_file: Optional[Path] = None, + program_arguments: Optional[List[str]] = None, + program_string: Optional[List[str]] = None, + program_string_extended: Optional[List[str]] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debug_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + use_module_before_program: Optional[List[str]] = None, + use_module_strict_before_program: Optional[List[str]] = None, + no_module_before_program: Optional[List[str]] = None, + loop_around_program: bool = False, + print_loop_around_program: bool = False, + rudimentary_switch_parsing: bool = False, + search_programfile_in_path: bool = False, + enable_tainting_warnings: bool = False, + enable_tainting_checks: bool = False, + dump_core_after_parsing: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang_dir: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> dict: + """ + Executes a Perl program with specified command-line switches. + + This tool wraps the 'perl' interpreter, allowing users to run Perl scripts + or one-liners with various configuration and debugging options. + It provides access to the core 'perl' command-line functionality, + which is the environment for running Perl modules like 'perl-jcode'. + + Parameters: + program_file: Path to the Perl program file to execute. + program_arguments: List of arguments to pass to the Perl program. + program_string: A list of Perl program lines to execute from the command line (using -e). + Multiple -e switches are allowed. + program_string_extended: A list of Perl program lines to execute from the command line (using -E). + Like -e, but enables all optional features. Multiple -E switches are allowed. + record_separator: Specify record separator. If an empty string (""), it defaults to \\0. + Example: "0" for \\0, "77" for octal 077. + autosplit: Enable autosplit mode with -n or -p (splits $_ into @F). + unicode_features: Enables the listed Unicode features (number or list). + Example: "all", "io", "say". + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). + debugger: Run program under debugger. Optionally specify debugger name (e.g., "MyDebugger"). + If an empty string (""), it enables the default debugger (-d). + debug_flags: Set debugging flags (argument is a bit mask or alphabets). + Example: "t" for trace, "s" for single step. + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. + split_pattern: split() pattern for -a switch (e.g., "/\\s+/"). Requires 'autosplit' to be true. + edit_in_place_extension: Edit <> files in place. If an extension is supplied (e.g., ".bak"), + it makes a backup. If an empty string (""), it edits in place without backup (-i). + include_directories: Specify @INC/#include directories. Multiple -I's allowed. + line_ending_processing: Enable line ending processing, specifies line terminator. + If an empty string (""), it enables line ending processing with default terminator (-l). + Example: "0" for octal 0. + use_module_before_program: Execute "use module..." before executing program (using -m). + Multiple modules can be specified. Example: ["Jcode", "strict"]. + use_module_strict_before_program: Execute "use module..." before executing program, with strict (using -M). + Multiple modules can be specified. Example: ["Jcode", "warnings"]. + no_module_before_program: Execute "no module..." before executing program (using -M-). + Multiple modules can be specified. Example: ["warnings"]. + loop_around_program: Assume "while (<>) { ... }" loop around program (using -n). + print_loop_around_program: Assume loop like -n but print line also, like sed (using -p). + rudimentary_switch_parsing: Enable rudimentary parsing for switches after programfile (using -s). + search_programfile_in_path: Look for programfile using PATH environment variable (using -S). + enable_tainting_warnings: Enable tainting warnings (using -t). + enable_tainting_checks: Enable tainting checks (using -T). + dump_core_after_parsing: Dump core after parsing program (using -u). + allow_unsafe_operations: Allow unsafe operations (using -U). + print_version: Print version, patchlevel and license (using -v). + print_config_summary: Print configuration summary. Optionally specify a single Config.pm variable. + If an empty string (""), it prints the full configuration summary (-V). + Example: "archname" for -V:archname. + enable_warnings: Enable many useful warnings (using -w). + enable_all_warnings: Enable all warnings (using -W). + ignore_text_before_shebang_dir: Ignore text before #!perl line. Optionally cd to the specified directory. + If Path(""), it ignores text without changing directory (-x). + disable_all_warnings: Disable all warnings (using -X). + """ + command = ["perl"] + output_files = [] + + # Input validation + if program_file and not program_file.is_file(): + raise ValueError(f"Program file '{program_file}' does not exist or is not a file.") + + if program_file and (program_string or program_string_extended): + raise ValueError("Cannot specify both a program file and program string(s) (-e/-E).") + + if not program_file and not (program_string or program_string_extended): + raise ValueError("Either a program file or at least one program string (-e/-E) must be provided.") + + if split_pattern and not autosplit: + raise ValueError("'-F/pattern/' switch requires '-a' (autosplit) to be enabled.") + + # -p implies -n + if print_loop_around_program: + loop_around_program = True + + # Handle warning flags: -w, -W, -X + warning_flags_count = sum([enable_warnings, enable_all_warnings, disable_all_warnings]) + if warning_flags_count > 1: + raise ValueError("Only one of -w, -W, or -X can be specified.") + + # Add switches to the command + if record_separator is not None: + command.append(f"-0{record_separator}") + if autosplit: + command.append("-a") + if unicode_features is not None: + command.append(f"-C{unicode_features}") + if check_syntax_only: + command.append("-c") + if debugger is not None: + command.append(f"-d:{debugger}") + if debug_flags is not None: + command.append(f"-D{debug_flags}") + if program_string: + for p_str in program_string: + command.extend(["-e", p_str]) + if program_string_extended: + for p_str in program_string_extended: + command.extend(["-E", p_str]) + if no_sitecustomize: + command.append("-f") + if split_pattern is not None: + command.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + command.append(f"-i{edit_in_place_extension}") + if include_directories: + for inc_dir in include_directories: + if not inc_dir.is_dir(): + raise ValueError(f"Include directory '{inc_dir}' does not exist or is not a directory.") + command.extend(["-I", str(inc_dir)]) + if line_ending_processing is not None: + command.append(f"-l{line_ending_processing}") + if use_module_before_program: + for module in use_module_before_program: + command.append(f"-m{module}") + if use_module_strict_before_program: + for module in use_module_strict_before_program: + command.append(f"-M{module}") + if no_module_before_program: + for module in no_module_before_program: + command.append(f"-M-{module}") + if loop_around_program: + command.append("-n") + if print_loop_around_program: + command.append("-p") + if rudimentary_switch_parsing: + command.append("-s") + if search_programfile_in_path: + command.append("-S") + if enable_tainting_warnings: + command.append("-t") + if enable_tainting_checks: + command.append("-T") + if dump_core_after_parsing: + command.append("-u") + if allow_unsafe_operations: + command.append("-U") + if print_version: + command.append("-v") + if print_config_summary is not None: + if print_config_summary == "": + command.append("-V") + else: + command.append(f"-V:{print_config_summary}") + if enable_warnings: + command.append("-w") + if enable_all_warnings: + command.append("-W") + if ignore_text_before_shebang_dir is not None: + if ignore_text_before_shebang_dir == Path(""): # This means -x without argument + command.append("-x") + elif ignore_text_before_shebang_dir.is_dir(): + command.append(f"-x{ignore_text_before_shebang_dir}") + else: + raise ValueError(f"Directory for -x '{ignore_text_before_shebang_dir}' does not exist or is not a directory.") + if disable_all_warnings: + command.append("-X") + + # Add program file and its arguments + if program_file: + command.append(str(program_file)) + if program_arguments: + command.extend(program_arguments) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": [], + } + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/app/perl-jcode_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/app/perl-jcode_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..423c7fa7d20e6793d2af692719f5dd9a74da1cc0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/app/perl-jcode_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/app/perl-jcode_server.py') +SERVER_NAME = 'biosci_perl_jcode' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5dc949b58bfeeeb6798c6ab8f7b9f4d5c98e5ffe --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-jcode: + build: . + image: mcp-perl-jcode:latest + container_name: mcp-perl-jcode + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-jcode + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..42cb581f464b695446d748f8577ea8bedde2159a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-jcode + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-jcode/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7e324acdc328a7d478bb3d2aa91766a1bd49de25 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-json-pp via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-json-pp -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-json-pp_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-json-pp_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-json-pp_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/app/perl-json-pp_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/app/perl-json-pp_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e7fa86cbc831c24c7601a84e46a0fe9042712768 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/app/perl-json-pp_server.py @@ -0,0 +1,180 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +@mcp.tool() +def json_pp( + input_file: str, + output_file: Optional[str] = None, + from_format: str = "json", + to_format: str = "json", + pretty: bool = True, + ascii: bool = False, + latin1: bool = False, + utf8: bool = True, + indent: int = 2, + space_before: bool = False, + space_after: bool = True, + relaxed: bool = False, + canonical: bool = False, + allow_nonref: bool = True, + allow_unknown: bool = False, + allow_blessed: bool = False, + convert_blessed: bool = False, + verbose: bool = False +): + """ + Converts between different JSON formats using the perl-json-pp utility. + Supports reading from JSON, Perl Eval, or YAML and outputting to JSON or Perl Eval. + + :param input_file: Path to the input file to process. + :param output_file: Path to save the output. If not provided, output is returned in stdout. + :param from_format: Input format. Options: 'json', 'eval', 'yaml'. Default: 'json'. + :param to_format: Output format. Options: 'json', 'eval'. Default: 'json'. + :param pretty: Enables pretty-printing of the output. + :param ascii: Use ASCII only; escape all non-ASCII characters. + :param latin1: Encode output in Latin-1. + :param utf8: Encode output in UTF-8. + :param indent: Number of spaces for indentation (used if pretty is True). + :param space_before: Add a space before the colon in key-value pairs. + :param space_after: Add a space after the colon in key-value pairs. + :param relaxed: Allow relaxed JSON syntax (e.g., trailing commas). + :param canonical: Sort object keys alphabetically. + :param allow_nonref: Allow non-reference values (scalars) as top-level JSON. + :param allow_unknown: Allow unknown types to be encoded as null. + :param allow_blessed: Allow blessed references (objects). + :param convert_blessed: Use TO_JSON method on blessed objects if available. + :param verbose: Enable verbose output. + """ + # Input validation + input_path = Path(input_file) + if not input_path.is_file(): + return {"error": f"Input file not found: {input_file}"} + + valid_from = ["json", "eval", "yaml"] + valid_to = ["json", "eval"] + + if from_format not in valid_from: + return {"error": f"Invalid from_format '{from_format}'. Must be one of {valid_from}"} + if to_format not in valid_to: + return {"error": f"Invalid to_format '{to_format}'. Must be one of {valid_to}"} + + if indent < 0: + return {"error": "Indent must be a non-negative integer."} + + # Construct command + cmd = ["json_pp"] + + # Format flags + cmd.extend(["-f", from_format]) + cmd.extend(["-t", to_format]) + + if verbose: + cmd.append("-v") + + # JSON options (-json_opt) + json_opts = [] + if pretty: + json_opts.append("pretty") + if ascii: + json_opts.append("ascii") + if latin1: + json_opts.append("latin1") + if utf8: + json_opts.append("utf8") + if indent != 2: + json_opts.append(f"indent:{indent}") + if space_before: + json_opts.append("space_before") + if space_after: + json_opts.append("space_after") + if relaxed: + json_opts.append("relaxed") + if canonical: + json_opts.append("canonical") + if allow_nonref: + json_opts.append("allow_nonref") + if allow_unknown: + json_opts.append("allow_unknown") + if allow_blessed: + json_opts.append("allow_blessed") + if convert_blessed: + json_opts.append("convert_blessed") + + if json_opts: + cmd.extend(["-json_opt", ",".join(json_opts)]) + + # Execution + try: + # json_pp reads from STDIN + with open(input_path, "r") as f_in: + if output_file: + output_path = Path(output_file) + with open(output_path, "w") as f_out: + process = subprocess.run( + cmd, + stdin=f_in, + stdout=f_out, + stderr=subprocess.PIPE, + text=True, + check=True + ) + stdout_content = f"Output written to {output_file}" + output_files = [str(output_path.absolute())] + else: + process = subprocess.run( + cmd, + stdin=f_in, + capture_output=True, + text=True, + check=True + ) + stdout_content = process.stdout + output_files = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_content, + "stderr": process.stderr, + "output_files": output_files + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": "Execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode + } + except Exception as e: + return { + "command_executed": " ".join(cmd), + "error": str(e) + } + +@mcp.tool() +def json_pp_version(): + """ + Returns the version information for the installed json_pp utility. + """ + cmd = ["json_pp", "-v"] + try: + # json_pp -v usually prints version and exits, but might expect STDIN + # We provide empty input to prevent hanging + process = subprocess.run( + cmd, + input="", + capture_output=True, + text=True, + check=False # -v might return non-zero in some versions if no input + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr + } + except Exception as e: + return { + "error": f"Could not determine version: {str(e)}" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/app/perl-json-pp_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/app/perl-json-pp_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ab8873711a27f437ac3391036c1830af4ac32d10 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/app/perl-json-pp_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/app/perl-json-pp_server.py') +SERVER_NAME = 'biosci_perl_json_pp' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..07d786bf4ac683261dd729143f5f388d71be3618 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-json-pp: + build: . + image: mcp-perl-json-pp:latest + container_name: mcp-perl-json-pp + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-json-pp + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f65fd8e82f6643a171ed05900e531c668e9541a6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-json-pp + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-pp/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b311b63df49d0b63b7e48f0d6b05c99c8a91412f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-json-xs via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-json-xs -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-json-xs_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-json-xs_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-json-xs_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/app/perl-json-xs_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/app/perl-json-xs_server.py new file mode 100644 index 0000000000000000000000000000000000000000..00133085937e09d3f1c91d0687793eaba3a72fd4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/app/perl-json-xs_server.py @@ -0,0 +1,223 @@ +from pathlib import Path +import subprocess +from typing import Optional, List, Dict, Any + +@mcp.tool() +def json_xs( + input_file: str, + from_format: str = "json", + to_format: str = "json", + expression: str = "", + verbose: bool = False, + output_file: str = "", +): + """ + JSON::XS command line utility for converting, filtering, and transforming JSON data. + This tool allows you to convert between various formats and apply Perl transformations. + + Args: + input_file: Path to the input file to process. + from_format: The format of the input file. + Options: json, storable, clojure, eval, yaml, cbor, string. + to_format: The format of the output. + Options: json, json-utf8, json-ascii, json-pretty, storable, + storable-file, clojure, eval, yaml, cbor, string, none. + expression: Perl code to evaluate on the data (the data is stored in $_). + verbose: Enable verbose output from the json_xs utility. + output_file: Optional path to save the output. If not provided, output is returned in stdout. + """ + # Input validation + input_path = Path(input_file) + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + valid_from = ["json", "storable", "clojure", "eval", "yaml", "cbor", "string"] + valid_to = ["json", "json-utf8", "json-ascii", "json-pretty", "storable", + "storable-file", "clojure", "eval", "yaml", "cbor", "string", "none"] + + if from_format not in valid_from: + raise ValueError(f"Invalid from_format '{from_format}'. Must be one of: {', '.join(valid_from)}") + if to_format not in valid_to: + raise ValueError(f"Invalid to_format '{to_format}'. Must be one of: {', '.join(valid_to)}") + + # Construct command + cmd = ["json_xs"] + if verbose: + cmd.append("-v") + + cmd.extend(["-f", from_format]) + cmd.extend(["-t", to_format]) + + if expression: + cmd.extend(["-e", expression]) + + cmd.append(str(input_path)) + + try: + # Subprocess execution + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + output_content = result.stdout + + # Handle output file + output_files = [] + if output_file: + out_path = Path(output_file) + out_path.write_text(output_content) + output_files.append(str(out_path)) + + return { + "command_executed": " ".join(cmd), + "stdout": output_content, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Command failed with return code {e.returncode}" + } + +@mcp.tool() +def perl_json_xs_oo_process( + input_file: str, + pretty: bool = False, + ascii: bool = False, + latin1: bool = False, + utf8: bool = True, + canonical: bool = False, + relaxed: bool = False, + allow_nonref: bool = True, + space_before: bool = False, + space_after: bool = False, + indent: bool = False, + output_file: str = "", +): + """ + Process JSON using the JSON::XS Object-Oriented interface for fine-grained control over + encoding and decoding flags. This exposes the internal configuration methods of the module. + + Args: + input_file: Path to the JSON input file. + pretty: Enable all formatting flags (indent, space_before, space_after). + ascii: Escape Unicode characters outside the 0..127 range. + latin1: Encode resulting JSON text as ISO-8859-1. + utf8: Encode/decode JSON result into/from UTF-8. + canonical: Sort object keys alphabetically. + relaxed: Accept extensions like trailing commas and shell-style comments. + allow_nonref: Allow non-references (scalars) at the top level. + space_before: Add a space before the colon in objects. + space_after: Add a space after the colon and comma. + indent: Use a multiline format with indentation. + output_file: Optional path to save the processed JSON. + """ + input_path = Path(input_file) + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + # Construct Perl one-liner to use the OO interface + # We build the coder object by chaining the mutators + perl_script = ( + "use JSON::XS; " + "local $/; " + "my $raw = <>; " + "my $coder = JSON::XS->new" + f"->ascii({1 if ascii else 0})" + f"->latin1({1 if latin1 else 0})" + f"->utf8({1 if utf8 else 0})" + f"->pretty({1 if pretty else 0})" + f"->canonical({1 if canonical else 0})" + f"->relaxed({1 if relaxed else 0})" + f"->allow_nonref({1 if allow_nonref else 0})" + f"->space_before({1 if space_before else 0})" + f"->space_after({1 if space_after else 0})" + f"->indent({1 if indent else 0}); " + "my $data = $coder->decode($raw); " + "print $coder->encode($data);" + ) + + cmd = ["perl", "-MJSON::XS", "-e", perl_script, str(input_path)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + output_content = result.stdout + output_files = [] + if output_file: + out_path = Path(output_file) + out_path.write_text(output_content) + output_files.append(str(out_path)) + + return { + "command_executed": " ".join(cmd), + "stdout": output_content, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed: {e.stderr}" + } + +@mcp.tool() +def perl_json_xs_version(): + """ + Check the installed version of the JSON::XS Perl module and the json_xs utility. + """ + try: + # Check module version + perl_ver_cmd = ["perl", "-MJSON::XS", "-e", "print $JSON::XS::VERSION"] + perl_res = subprocess.run(perl_ver_cmd, capture_output=True, text=True, check=True) + + # Check CLI utility version + cli_ver_cmd = ["json_xs", "-v"] + # json_xs -v usually prints to stderr and might exit with 0 or 1 depending on version + cli_res = subprocess.run(cli_ver_cmd, capture_output=True, text=True) + + return { + "module_version": perl_res.stdout.strip(), + "cli_info": cli_res.stderr.strip() if cli_res.stderr else cli_res.stdout.strip(), + "status": "success" + } + except Exception as e: + return { + "error": str(e), + "status": "failed" + } + +@mcp.tool() +def perl_json_xs_validate(input_file: str): + """ + Validate a JSON file using JSON::XS. This is a convenience wrapper around the + decode_json functional interface. + + Args: + input_file: Path to the JSON file to validate. + """ + input_path = Path(input_file) + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + # Use decode_json which is the fastest functional interface + perl_script = "use JSON::XS; local $/; my $raw = <>; eval { decode_json($raw) }; if ($@) { die $@ } else { print 'Valid JSON' }" + cmd = ["perl", "-MJSON::XS", "-e", perl_script, str(input_path)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "is_valid": True, + "stdout": result.stdout.strip(), + "command_executed": " ".join(cmd) + } + except subprocess.CalledProcessError as e: + return { + "is_valid": False, + "stderr": e.stderr.strip(), + "command_executed": " ".join(cmd), + "error": "JSON validation failed" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/app/perl-json-xs_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/app/perl-json-xs_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e641e5dd2aa62fbdf263c961b2f5e69b00a52784 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/app/perl-json-xs_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/app/perl-json-xs_server.py') +SERVER_NAME = 'biosci_perl_json_xs' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..fb4044c92a5edc1db0f1093c6bca2e6b9467adb6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-json-xs: + build: . + image: mcp-perl-json-xs:latest + container_name: mcp-perl-json-xs + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-json-xs + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..da8b22ab725a19f48a3a7e3e623641d11e98251a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-json-xs + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json-xs/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4cbbe0ed169a2427c11c1fbda20c83f14baf9dce --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-json via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-json -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-json_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-json_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-json_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/app/perl-json_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/app/perl-json_server.py new file mode 100644 index 0000000000000000000000000000000000000000..030397b570c81616e90dbc3f958a7da2496edd3c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/app/perl-json_server.py @@ -0,0 +1,268 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def perl_json_encode( + perl_code: str, + ascii: bool = False, + utf8: bool = True, + pretty: bool = False, + canonical: bool = False, + allow_nonref: bool = True, + convert_blessed: bool = False, + space_before: bool = False, + space_after: bool = False, +): + """ + Encodes a Perl data structure into a JSON string using the perl-json module. + + Args: + perl_code: A string containing a Perl data structure (e.g., '{a => 1, b => [2, 3]}'). + ascii: If true, encodes non-ASCII characters as \\uXXXX escapes. + utf8: If true, produces UTF-8 encoded binary string. + pretty: Enables indent, space_before, and space_after for readable output. + canonical: Sorts object keys alphabetically. + allow_nonref: Allows encoding of non-reference scalars (strings, numbers, null). + convert_blessed: Allows encoding of blessed objects (requires TO_JSON method or universal conversion). + space_before: Adds a space before the ':' in key-value pairs. + space_after: Adds a space after the ':' and ',' in JSON. + """ + # Construct the Perl one-liner + # We use JSON->new and chain the methods based on parameters + perl_script = "use JSON; " + perl_script += "my $json = JSON->new;" + if ascii: perl_script += "$json->ascii(1);" + if utf8: perl_script += "$json->utf8(1);" + if pretty: perl_script += "$json->pretty(1);" + if canonical: perl_script += "$json->canonical(1);" + if allow_nonref: perl_script += "$json->allow_nonref(1);" + if convert_blessed: perl_script += "$json->convert_blessed(1);" + if space_before: perl_script += "$json->space_before(1);" + if space_after: perl_script += "$json->space_after(1);" + + # The eval(shift) takes the perl_code from the command line arguments + perl_script += "print $json->encode(eval(shift));" + + try: + result = subprocess.run( + ["perl", "-MJSON", "-e", perl_script, "--", perl_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"perl -MJSON -e '...' -- '{perl_code}'", + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def perl_json_decode( + json_text: str, + utf8: bool = True, + relaxed: bool = False, + allow_nonref: bool = True, + max_depth: int = 512, +): + """ + Decodes a JSON string into a Perl data structure representation (using Data::Dumper). + + Args: + json_text: The JSON string to decode. + utf8: If true, expects the input to be UTF-8 encoded. + relaxed: Allows shell-style comments and trailing commas in the JSON. + allow_nonref: Allows decoding of non-reference JSON values (scalars). + max_depth: Sets the maximum nesting depth for the JSON structure. + """ + if max_depth < 1: + max_depth = 512 + + perl_script = "use JSON; use Data::Dumper; " + perl_script += "$Data::Dumper::Terse = 1; $Data::Dumper::Indent = 1; " + perl_script += "my $json = JSON->new;" + if utf8: perl_script += "$json->utf8(1);" + if relaxed: perl_script += "$json->relaxed(1);" + if allow_nonref: perl_script += "$json->allow_nonref(1);" + perl_script += f"$json->max_depth({max_depth});" + + perl_script += "print Dumper($json->decode(shift));" + + try: + result = subprocess.run( + ["perl", "-MJSON", "-MData::Dumper", "-e", perl_script, "--", json_text], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"perl -MJSON -MData::Dumper -e '...' -- '{json_text}'", + "perl_structure": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def perl_json_reformat_file( + input_file: str, + output_file: Optional[str] = None, + pretty: bool = True, + canonical: bool = True, + ascii: bool = False, + relaxed: bool = False, +): + """ + Reads a JSON file and reformats it (pretty-print or minify). + + Args: + input_file: Path to the input JSON file. + output_file: Path to save the reformatted JSON. If not provided, returns to stdout. + pretty: If true, produces human-readable indented output. + canonical: If true, sorts object keys. + ascii: If true, escapes non-ASCII characters. + relaxed: If true, allows comments and trailing commas in the input file. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} does not exist."} + + perl_script = "use JSON; use File::Slurp; " + # Note: Using a simple file read if File::Slurp isn't guaranteed, + # but standard perl-json users often have it. We'll use a core-only way for safety. + perl_script = ( + "use JSON; " + "undef $/; " + "my $content = <>; " + "my $json = JSON->new;" + ) + + if pretty: perl_script += "$json->pretty(1);" + if canonical: perl_script += "$json->canonical(1);" + if ascii: perl_script += "$json->ascii(1);" + if relaxed: perl_script += "$json->relaxed(1);" + + perl_script += "print $json->encode($json->decode($content));" + + cmd = ["perl", "-MJSON", "-e", perl_script, input_file] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + output_files = [] + if output_file: + out_path = Path(output_file) + out_path.write_text(result.stdout) + output_files.append(str(out_path)) + return { + "command_executed": " ".join(cmd), + "message": f"Reformatted JSON saved to {output_file}", + "output_files": output_files, + "status": "success" + } + else: + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def perl_json_validate_file( + input_file: str, + relaxed: bool = False, +): + """ + Validates the syntax of a JSON file. + + Args: + input_file: Path to the JSON file to validate. + relaxed: If true, allows comments and trailing commas during validation. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} does not exist."} + + perl_script = ( + "use JSON; " + "undef $/; " + "my $content = <>; " + "my $json = JSON->new;" + ) + if relaxed: perl_script += "$json->relaxed(1);" + perl_script += "eval { $json->decode($content) }; if ($@) { die $@ } else { print 'Valid JSON' }" + + try: + result = subprocess.run( + ["perl", "-MJSON", "-e", perl_script, input_file], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"perl -MJSON -e '...' {input_file}", + "stdout": result.stdout, + "is_valid": True, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "is_valid": False, + "error_message": e.stderr.strip(), + "status": "invalid" + } + +@mcp.tool() +def perl_json_get_backend(): + """ + Identifies which backend module (JSON::XS, JSON::PP, or Cpanel::JSON::XS) is currently being used by the JSON module. + """ + perl_script = "use JSON; my $json = JSON->new; print $json->backend;" + + try: + result = subprocess.run( + ["perl", "-MJSON", "-e", perl_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"perl -MJSON -e '{perl_script}'", + "backend": result.stdout, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": e.cmd, + "error": str(e), + "status": "error" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/app/perl-json_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/app/perl-json_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..67071ac1c73375cc40e8de539948c456d622dc0c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/app/perl-json_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/app/perl-json_server.py') +SERVER_NAME = 'biosci_perl_json' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..87a79e338c5c185eba1959ea07f471d116bc10f6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-json: + build: . + image: mcp-perl-json:latest + container_name: mcp-perl-json + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-json + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..72ba2caaab2c492444ec46c032118d63bf77c146 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-json + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-json/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7059074566b66c42acca7d5eeba13dbb9dd17bef --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-lib via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-lib -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-lib_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-lib_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-lib_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/app/perl-lib_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/app/perl-lib_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ca78ca0ca38cd7927f23b647fd0e2333ee79e623 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/app/perl-lib_server.py @@ -0,0 +1,356 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union + +@mcp.tool() +def vcf_annotate( + input_vcf: str, + annotations: str, + columns: str, + description: Optional[str] = None, + fill_id: bool = False, + filter: Optional[str] = None, + output_file: Optional[str] = None, +): + """ + Annotate VCF files using vcf-annotate (VCFtools Perl library). + + :param input_vcf: Path to the input VCF file. + :param annotations: Path to the tabix-indexed annotation file. + :param columns: Comma-separated list of columns (e.g., 'CHROM,POS,REF,ALT,ID,INFO/ANN'). + :param description: Path to a file containing tag descriptions. + :param fill_id: If True, fill the ID column based on coordinates. + :param filter: Apply a filter (e.g., 'FilterName:Condition'). + :param output_file: Path to save the annotated VCF. + """ + vcf_path = Path(input_vcf) + ann_path = Path(annotations) + + if not vcf_path.exists(): + return {"error": f"Input VCF not found: {input_vcf}"} + if not ann_path.exists(): + return {"error": f"Annotation file not found: {annotations}"} + + cmd = ["vcf-annotate", "-a", str(ann_path), "-c", columns] + + if description: + cmd.extend(["-d", description]) + if fill_id: + cmd.append("--fill-id") + if filter: + cmd.extend(["-f", filter]) + + cmd.append(str(vcf_path)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + if output_file: + out_path = Path(output_file) + out_path.write_text(result.stdout) + return { + "command_executed": " ".join(cmd), + "stdout": "Output written to file", + "stderr": result.stderr, + "output_files": [str(out_path)] + } + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def vcf_compare( + files: List[str], + prefix: str = "compare_out", + ignore_type: bool = False, + chromosomes: Optional[str] = None, +): + """ + Compare VCF files using vcf-compare. + + :param files: List of paths to VCF files to compare. + :param prefix: Prefix for the output files. + :param ignore_type: Ignore variant type (e.g., SNP vs Indel). + :param chromosomes: Comma-separated list of chromosomes to process. + """ + valid_files = [] + for f in files: + p = Path(f) + if not p.exists(): + return {"error": f"File not found: {f}"} + valid_files.append(str(p)) + + cmd = ["vcf-compare"] + if ignore_type: + cmd.append("-i") + if chromosomes: + cmd.extend(["-r", chromosomes]) + + cmd.extend(valid_files) + + # vcf-compare usually outputs to stdout but can generate files with -p + cmd.extend(["-p", prefix]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [f"{prefix}{ext}" for ext in [".stats", ".plot"]] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def vcf_concat( + files: List[str], + output_file: Optional[str] = None, + temp_dir: str = "/tmp", +): + """ + Concatenate VCF files using vcf-concat. + + :param files: List of VCF files to concatenate. + :param output_file: Path to the output VCF. + :param temp_dir: Directory for temporary files. + """ + valid_files = [] + for f in files: + p = Path(f) + if not p.exists(): + return {"error": f"File not found: {f}"} + valid_files.append(str(p)) + + cmd = ["vcf-concat", "-t", temp_dir] + valid_files + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + if output_file: + out_path = Path(output_file) + out_path.write_text(result.stdout) + return { + "command_executed": " ".join(cmd), + "stdout": "Concatenation complete", + "output_files": [str(out_path)] + } + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def vcf_merge( + files: List[str], + ref_fasta: Optional[str] = None, + output_file: Optional[str] = None, +): + """ + Merge VCF files using vcf-merge. + + :param files: List of VCF files to merge (must be bgzipped and tabix indexed). + :param ref_fasta: Optional reference fasta for resolving conflicts. + :param output_file: Path to the output merged VCF. + """ + valid_files = [] + for f in files: + p = Path(f) + if not p.exists(): + return {"error": f"File not found: {f}"} + valid_files.append(str(p)) + + cmd = ["vcf-merge"] + if ref_fasta: + cmd.extend(["-R", ref_fasta]) + + cmd.extend(valid_files) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + if output_file: + out_path = Path(output_file) + out_path.write_text(result.stdout) + return { + "command_executed": " ".join(cmd), + "stdout": "Merge complete", + "output_files": [str(out_path)] + } + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def vcf_stats( + input_vcf: str, + prefix: str = "vcf_stats", + dump_stats: bool = True, +): + """ + Generate statistics for a VCF file using vcf-stats. + + :param input_vcf: Path to the input VCF file. + :param prefix: Prefix for output files. + :param dump_stats: If True, dump statistics to files. + """ + vcf_path = Path(input_vcf) + if not vcf_path.exists(): + return {"error": f"Input VCF not found: {input_vcf}"} + + cmd = ["vcf-stats", str(vcf_path)] + if dump_stats: + cmd.extend(["-p", prefix]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [f"{prefix}.txt"] if dump_stats else [] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def vcf_sort( + input_vcf: str, + output_file: Optional[str] = None, + temp_dir: str = "/tmp", +): + """ + Sort a VCF file using vcf-sort. + + :param input_vcf: Path to the input VCF file. + :param output_file: Path to the output sorted VCF. + :param temp_dir: Directory for temporary files. + """ + vcf_path = Path(input_vcf) + if not vcf_path.exists(): + return {"error": f"Input VCF not found: {input_vcf}"} + + cmd = ["vcf-sort", "-t", temp_dir, str(vcf_path)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + if output_file: + out_path = Path(output_file) + out_path.write_text(result.stdout) + return { + "command_executed": " ".join(cmd), + "stdout": "Sort complete", + "output_files": [str(out_path)] + } + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def vcf_validator( + input_vcf: str, +): + """ + Validate a VCF file using vcf-validator. + + :param input_vcf: Path to the input VCF file. + """ + vcf_path = Path(input_vcf) + if not vcf_path.exists(): + return {"error": f"Input VCF not found: {input_vcf}"} + + cmd = ["vcf-validator", str(vcf_path)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "Valid" if not result.stderr else "Issues found" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": "Validation failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def vcf_subset( + input_vcf: str, + samples: str, + exclude_ref: bool = False, + keep_id: bool = False, + output_file: Optional[str] = None, +): + """ + Subset a VCF file by samples using vcf-subset. + + :param input_vcf: Path to the input VCF file. + :param samples: Comma-separated list of sample names or a file path. + :param exclude_ref: Exclude reference-only sites. + :param keep_id: Keep the ID column. + :param output_file: Path to the output subset VCF. + """ + vcf_path = Path(input_vcf) + if not vcf_path.exists(): + return {"error": f"Input VCF not found: {input_vcf}"} + + cmd = ["vcf-subset"] + if exclude_ref: + cmd.append("-e") + if keep_id: + cmd.append("-i") + + # Check if samples is a file or a list + if Path(samples).exists(): + cmd.extend(["-f", samples]) + else: + cmd.extend(["-c", samples]) + + cmd.append(str(vcf_path)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + if output_file: + out_path = Path(output_file) + out_path.write_text(result.stdout) + return { + "command_executed": " ".join(cmd), + "stdout": "Subset complete", + "output_files": [str(out_path)] + } + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/app/perl-lib_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/app/perl-lib_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c1457d6f310d9fc3e10c7736e002a52815d2dad7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/app/perl-lib_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/app/perl-lib_server.py') +SERVER_NAME = 'biosci_perl_lib' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e97f780fa74a7abaff2931ff6d3edc9d3d265dab --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-lib: + build: . + image: mcp-perl-lib:latest + container_name: mcp-perl-lib + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-lib + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e05730843585d1b0be263ee7316cf31755743a00 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-lib + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lib/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7feffc1fda0d7e7b3b726533c493697fdfe86478 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-libwww-perl via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-libwww-perl -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-libwww-perl_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-libwww-perl_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-libwww-perl_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/app/perl-libwww-perl_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/app/perl-libwww-perl_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d3832e40f89d33bd921092a3486928823e4cd224 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/app/perl-libwww-perl_server.py @@ -0,0 +1,298 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +def _run_command(cmd: List[str], input_data: Optional[str] = None) -> Dict[str, Any]: + """Helper to run subprocess commands and return structured output.""" + try: + process = subprocess.run( + cmd, + input=input_data.encode() if input_data else None, + capture_output=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout.decode(), + "stderr": process.stderr.decode(), + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout.decode(), + "stderr": e.stderr.decode(), + "error": str(e), + "status": "error" + } + +@mcp.tool() +def lwp_request( + url: str, + method: str = "GET", + timeout: int = 180, + content_type: Optional[str] = None, + headers: Optional[List[str]] = None, + proxy: Optional[str] = None, + credentials: Optional[str] = None, + base_url: Optional[str] = None, + if_modified_since: Optional[str] = None, + show_headers: bool = False, + show_status_chain: bool = False, + no_content: bool = False, + force: bool = False, + output_format: Optional[str] = None, + input_data: Optional[str] = None, +) -> Dict[str, Any]: + """ + Execute an HTTP request using lwp-request (libwww-perl). + + Args: + url: The URL to request. + method: HTTP method (GET, POST, HEAD, PUT, DELETE). + timeout: Timeout in seconds (default 180). + content_type: Set the Content-Type header for the request (-c). + headers: List of additional headers in 'Header: Value' format (-H). + proxy: Proxy URL to use (-p). + credentials: User credentials in 'user:pass' format (-C). + base_url: Base URL for relative links (-b). + if_modified_since: If-Modified-Since time (-i). + show_headers: Display response headers (-e). + show_status_chain: Show the response status chain (-S). + no_content: Do not display the response content (-d). + force: Force the request (-f). + output_format: Output format (e.g., 'html', 'text', 'ps', 'dump') (-o). + input_data: Data to be sent in the request body (for POST/PUT). + """ + if not url: + raise ValueError("URL is required") + if timeout <= 0: + raise ValueError("Timeout must be a positive integer") + + cmd = ["lwp-request", "-m", method.upper(), "-t", str(timeout)] + + if content_type: + cmd.extend(["-c", content_type]) + if headers: + for h in headers: + cmd.extend(["-H", h]) + if proxy: + cmd.extend(["-p", proxy]) + if credentials: + cmd.extend(["-C", credentials]) + if base_url: + cmd.extend(["-b", base_url]) + if if_modified_since: + cmd.extend(["-i", if_modified_since]) + if show_headers: + cmd.append("-e") + if show_status_chain: + cmd.append("-S") + if no_content: + cmd.append("-d") + if force: + cmd.append("-f") + if output_format: + cmd.extend(["-o", output_format]) + + cmd.append(url) + + return _run_command(cmd, input_data) + +@mcp.tool() +def lwp_get( + url: str, + timeout: int = 180, + headers: Optional[List[str]] = None, + proxy: Optional[str] = None, + show_headers: bool = False, + no_content: bool = False, +) -> Dict[str, Any]: + """ + Send a GET request using the GET utility (alias for lwp-request). + + Args: + url: The URL to request. + timeout: Timeout in seconds (default 180). + headers: List of additional headers in 'Header: Value' format. + proxy: Proxy URL to use. + show_headers: Display response headers. + no_content: Do not display response content. + """ + if not url: + raise ValueError("URL is required") + + cmd = ["GET", "-t", str(timeout)] + if headers: + for h in headers: + cmd.extend(["-H", h]) + if proxy: + cmd.extend(["-p", proxy]) + if show_headers: + cmd.append("-e") + if no_content: + cmd.append("-d") + + cmd.append(url) + return _run_command(cmd) + +@mcp.tool() +def lwp_post( + url: str, + input_data: str, + content_type: str = "application/x-www-form-urlencoded", + timeout: int = 180, + headers: Optional[List[str]] = None, + proxy: Optional[str] = None, + show_headers: bool = False, +) -> Dict[str, Any]: + """ + Send a POST request using the POST utility (alias for lwp-request). + + Args: + url: The URL to request. + input_data: Data to be sent in the request body. + content_type: Content-Type of the input data (default application/x-www-form-urlencoded). + timeout: Timeout in seconds (default 180). + headers: List of additional headers in 'Header: Value' format. + proxy: Proxy URL to use. + show_headers: Display response headers. + """ + if not url: + raise ValueError("URL is required") + + cmd = ["POST", "-t", str(timeout), "-c", content_type] + if headers: + for h in headers: + cmd.extend(["-H", h]) + if proxy: + cmd.extend(["-p", proxy]) + if show_headers: + cmd.append("-e") + + cmd.append(url) + return _run_command(cmd, input_data) + +@mcp.tool() +def lwp_head( + url: str, + timeout: int = 180, + headers: Optional[List[str]] = None, + proxy: Optional[str] = None, +) -> Dict[str, Any]: + """ + Send a HEAD request using the HEAD utility (alias for lwp-request). + + Args: + url: The URL to request. + timeout: Timeout in seconds (default 180). + headers: List of additional headers in 'Header: Value' format. + proxy: Proxy URL to use. + """ + if not url: + raise ValueError("URL is required") + + cmd = ["HEAD", "-t", str(timeout)] + if headers: + for h in headers: + cmd.extend(["-H", h]) + if proxy: + cmd.extend(["-p", proxy]) + + cmd.append(url) + return _run_command(cmd) + +@mcp.tool() +def lwp_download( + url: str, + output_file: Optional[str] = None, +) -> Dict[str, Any]: + """ + Download a file from a URL using lwp-download. + + Args: + url: The URL to download. + output_file: Optional local filename to save the content. + """ + if not url: + raise ValueError("URL is required") + + cmd = ["lwp-download", url] + if output_file: + out_path = Path(output_file) + if not out_path.parent.exists(): + raise ValueError(f"Parent directory does not exist: {out_path.parent}") + cmd.append(output_file) + + return _run_command(cmd) + +@mcp.tool() +def lwp_mirror( + url: str, + output_file: str, +) -> Dict[str, Any]: + """ + Mirror a URL to a local file using lwp-mirror. + Only downloads if the remote file is newer than the local copy. + + Args: + url: The URL to mirror. + output_file: Local filename to save the content. + """ + if not url: + raise ValueError("URL is required") + if not output_file: + raise ValueError("Output file path is required") + + out_path = Path(output_file) + if not out_path.parent.exists(): + raise ValueError(f"Parent directory does not exist: {out_path.parent}") + + cmd = ["lwp-mirror", url, output_file] + return _run_command(cmd) + +@mcp.tool() +def lwp_dump( + url: str, +) -> Dict[str, Any]: + """ + Dump the structure of a resource using lwp-dump. + + Args: + url: The URL to dump. + """ + if not url: + raise ValueError("URL is required") + + cmd = ["lwp-dump", url] + return _run_command(cmd) + +@mcp.tool() +def lwp_version() -> Dict[str, Any]: + """Get the version of libwww-perl.""" + return _run_command(["lwp-request", "-v"]) + +@mcp.tool() +def perl_lwp_execute( + script_content: str, + args: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Execute a Perl script that uses libwww-perl (LWP). + + Args: + script_content: The Perl code to execute. + args: Optional command line arguments for the script. + """ + if not script_content: + raise ValueError("Script content is required") + + # Prepend common LWP modules if not explicitly present in the snippet + if "use LWP" not in script_content: + script_content = "use LWP::UserAgent; use HTTP::Request; use HTTP::Response; " + script_content + + cmd = ["perl", "-e", script_content] + if args: + cmd.extend(args) + + return _run_command(cmd) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/app/perl-libwww-perl_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/app/perl-libwww-perl_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ad4e2e03151240befb2cce13a27681323173eb7a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/app/perl-libwww-perl_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/app/perl-libwww-perl_server.py') +SERVER_NAME = 'biosci_perl_libwww_perl' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..34c1c90142d2332cc38a74838f37d7c16419ab0c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-libwww-perl: + build: . + image: mcp-perl-libwww-perl:latest + container_name: mcp-perl-libwww-perl + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-libwww-perl + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1a8e865e1f758d15ebd21393f2c36578818a3a6a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-libwww-perl + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libwww-perl/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..08b89036ef919de80b6e4ad1450f549f803d6b21 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-libxml-perl via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-libxml-perl -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-libxml-perl_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-libxml-perl_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-libxml-perl_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/app/perl-libxml-perl_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/app/perl-libxml-perl_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2c389b5c1a8ae6912739f66e85a10abc791fcee7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/app/perl-libxml-perl_server.py @@ -0,0 +1,180 @@ +import subprocess +from pathlib import Path +from typing import Optional, List +import logging + +# Set up logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# @mcp.tool() +def perl_interpreter( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + execute_program: Optional[List[str]] = None, + execute_program_extended: Optional[List[str]] = None, + check_syntax_only: bool = False, + run_debugger: bool = False, + debugger_module: Optional[str] = None, + debugging_flags: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + taint_warnings: bool = False, + taint_checks: bool = False, + include_dirs: Optional[List[Path]] = None, + use_modules: Optional[List[str]] = None, + use_modules_no_import: Optional[List[str]] = None, + no_modules: Optional[List[str]] = None, + loop_program: bool = False, + loop_and_print: bool = False, + autosplit: bool = False, + split_pattern: Optional[str] = None, + in_place_edit: bool = False, + backup_extension: Optional[str] = None, + line_ending_processing: Optional[str] = None, + record_separator: Optional[str] = None, + parse_switches: bool = False, + search_path: bool = False, + dump_core: bool = False, + allow_unsafe: bool = False, + no_sitecustomize: bool = False, + unicode_features: Optional[str] = None, + extract_script: bool = False, + change_dir_before_extract: Optional[Path] = None, + print_version: bool = False, + print_config: bool = False, + config_variable: Optional[str] = None, +): + """ + Executes scripts using the Perl interpreter. + + This tool is a comprehensive wrapper for the `perl` command-line executable. + It allows for running Perl scripts from files or directly as one-liners, + and provides access to a wide range of Perl's execution switches for + debugging, module loading, and input/output processing. + """ + # --- Input Validation --- + if not any([programfile, execute_program, execute_program_extended, print_version, print_config]): + raise ValueError("Either a program file, a program string (-e or -E), or an informational flag (-v or -V) must be provided.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"Program file not found: {programfile}") + + if loop_program and loop_and_print: + raise ValueError("Cannot use -n (loop_program) and -p (loop_and_print) simultaneously.") + + if enable_all_warnings and disable_all_warnings: + raise ValueError("Cannot use -W (enable_all_warnings) and -X (disable_all_warnings) simultaneously.") + + if backup_extension is not None and not in_place_edit: + raise ValueError("backup_extension (-i) requires in_place_edit (-i) to be True.") + + if config_variable and not print_config: + raise ValueError("config_variable (-V:variable) requires print_config (-V) to be True.") + + if debugger_module and not run_debugger: + raise ValueError("debugger_module (-d:debugger) requires run_debugger (-d) to be True.") + + if change_dir_before_extract and not extract_script: + raise ValueError("change_dir_before_extract (-x directory) requires extract_script (-x) to be True.") + + # --- Command Construction --- + cmd = ["perl"] + + if record_separator is not None: cmd.append(f"-0{record_separator}") + if autosplit: cmd.append("-a") + if unicode_features is not None: cmd.append(f"-C{unicode_features}") + if check_syntax_only: cmd.append("-c") + if run_debugger: + debug_flag = "-d" + if debugger_module: debug_flag += f":{debugger_module}" + cmd.append(debug_flag) + if debugging_flags is not None: cmd.append(f"-D{debugging_flags}") + if execute_program: + for prog in execute_program: cmd.extend(["-e", prog]) + if execute_program_extended: + for prog in execute_program_extended: cmd.extend(["-E", prog]) + if no_sitecustomize: cmd.append("-f") + if split_pattern is not None: cmd.append(f"-F{split_pattern}") + if in_place_edit: + i_flag = "-i" + if backup_extension is not None: i_flag += backup_extension + cmd.append(i_flag) + if include_dirs: + for directory in include_dirs: cmd.extend(["-I", str(directory)]) + if line_ending_processing is not None: cmd.append(f"-l{line_ending_processing}") + if use_modules: + for module in use_modules: cmd.append(f"-M{module}") + if use_modules_no_import: + for module in use_modules_no_import: cmd.append(f"-m{module}") + if no_modules: + for module in no_modules: cmd.append(f"-M-{module}") + if loop_program: cmd.append("-n") + if loop_and_print: cmd.append("-p") + if parse_switches: cmd.append("-s") + if search_path: cmd.append("-S") + if taint_warnings: cmd.append("-t") + if taint_checks: cmd.append("-T") + if dump_core: cmd.append("-u") + if allow_unsafe: cmd.append("-U") + if print_version: cmd.append("-v") + if print_config: + v_flag = "-V" + if config_variable: v_flag += f":{config_variable}" + cmd.append(v_flag) + if enable_warnings: cmd.append("-w") + if enable_all_warnings: cmd.append("-W") + if extract_script: + x_flag = "-x" + if change_dir_before_extract: x_flag += str(change_dir_before_extract) + cmd.append(x_flag) + if disable_all_warnings: cmd.append("-X") + + if programfile: + cmd.append(str(programfile)) + if arguments: + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=False, # Set to False to handle non-zero exit codes manually + ) + + if result.returncode != 0: + logger.error(f"Command failed with exit code {result.returncode}") + logger.error(f"Stderr: {result.stderr}") + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "return_code": result.returncode, + "output_files": [] + } + except FileNotFoundError: + stderr_msg = "Error: 'perl' command not found. Please ensure Perl is installed and in the system's PATH." + logger.error(stderr_msg) + return { + "command_executed": command_executed, + "stdout": "", + "stderr": stderr_msg, + "return_code": 1, + "output_files": [] + } + except Exception as e: + logger.error(f"An unexpected error occurred: {e}") + return { + "command_executed": command_executed, + "stdout": "", + "stderr": str(e), + "return_code": 1, + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/app/perl-libxml-perl_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/app/perl-libxml-perl_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c90582dfa6c66a4f8c4fe9c8be7c724d4f9df9cb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/app/perl-libxml-perl_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/app/perl-libxml-perl_server.py') +SERVER_NAME = 'biosci_perl_libxml_perl' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2f296c50f5a1823252191716f4a5a2b092641e02 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-libxml-perl: + build: . + image: mcp-perl-libxml-perl:latest + container_name: mcp-perl-libxml-perl + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-libxml-perl + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e1c8320a14489a7a62de9bb968e7ae5ab2037e9a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-libxml-perl + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-libxml-perl/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5220ae243942ab8f8c33318264b70ce3fd7080b6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-list-moreutils-xs via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-list-moreutils-xs -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-list-moreutils-xs_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-list-moreutils-xs_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-list-moreutils-xs_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/app/perl-list-moreutils-xs_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/app/perl-list-moreutils-xs_server.py new file mode 100644 index 0000000000000000000000000000000000000000..89252dbadb4120effcc7c11d00ff752f43935436 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/app/perl-list-moreutils-xs_server.py @@ -0,0 +1,262 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union +import os +import tempfile + +# No need to import mcp, as per instructions. + +@mcp.tool() +def run_perl_script( + program_file: Optional[Path] = None, + program_arguments: Optional[List[str]] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger_arg: Optional[str] = None, + debugging_flags: Optional[str] = None, + program_lines: Optional[List[str]] = None, + program_lines_extended: Optional[List[str]] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_terminator: Optional[str] = None, + use_modules: Optional[List[str]] = None, + no_modules: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + rudimentary_switch_parsing: bool = False, + search_path_for_programfile: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core_on_parse_error: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang: bool = False, + ignore_text_before_shebang_dir: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> dict: + """ + Executes a Perl script or one-liner with various Perl interpreter switches. + + This tool wraps the 'perl' command, allowing users to run Perl programs + and leverage modules like List::MoreUtils::XS (if available in the environment). + The 'perl-list-moreutils-xs' package provides the List::MoreUtils::XS module, + which can be used within your Perl script (e.g., `use List::MoreUtils::XS;`). + + Args: + program_file: Path to the Perl program file to execute. + program_arguments: Arguments to pass to the Perl program. + record_separator: Specify record separator. Use '0' for NUL, '0777' for paragraph mode, + or an empty string '' for just -0 (NUL). Set to None to disable. + autosplit: Enable autosplit mode with -n or -p (splits $_ into @F). + unicode_features: Enables listed Unicode features (e.g., 'all', 'io,say'). + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). + debugger_arg: Run program under debugger. Use a string like 'MyDebugger' for -d:MyDebugger, + or an empty string '' for just -d. Set to None to disable. + debugging_flags: Set debugging flags (argument is a bit mask or alphabets). + program_lines: One or more lines of Perl program code to execute (for -e). + program_lines_extended: One or more lines of Perl program code, like -e, but enables all optional features (for -E). + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. + split_pattern: split() pattern for -a switch (e.g., '/\t/'). + edit_in_place_extension: Edit <> files in place. Makes backup if extension supplied (e.g., '.bak'). + Use an empty string '' for no backup (modifies file directly). + Set to None to disable in-place editing. + include_directories: Specify @INC/#include directories. + line_ending_terminator: Enable line ending processing, specifies line terminator. + Use '0' for NUL, '0777' for paragraph mode, or an empty string '' for just -l. + Set to None to disable. + use_modules: Execute 'use module...' before executing program (e.g., ['List::MoreUtils::XS', 'MyModule qw(func)']). + Corresponds to -M or -m. + no_modules: Execute 'no module...' before executing program (e.g., ['MyModule']). Corresponds to -M-. + loop_around_program: Assume "while (<>) { ... }" loop around program (for -n). + loop_and_print: Assume loop like -n but print line also, like sed (for -p). + rudimentary_switch_parsing: Enable rudimentary parsing for switches after programfile. + search_path_for_programfile: Look for programfile using PATH environment variable. + tainting_warnings: Enable tainting warnings. + tainting_checks: Enable tainting checks. + dump_core_on_parse_error: Dump core after parsing program. + allow_unsafe_operations: Allow unsafe operations. + print_version: Print version, patchlevel and license (-v). + print_config: Print configuration summary or a single Config.pm variable (-V). + Use an empty string '' for summary (-V), or a variable name like 'archname' for -V:archname. + Set to None to disable. + enable_warnings: Enable many useful warnings (-w). + enable_all_warnings: Enable all warnings (-W). + ignore_text_before_shebang: Ignore text before #!perl line (-x). + ignore_text_before_shebang_dir: Ignore text before #!perl line and optionally cd to directory (-x[directory]). + disable_all_warnings: Disable all warnings (-X). + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + command = ["perl"] + output_files = [] + + # --- Input Validation --- + if program_file: + if not program_file.is_file(): + raise ValueError(f"Program file not found: {program_file}") + + if not program_file and not (program_lines or program_lines_extended): + raise ValueError("Either 'program_file' or at least one of 'program_lines' or 'program_lines_extended' must be provided.") + + if program_file and (program_lines or program_lines_extended): + raise ValueError("Cannot provide both 'program_file' and 'program_lines'/'program_lines_extended'. Choose one method for program input.") + + if loop_around_program and loop_and_print: + raise ValueError("Options 'loop_around_program' (-n) and 'loop_and_print' (-p) are mutually exclusive.") + + if print_version and print_config is not None: + raise ValueError("Option 'print_version' (-v) cannot be combined with '-V' or '-V:variable'.") + + if disable_all_warnings: + if enable_warnings or enable_all_warnings: + raise ValueError("Option 'disable_all_warnings' (-X) cannot be combined with 'enable_warnings' (-w) or 'enable_all_warnings' (-W).") + elif enable_all_warnings: + if enable_warnings: + raise ValueError("Option 'enable_all_warnings' (-W) implies 'enable_warnings' (-w), so they cannot be combined explicitly.") + + if edit_in_place_extension is not None: + if not program_file: + raise ValueError("Option 'edit_in_place_extension' (-i) requires 'program_file' to be specified.") + # The original file is modified. If an extension is provided, a backup is made. + if edit_in_place_extension != "": # If extension is provided, a backup is made + backup_file = Path(str(program_file) + edit_in_place_extension) + output_files.append(str(backup_file)) + output_files.append(str(program_file)) # The original file is modified in place + + if ignore_text_before_shebang and ignore_text_before_shebang_dir: + raise ValueError("Cannot use both -x (no directory) and -x[directory].") + if ignore_text_before_shebang_dir: + if not ignore_text_before_shebang_dir.is_dir(): + raise ValueError(f"Directory for -x not found: {ignore_text_before_shebang_dir}") + if include_directories: + for d in include_directories: + if not d.is_dir(): + raise ValueError(f"Include directory not found: {d}") + + + # --- Build Command --- + + if record_separator is not None: + command.append(f"-0{record_separator}") + if autosplit: + command.append("-a") + if unicode_features: + command.append(f"-C{unicode_features}") + if check_syntax_only: + command.append("-c") + if debugger_arg is not None: + if debugger_arg == "": + command.append("-d") + else: + command.append(f"-d:{debugger_arg}") + if debugging_flags: + command.append(f"-D{debugging_flags}") + if program_lines: + for line in program_lines: + command.extend(["-e", line]) + if program_lines_extended: + for line in program_lines_extended: + command.extend(["-E", line]) + if no_sitecustomize: + command.append("-f") + if split_pattern: + command.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + command.append(f"-i{edit_in_place_extension}") + if include_directories: + for d in include_directories: + command.extend(["-I", str(d)]) + if line_ending_terminator is not None: + command.append(f"-l{line_ending_terminator}") + + if use_modules: + for module_spec in use_modules: + command.append(f"-M{module_spec}") + if no_modules: + for module_spec in no_modules: + command.append(f"-M-{module_spec}") + + if loop_around_program: + command.append("-n") + if loop_and_print: + command.append("-p") + if rudimentary_switch_parsing: + command.append("-s") + if search_path_for_programfile: + command.append("-S") + if tainting_warnings: + command.append("-t") + if tainting_checks: + command.append("-T") + if dump_core_on_parse_error: + command.append("-u") + if allow_unsafe_operations: + command.append("-U") + if print_version: + command.append("-v") + if print_config is not None: + if print_config == "": + command.append("-V") + else: + command.append(f"-V:{print_config}") + if enable_warnings: + command.append("-w") + if enable_all_warnings: + command.append("-W") + if ignore_text_before_shebang_dir: + command.append(f"-x{ignore_text_before_shebang_dir}") + elif ignore_text_before_shebang: + command.append("-x") + if disable_all_warnings: + command.append("-X") + + # Add program file and its arguments last + if program_file: + command.append(str(program_file)) + if program_arguments: + command.extend(program_arguments) + + # --- Execute Command --- + command_executed = " ".join(str(arg) for arg in command) + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": output_files + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Ensure Perl is installed and in your PATH.", + "error": "Perl executable not found.", + "returncode": 127, + "output_files": output_files + } + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/app/perl-list-moreutils-xs_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/app/perl-list-moreutils-xs_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2691a24d6a7510f8767536161cb09f4dd8a12434 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/app/perl-list-moreutils-xs_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/app/perl-list-moreutils-xs_server.py') +SERVER_NAME = 'biosci_perl_list_moreutils_xs' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..bdec36fe3fdc756016140c7439ea6441139be820 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-list-moreutils-xs: + build: . + image: mcp-perl-list-moreutils-xs:latest + container_name: mcp-perl-list-moreutils-xs + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-list-moreutils-xs + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..749ed1ec7787472024efd71738867bcc02c9cf38 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-list-moreutils-xs + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils-xs/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7fe2222d2c3b01f8391ccda2a0d690d823d472da --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-list-moreutils via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-list-moreutils -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-list-moreutils_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-list-moreutils_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-list-moreutils_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/app/perl-list-moreutils_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/app/perl-list-moreutils_server.py new file mode 100644 index 0000000000000000000000000000000000000000..aec81934e0ab77c19e925d705cae5189ec50beb1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/app/perl-list-moreutils_server.py @@ -0,0 +1,344 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union +import tempfile + +def _run_perl_command(script: str, input_data: Optional[str] = None, input_file: Optional[str] = None): + """ + Internal helper to execute Perl one-liners using List::MoreUtils. + """ + cmd = ["perl", "-MList::MoreUtils=:all", "-e", script] + + stdin_handle = None + if input_file: + input_path = Path(input_file) + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + stdin_handle = open(input_path, "r") + + try: + process = subprocess.run( + cmd, + input=input_data if not input_file else None, + stdin=stdin_handle, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "return_code": process.returncode + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "error": str(e) + } + finally: + if stdin_handle: + stdin_handle.close() + +@mcp.tool() +def list_moreutils_uniq( + input_file: str, + output_file: Optional[str] = None, +): + """ + Returns a list of the elements, in the order they first appear, with all duplicates removed. + + Args: + input_file: Path to the input file (one element per line). + output_file: Optional path to save the unique elements. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} does not exist."} + + # Perl script to read lines, chomp them, run uniq, and print + script = 'print uniq();' + + result = _run_perl_command(script, input_file=input_file) + + if output_file and "stdout" in result: + out_path = Path(output_file) + out_path.write_text(result["stdout"]) + result["output_files"] = [str(out_path)] + + return result + +@mcp.tool() +def list_moreutils_singleton( + input_file: str, + output_file: Optional[str] = None, +): + """ + Returns a list of the elements which appear exactly once in the input. + + Args: + input_file: Path to the input file (one element per line). + output_file: Optional path to save the singleton elements. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} does not exist."} + + script = 'print singleton();' + result = _run_perl_command(script, input_file=input_file) + + if output_file and "stdout" in result: + out_path = Path(output_file) + out_path.write_text(result["stdout"]) + result["output_files"] = [str(out_path)] + + return result + +@mcp.tool() +def list_moreutils_mesh( + file1: str, + file2: str, + output_file: Optional[str] = None, +): + """ + Interleaves the elements of two files. Also known as 'zip'. + + Args: + file1: Path to the first input file. + file2: Path to the second input file. + output_file: Optional path to save the meshed output. + """ + p1 = Path(file1) + p2 = Path(file2) + if not p1.exists() or not p2.exists(): + return {"error": "One or both input files do not exist."} + + # Read both files into arrays and mesh them + script = ( + 'open my $f1, "<", $ARGV[0] or die; my @a = <$f1>; ' + 'open my $f2, "<", $ARGV[1] or die; my @b = <$f2>; ' + 'print mesh @a, @b;' + ) + + cmd = ["perl", "-MList::MoreUtils=:all", "-e", script, str(p1), str(p2)] + + try: + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + result = { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr + } + if output_file: + out_path = Path(output_file) + out_path.write_text(process.stdout) + result["output_files"] = [str(out_path)] + return result + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def list_moreutils_minmax( + input_file: str, +): + """ + Calculates the minimum and maximum values in a list of numbers. + + Args: + input_file: Path to a file containing one number per line. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} does not exist."} + + script = 'my @a = ; my ($min, $max) = minmax @a; print "Min: $min\nMax: $max\n";' + return _run_perl_command(script, input_file=input_file) + +@mcp.tool() +def list_moreutils_junction( + input_file: str, + mode: str = "any", + pattern: str = ".", +): + """ + Performs junction logic (any, all, none, notall) on a list based on a regex pattern. + + Args: + input_file: Path to the input file. + mode: Logic mode to use: 'any', 'all', 'none', or 'notall'. + pattern: Regex pattern to match against each line. + """ + if mode not in ["any", "all", "none", "notall"]: + return {"error": "Mode must be one of: any, all, none, notall"} + + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} does not exist."} + + # Escape pattern for Perl + safe_pattern = pattern.replace("'", "\\'") + script = f'my @a = ; if ({mode} {{ m/{safe_pattern}/ }} @a) {{ print "True\\n" }} else {{ print "False\\n" }}' + + return _run_perl_command(script, input_file=input_file) + +@mcp.tool() +def list_moreutils_counting( + input_file: str, + mode: str = "true", + pattern: str = ".", +): + """ + Counts how many elements match (true) or do not match (false) a pattern. + + Args: + input_file: Path to the input file. + mode: 'true' to count matches, 'false' to count non-matches. + pattern: Regex pattern to match. + """ + if mode not in ["true", "false"]: + return {"error": "Mode must be 'true' or 'false'"} + + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} does not exist."} + + safe_pattern = pattern.replace("'", "\\'") + script = f'my @a = ; print {mode} {{ m/{safe_pattern}/ }} @a;' + + return _run_perl_command(script, input_file=input_file) + +@mcp.tool() +def list_moreutils_filtering( + input_file: str, + mode: str = "before", + pattern: str = ".", + include_boundary: bool = False, + output_file: Optional[str] = None, +): + """ + Filters a list based on a boundary pattern. + + Args: + input_file: Path to the input file. + mode: 'before' (elements before match) or 'after' (elements after match). + pattern: Regex pattern defining the boundary. + include_boundary: Whether to include the element that matched the pattern. + output_file: Optional path to save results. + """ + if mode not in ["before", "after"]: + return {"error": "Mode must be 'before' or 'after'"} + + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} does not exist."} + + func = mode + if include_boundary: + func += "_incl" + + safe_pattern = pattern.replace("'", "\\'") + script = f'my @a = ; print {func} {{ m/{safe_pattern}/ }} @a;' + + result = _run_perl_command(script, input_file=input_file) + + if output_file and "stdout" in result: + out_path = Path(output_file) + out_path.write_text(result["stdout"]) + result["output_files"] = [str(out_path)] + + return result + +@mcp.tool() +def list_moreutils_apply( + input_file: str, + perl_expression: str = "s/\\s+//g", + output_file: Optional[str] = None, +): + """ + Applies a Perl transformation to every element in the list. + + Args: + input_file: Path to the input file. + perl_expression: Perl code to apply to $_ (e.g., 's/foo/bar/' or '$_ = reverse'). + output_file: Optional path to save results. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} does not exist."} + + # apply { ... } @list returns the modified list + script = f'my @a = ; print apply {{ {perl_expression} }} @a;' + + result = _run_perl_command(script, input_file=input_file) + + if output_file and "stdout" in result: + out_path = Path(output_file) + out_path.write_text(result["stdout"]) + result["output_files"] = [str(out_path)] + + return result + +@mcp.tool() +def list_moreutils_indexes( + input_file: str, + pattern: str = ".", +): + """ + Returns the 0-based indices of all elements matching the pattern. + + Args: + input_file: Path to the input file. + pattern: Regex pattern to match. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} does not exist."} + + safe_pattern = pattern.replace("'", "\\'") + script = f'my @a = ; print join("\\n", indexes {{ m/{safe_pattern}/ }} @a);' + + return _run_perl_command(script, input_file=input_file) + +@mcp.tool() +def list_moreutils_part( + input_file: str, + perl_condition: str = "$_ =~ /pattern/ ? 0 : 1", + output_prefix: str = "part", +): + """ + Partitions a list into multiple files based on a Perl condition. + The condition should return an integer index (0, 1, 2...). + + Args: + input_file: Path to the input file. + perl_condition: Perl expression returning an index for each element. + output_prefix: Prefix for the generated partition files (e.g., part_0.txt, part_1.txt). + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} does not exist."} + + # This script partitions the list and writes each part to a separate file + script = ( + f'my @a = ; ' + f'my @parts = part {{ {perl_condition} }} @a; ' + f'for my $i (0 .. $#parts) {{ ' + f' if ($parts[$i]) {{ ' + f' open my $fh, ">", "{output_prefix}_$i.txt" or die; ' + f' print $fh @{{$parts[$i]}}; ' + f' close $fh; ' + f' print "{output_prefix}_$i.txt\\n"; ' + f' }} ' + f'}}' + ) + + result = _run_perl_command(script, input_file=input_file) + + if "stdout" in result: + files = result["stdout"].strip().split("\n") + result["output_files"] = [f for f in files if f] + + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/app/perl-list-moreutils_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/app/perl-list-moreutils_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0b13db3129f0a7638fbb35fa2412350851ea0d63 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/app/perl-list-moreutils_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/app/perl-list-moreutils_server.py') +SERVER_NAME = 'biosci_perl_list_moreutils' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..810993544ab20ad8894bbd61b484efed9c376fbd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-list-moreutils: + build: . + image: mcp-perl-list-moreutils:latest + container_name: mcp-perl-list-moreutils + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-list-moreutils + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ca225013df9e37225c0933287c09b4949b1eac45 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-list-moreutils + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-list-moreutils/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bda10ebc68b470f7fd03e78bb81d45d2d9caf575 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-locale-maketext-simple via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-locale-maketext-simple -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-locale-maketext-simple_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-locale-maketext-simple_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-locale-maketext-simple_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/app/perl-locale-maketext-simple_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/app/perl-locale-maketext-simple_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3fb7e5c2815552e9f814606f78029f1055c81980 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/app/perl-locale-maketext-simple_server.py @@ -0,0 +1,166 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# In a real MCP environment, the @mcp.tool decorator is provided by the framework. +# No import is needed in the final script as per the instructions. + +@mcp.tool() +def perl_interpreter( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + execute_program: Optional[List[str]] = None, + execute_program_with_features: Optional[List[str]] = None, + check_syntax: bool = False, + print_version: bool = False, + print_config_variable: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + include_dirs: Optional[List[Path]] = None, + use_module: Optional[List[str]] = None, + no_module: Optional[List[str]] = None, + use_module_no_import: Optional[List[str]] = None, + no_module_no_import: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + autosplit: bool = False, + split_pattern: Optional[str] = None, + in_place_edit_extension: Optional[str] = None, + record_separator: Optional[str] = None, + line_ending_processing: Optional[str] = None, + taint_checks: bool = False, + taint_warnings: bool = False, + allow_unsafe_operations: bool = False, + search_path_for_program: bool = False, + enable_switch_parsing: bool = False, + unicode_features: Optional[str] = None, + debugger: Optional[str] = None, + debug_flags: Optional[str] = None, + no_sitecustomize: bool = False, + dump_core: bool = False, + extract_script_and_cd: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Provides a wrapper for the `perl` command-line interpreter. + + This tool can execute Perl scripts from files or strings and supports the full + range of standard Perl command-line switches. It is the underlying engine for + many Perl-based bioinformatics tools. + """ + # --- Input Validation --- + if not any([programfile, execute_program, execute_program_with_features, print_version, print_config_variable is not None]): + raise ValueError("At least one primary action is required: specify a 'programfile', 'execute_program', 'execute_program_with_features', 'print_version', or 'print_config_variable'.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"The specified program file does not exist: {programfile}") + + if include_dirs: + for directory in include_dirs: + if not directory.is_dir(): + raise NotADirectoryError(f"The specified include directory does not exist: {directory}") + + if extract_script_and_cd is not None: + if not extract_script_and_cd.is_dir(): + raise NotADirectoryError(f"The directory specified for the -x option does not exist: {extract_script_and_cd}") + + # --- Command Construction --- + cmd = ["perl"] + + # Flags with optional values + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if debugger is not None: + cmd.append(f"-d{debugger}") + if debug_flags is not None: + cmd.append(f"-D{debug_flags}") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if in_place_edit_extension is not None: + cmd.append(f"-i{in_place_edit_extension}") + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + if print_config_variable is not None: + cmd.append(f"-V{print_config_variable}") + if extract_script_and_cd is not None: + cmd.extend(["-x", str(extract_script_and_cd)]) + + # Boolean flags + if autosplit: cmd.append("-a") + if check_syntax: cmd.append("-c") + if no_sitecustomize: cmd.append("-f") + if loop_around_program: cmd.append("-n") + if loop_and_print: cmd.append("-p") + if enable_switch_parsing: cmd.append("-s") + if search_path_for_program: cmd.append("-S") + if taint_warnings: cmd.append("-t") + if taint_checks: cmd.append("-T") + if dump_core: cmd.append("-u") + if allow_unsafe_operations: cmd.append("-U") + if print_version: cmd.append("-v") + if enable_warnings: cmd.append("-w") + if enable_all_warnings: cmd.append("-W") + if disable_all_warnings: cmd.append("-X") + + # List-based arguments + if include_dirs: + for directory in include_dirs: + cmd.extend(["-I", str(directory)]) + if use_module: + for mod in use_module: + cmd.append(f"-M{mod}") + if no_module: + for mod in no_module: + cmd.append(f"-m{mod}") # Corrected from -M- to -m as per some perl versions, though -M- is also valid. Sticking to distinct params. + if use_module_no_import: + for mod in use_module_no_import: + cmd.append(f"-m{mod}") + if no_module_no_import: + for mod in no_module_no_import: + cmd.append(f"-M-{mod}") # Corrected from -m- to -M- + if execute_program: + for prog_line in execute_program: + cmd.extend(["-e", prog_line]) + if execute_program_with_features: + for prog_line in execute_program_with_features: + cmd.extend(["-E", prog_line]) + + # Positional arguments + if programfile: + cmd.append(str(programfile)) + if arguments: + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_string = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_string, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] # Output files are script-dependent and not predictable + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_string, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed with return code {e.returncode}", + "return_code": e.returncode + } + except FileNotFoundError: + return { + "command_executed": command_string, + "stdout": "", + "stderr": "The 'perl' executable was not found in the system's PATH.", + "error": "Executable not found", + "return_code": -1 + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/app/perl-locale-maketext-simple_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/app/perl-locale-maketext-simple_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ba2289fd71fb32f231ea29ad97f0ec034f0ccc2d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/app/perl-locale-maketext-simple_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/app/perl-locale-maketext-simple_server.py') +SERVER_NAME = 'biosci_perl_locale_maketext_simple' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..897f1f59ceec4eada3ead655cfd106cf72e75719 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-locale-maketext-simple: + build: . + image: mcp-perl-locale-maketext-simple:latest + container_name: mcp-perl-locale-maketext-simple + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-locale-maketext-simple + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..170d1b73b8d29116d4c23ce44ec14eb4f6620c22 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-locale-maketext-simple + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..579757d7023147b4e4c00eb8bb2ba13bf8d4e236 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-lwp-mediatypes via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-lwp-mediatypes -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-lwp-mediatypes_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-lwp-mediatypes_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-lwp-mediatypes_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/app/perl-lwp-mediatypes_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/app/perl-lwp-mediatypes_server.py new file mode 100644 index 0000000000000000000000000000000000000000..30466ef05f96e39d3426e913866f28d5f2b3dd19 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/app/perl-lwp-mediatypes_server.py @@ -0,0 +1,248 @@ +import subprocess +import json +from pathlib import Path +from typing import List, Optional, Dict, Union, Any + +# Helper function to run Perl scripts +def _run_perl_script(script_content: str, args: List[str]) -> Dict[str, Any]: + """ + Executes a Perl script with given arguments and captures output. + """ + command = ["perl", "-MJSON", "-e", script_content, *args] + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + + stdout_data = result.stdout.strip() + stderr_data = result.stderr.strip() + + # Attempt to parse JSON output if available + parsed_output = {} + if stdout_data: + try: + parsed_output = json.loads(stdout_data) + except json.JSONDecodeError: + # If stdout is not JSON, return it as raw_stdout + parsed_output = {"raw_stdout": stdout_data} + + return { + "command_executed": " ".join(command), + "stdout": parsed_output, + "stderr": stderr_data, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "error": str(e), + "returncode": e.returncode, + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'perl' command not found. Ensure Perl is installed and in your PATH.", + "error": "Perl executable not found", + "returncode": 127, + "output_files": [], + } + + +@mcp.tool() +def guess_media_type_for_file_or_url( + file_or_url: str, +) -> Dict[str, Any]: + """ + Guesses the media type and encoding for a given file path or URL. + + This function uses the LWP::MediaTypes Perl module's guess_media_type function + to determine the content type and any associated content encodings. + + Args: + file_or_url: The path to a file or a URL string for which to guess the media type. + + Returns: + A dictionary containing the command executed, stdout (parsed JSON with + 'content_type' and 'content_encodings'), stderr, and any output files. + The 'content_type' will be a string like "text/html", and 'content_encodings' + will be a list of strings (e.g., ["gzip"]). If the type cannot be deduced, + it might return "text/plain" or "application/octet-stream". + """ + if not file_or_url: + raise ValueError("file_or_url cannot be empty.") + + perl_script = """ + use LWP::MediaTypes qw(guess_media_type); + use JSON; + my $input = shift @ARGV; + my ($type, @encodings) = guess_media_type($input); + my %result = ( + "content_type" => $type, + "content_encodings" => \\@encodings + ); + print encode_json(\\%result) . "\\n"; + """ + return _run_perl_script(perl_script, [file_or_url]) + + +@mcp.tool() +def get_media_suffixes( + media_types: List[str], +) -> Dict[str, Any]: + """ + Returns all file suffixes that can be used to denote the specified media type(s). + + Wildcard types (e.g., 'image/*') are supported. In a scalar context (which is + how the Perl script will effectively operate for a single type), it would return + the first suffix found. This tool returns all suffixes found for all provided types. + + Args: + media_types: A list of media type strings (e.g., ["image/*", "audio/basic", "text/html"]). + + Returns: + A dictionary containing the command executed, stdout (parsed JSON with + a 'suffixes' list), stderr, and any output files. + """ + if not media_types: + raise ValueError("media_types list cannot be empty.") + if not all(isinstance(mt, str) and mt for mt in media_types): + raise ValueError("All media_types must be non-empty strings.") + + perl_script = """ + use LWP::MediaTypes qw(media_suffix); + use JSON; + my @types = @ARGV; + my @suffixes = media_suffix(@types); + my %result = ( + "suffixes" => \\@suffixes + ); + print encode_json(\\%result) . "\\n"; + """ + return _run_perl_script(perl_script, media_types) + + +@mcp.tool() +def add_media_type_mapping( + media_type: str, + extensions: List[str], +) -> Dict[str, Any]: + """ + Associates a list of file extensions with a given media type. + + This mapping is temporary and only applies to the current Perl process execution. + Subsequent calls to other LWP::MediaTypes functions within the same process + might use this new mapping, but each MCP tool call runs in a new process. + + Args: + media_type: The media type string (e.g., "x-world/x-vrml"). + extensions: A list of file extensions (e.g., ["wrl", "vrml"]). + + Returns: + A dictionary confirming the operation, including the command executed, + stdout (parsed JSON with 'status' and 'message'), stderr, and output files. + """ + if not media_type: + raise ValueError("media_type cannot be empty.") + if not isinstance(media_type, str): + raise TypeError("media_type must be a string.") + if not extensions: + raise ValueError("extensions list cannot be empty.") + if not all(isinstance(ext, str) and ext for ext in extensions): + raise ValueError("All extensions must be non-empty strings.") + + perl_script = """ + use LWP::MediaTypes qw(add_type); + use JSON; + my $type = shift @ARGV; + my @exts = @ARGV; + add_type($type => @exts); + print encode_json({"status" => "success", "message" => "Type added: $type with extensions " . join(", ", @exts)}) . "\\n"; + """ + return _run_perl_script(perl_script, [media_type, *extensions]) + + +@mcp.tool() +def add_encoding_mapping( + encoding_type: str, + extensions: List[str], +) -> Dict[str, Any]: + """ + Associates a list of file extensions with an encoding type. + + This mapping is temporary and only applies to the current Perl process execution. + Subsequent calls to other LWP::MediaTypes functions within the same process + might use this new mapping, but each MCP tool call runs in a new process. + + Args: + encoding_type: The encoding type string (e.g., "x-gzip"). + extensions: A list of file extensions (e.g., ["gz"]). + + Returns: + A dictionary confirming the operation, including the command executed, + stdout (parsed JSON with 'status' and 'message'), stderr, and output files. + """ + if not encoding_type: + raise ValueError("encoding_type cannot be empty.") + if not isinstance(encoding_type, str): + raise TypeError("encoding_type must be a string.") + if not extensions: + raise ValueError("extensions list cannot be empty.") + if not all(isinstance(ext, str) and ext for ext in extensions): + raise ValueError("All extensions must be non-empty strings.") + + perl_script = """ + use LWP::MediaTypes qw(add_encoding); + use JSON; + my $type = shift @ARGV; + my @exts = @ARGV; + add_encoding($type => @exts); + print encode_json({"status" => "success", "message" => "Encoding added: $type with extensions " . join(", ", @exts)}) . "\\n"; + """ + return _run_perl_script(perl_script, [encoding_type, *extensions]) + + +@mcp.tool() +def read_custom_media_types_files( + media_type_files: List[Path], +) -> Dict[str, Any]: + """ + Parses one or more media types definition files and adds the type mappings found there. + + This allows loading custom or additional media type definitions beyond the default + `media.types` or `~/.media.types` files. The effect is temporary for the current + Perl process execution. + + Args: + media_type_files: A list of Path objects pointing to media types definition files. + + Returns: + A dictionary confirming the operation, including the command executed, + stdout (parsed JSON with 'status' and 'message'), stderr, and output files. + """ + if not media_type_files: + raise ValueError("media_type_files list cannot be empty.") + + file_paths_str: List[str] = [] + for f_path in media_type_files: + if not isinstance(f_path, Path): + raise TypeError(f"Expected Path object, got {type(f_path)} for {f_path}") + if not f_path.is_file(): + raise FileNotFoundError(f"Media type file not found: {f_path}") + file_paths_str.append(str(f_path)) + + perl_script = """ + use LWP::MediaTypes qw(read_media_types); + use JSON; + my @files = @ARGV; + read_media_types(@files); + print encode_json({"status" => "success", "message" => "Read media types from files: " . join(", ", @files)}) . "\\n"; + """ + return _run_perl_script(perl_script, file_paths_str) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/app/perl-lwp-mediatypes_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/app/perl-lwp-mediatypes_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f5f0a5f633a2e6e89f222ca7ea43fd1db8de053b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/app/perl-lwp-mediatypes_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/app/perl-lwp-mediatypes_server.py') +SERVER_NAME = 'biosci_perl_lwp_mediatypes' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0a9e7c60dcd8146399c76ecff94eb39255914a6d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-lwp-mediatypes: + build: . + image: mcp-perl-lwp-mediatypes:latest + container_name: mcp-perl-lwp-mediatypes + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-lwp-mediatypes + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..be8064aa5baa3cef92236097504a1e81db09e832 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-lwp-mediatypes + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-mediatypes/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f654e93ac1777e6465775d658907265c5d322f93 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-lwp-protocol-https via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-lwp-protocol-https -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-lwp-protocol-https_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-lwp-protocol-https_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-lwp-protocol-https_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/app/perl-lwp-protocol-https_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/app/perl-lwp-protocol-https_server.py new file mode 100644 index 0000000000000000000000000000000000000000..848584cd7fea18c1dce1ac7ba60b35e28f246d23 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/app/perl-lwp-protocol-https_server.py @@ -0,0 +1,127 @@ +import subprocess +import tempfile +import urllib.parse +import shutil +from pathlib import Path +from typing import Dict, Union, List + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +@mcp.tool() +def check_lwp_https_installation( + test_url: str = "https://www.google.com", + perl_executable: Path = Path("perl"), +) -> Dict[str, Union[str, List[str], bool]]: + """ + Verifies that the perl-lwp-protocol-https module is installed and functional. + + This tool executes a small Perl script that attempts to make an HTTPS GET + request to a specified URL using LWP::UserAgent. A successful execution + indicates that the LWP::Protocol::https module is correctly installed and + configured, as it is a prerequisite for LWP to handle https:// URLs. + + Args: + test_url: The HTTPS URL to use for the connection test. + Defaults to "https://www.google.com". + perl_executable: The path to or name of the Perl interpreter. + Defaults to "perl". + + Returns: + A dictionary containing the execution details and success status. + """ + # 1. Input Validation + parsed_url = urllib.parse.urlparse(test_url) + if not parsed_url.scheme == "https": + raise ValueError(f"The test_url must be an HTTPS URL (e.g., 'https://...'), but got '{test_url}'.") + + if not shutil.which(str(perl_executable)): + raise FileNotFoundError( + f"Perl executable '{perl_executable}' not found. " + "Please ensure it is installed and in your system's PATH, or provide the full path." + ) + + # 2. Create a temporary Perl script + # This script checks for LWP::UserAgent and attempts an HTTPS GET request. + # LWP::UserAgent automatically loads LWP::Protocol::https for https URLs. + # If the module is missing, the request will fail with a specific error. + perl_script_content = f""" + use strict; + use warnings; + use LWP::UserAgent; + + my $ua = LWP::UserAgent->new; + $ua->timeout(15); + $ua->env_proxy; + + my $response = $ua->get('{test_url}'); + + if ($response->is_success) {{ + print "Successfully fetched {test_url}\\n"; + print "Status: " . $response->status_line . "\\n"; + exit 0; + }} else {{ + print STDERR "Failed to fetch {test_url}\\n"; + print STDERR "Status: " . $response->status_line . "\\n"; + # Provide a helpful hint if the protocol is not supported + if ($response->code == 501 && $response->message =~ /Protocol scheme 'https' is not supported/) {{ + print STDERR "Hint: This error often means the LWP::Protocol::https module is not installed.\\n"; + print STDERR "Try installing it with: cpan LWP::Protocol::https\\n"; + }} + exit 1; + }} + """ + + command: List[str] = [] + + try: + with tempfile.NamedTemporaryFile(mode='w', delete=True, suffix=".pl", encoding='utf-8') as tmp_script: + tmp_script.write(perl_script_content) + tmp_script.flush() + + command = [str(perl_executable), tmp_script.name] + + # 3. Subprocess Execution + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding='utf-8', + errors='replace' + ) + + # 5. Structured Result Return (Success Case) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [], + "success": True + } + + # 4. Error Handling + except subprocess.CalledProcessError as e: + # This happens if the perl script exits with a non-zero status code. + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "success": False + } + except Exception as e: + # Catch any other unexpected Python errors. + return { + "command_executed": " ".join(command) if command else f"{perl_executable} ", + "stdout": "", + "stderr": f"An unexpected Python error occurred: {str(e)}", + "output_files": [], + "success": False + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/app/perl-lwp-protocol-https_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/app/perl-lwp-protocol-https_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..509cbfac22bd8838033a6f3671ca3a326af98b46 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/app/perl-lwp-protocol-https_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/app/perl-lwp-protocol-https_server.py') +SERVER_NAME = 'biosci_perl_lwp_protocol_https' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..9b9b76be6901e958ee41274dace109d25a08ad13 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-lwp-protocol-https: + build: . + image: mcp-perl-lwp-protocol-https:latest + container_name: mcp-perl-lwp-protocol-https + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-lwp-protocol-https + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..26456d8a1518243481706ecf56fe8eaa6c066527 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-lwp-protocol-https + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-protocol-https/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-simple/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-simple/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-lwp-simple/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e2420b9059a39b61e9327929d1aea2421e3e3416 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-mailtools via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-mailtools -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-mailtools_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-mailtools_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-mailtools_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/app/perl-mailtools_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/app/perl-mailtools_server.py new file mode 100644 index 0000000000000000000000000000000000000000..74c1e0aae166bdfca7d46ed6c536482fa9233002 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/app/perl-mailtools_server.py @@ -0,0 +1,212 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# MCP decorator is not imported as per the instructions. +# It is assumed to be available in the execution environment. + +# @mcp.tool() +def run_perl( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + program: Optional[str] = None, + enable_features_program: Optional[str] = None, + check_syntax_only: bool = False, + record_separator: Optional[str] = None, + autosplit: bool = False, + split_pattern: Optional[str] = None, + unicode_features: Optional[str] = None, + run_under_debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + disable_sitelib: bool = False, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + use_modules: Optional[List[str]] = None, + no_modules: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + parse_switches: bool = False, + search_path: bool = False, + enable_tainting_warnings: bool = False, + enable_tainting_checks: bool = False, + dump_core: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + ignore_text_before_shebang: Optional[Path] = None, +) -> dict: + """ + Executes the Perl interpreter. While the package is 'perl-mailtools', it is a library + and does not provide a direct command-line tool. This function wraps the 'perl' + executable itself, allowing execution of scripts that may use the MailTools modules. + + Args: + programfile: The Perl script file to execute. + arguments: Arguments to pass to the programfile. + program: A one-line program string to execute (-e). + enable_features_program: Like -e, but enables all optional features (-E). + check_syntax_only: Check syntax only; runs BEGIN and CHECK blocks (-c). + record_separator: Specify record separator (-0[octal]). + autosplit: Autosplit mode with -n or -p; splits $_ into @F (-a). + split_pattern: split() pattern for -a switch (-F/pattern/). + unicode_features: Enables the listed Unicode features (-C[number/list]). + run_under_debugger: Run program under a specified debugger (-d[:debugger]). + debugging_flags: Set debugging flags (-D[number/list]). + disable_sitelib: Don't do $sitelib/sitecustomize.pl at startup (-f). + edit_in_place_extension: Edit <> files in place; makes backup if extension is supplied (-i[extension]). + include_directories: Specify @INC/#include directory (-I). Can be specified multiple times. + line_ending_processing: Enable line ending processing, specifies line terminator (-l[octal]). + use_modules: Execute "use module..." before executing the program (-M). + no_modules: Execute "no module..." before executing the program (-m). + loop_around_program: Assume "while (<>) { ... }" loop around program (-n). + loop_and_print: Assume loop like -n but also print line, like sed (-p). + parse_switches: Enable rudimentary parsing for switches after programfile (-s). + search_path: Look for programfile using the PATH environment variable (-S). + enable_tainting_warnings: Enable tainting warnings (-t). + enable_tainting_checks: Enable tainting checks (-T). + dump_core: Dump core after parsing the program (-u). + allow_unsafe_operations: Allow unsafe operations (-U). + print_version: Print version, patchlevel, and license (-v). + print_config_summary: Print configuration summary or a single Config.pm variable (-V[:variable]). + enable_warnings: Enable many useful warnings (-w). + enable_all_warnings: Enable all warnings (-W). + disable_all_warnings: Disable all warnings (-X). + ignore_text_before_shebang: Ignore text before #!perl line, optionally cd to directory (-x[directory]). + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # --- Input Validation --- + program_sources = [programfile, program, enable_features_program] + if sum(p is not None for p in program_sources) > 1: + raise ValueError("Only one of 'programfile', 'program', or 'enable_features_program' can be specified.") + if all(p is None for p in program_sources) and not print_version and print_config_summary is None: + raise ValueError("Either 'programfile', 'program', 'enable_features_program', 'print_version', or 'print_config_summary' must be provided.") + + if arguments and not programfile: + raise ValueError("'arguments' can only be provided when 'programfile' is specified.") + + warning_flags = [enable_warnings, enable_all_warnings, disable_all_warnings] + if sum(warning_flags) > 1: + raise ValueError("Only one of 'enable_warnings', 'enable_all_warnings', or 'disable_all_warnings' can be set.") + + if loop_around_program and loop_and_print: + raise ValueError("'loop_around_program' (-n) and 'loop_and_print' (-p) are mutually exclusive.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"The program file '{programfile}' does not exist.") + + if include_directories: + for directory in include_directories: + if not directory.is_dir(): + raise NotADirectoryError(f"The include directory '{directory}' does not exist or is not a directory.") + + # --- Command Construction --- + cmd = ["perl"] + + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if run_under_debugger is not None: + cmd.append(f"-d{run_under_debugger}") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if disable_sitelib: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + cmd.append(f"-i{edit_in_place_extension}") + if include_directories: + for directory in include_directories: + cmd.extend(["-I", str(directory)]) + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + if use_modules: + for module in use_modules: + cmd.extend(["-M", module]) + if no_modules: + for module in no_modules: + cmd.extend(["-m", module]) + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if parse_switches: + cmd.append("-s") + if search_path: + cmd.append("-S") + if enable_tainting_warnings: + cmd.append("-t") + if enable_tainting_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if allow_unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config_summary is not None: + cmd.append(f"-V{print_config_summary}") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if disable_all_warnings: + cmd.append("-X") + if ignore_text_before_shebang is not None: + cmd.append(f"-x{ignore_text_before_shebang}") + + if program: + cmd.extend(["-e", program]) + elif enable_features_program: + cmd.extend(["-E", enable_features_program]) + elif programfile: + cmd.append(str(programfile)) + + if arguments: + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # --- Structured Result Return --- + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [] # Perl execution itself doesn't guarantee output files + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/app/perl-mailtools_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/app/perl-mailtools_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fcd173129e4b264da7b3b1e9a840001c4d48990d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/app/perl-mailtools_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/app/perl-mailtools_server.py') +SERVER_NAME = 'biosci_perl_mailtools' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..13d77c601c7e4d7d7763d49b3c545a5cb1c0fb39 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-mailtools: + build: . + image: mcp-perl-mailtools:latest + container_name: mcp-perl-mailtools + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-mailtools + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..17030d44043e37b09a99876150bc0e06516d254d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-mailtools + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mailtools/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8e1c93b29d3e5a1566628158daa83817e3f62e05 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-math-bezier via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-math-bezier -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-math-bezier_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-math-bezier_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-math-bezier_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/app/perl-math-bezier_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/app/perl-math-bezier_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5c050968eaf67335d144a20582820cd2de87467f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/app/perl-math-bezier_server.py @@ -0,0 +1,127 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# MCP decorator is omitted as per instructions, but this is an MCP-ready tool. +# import mcp + +@mcp.tool() +def run_perl_script( + programfile: Optional[Path] = None, + program: Optional[str] = None, + arguments: Optional[List[str]] = None, + include_dirs: Optional[List[Path]] = None, + modules: Optional[List[str]] = None, + check_syntax_only: bool = False, + enable_warnings: bool = False, + disable_warnings: bool = False, + enable_all_warnings: bool = False, + enable_taint_checks: bool = False, + enable_optional_features_for_program: bool = False, +) -> dict: + """ + Executes a Perl script using the Perl interpreter. + + This tool serves as a generic wrapper for the `perl` command-line interpreter. + The `perl-math-bezier` package is a library and does not provide a direct executable. + To use it, you must provide a Perl script or a one-liner that utilizes the library's modules (e.g., via the -M flag or 'use Math::Bezier;' in the script). + + Args: + programfile: Path to the Perl program file to execute. + program: A one-liner string of a Perl program to execute (uses -e or -E). + arguments: A list of arguments to pass to the program file. + include_dirs: A list of directories to add to Perl's @INC search path (uses -I). + modules: A list of Perl modules to load before executing the program (uses -M). + Example: ["Math::Bezier"] + check_syntax_only: If True, checks the syntax of the script without executing it (uses -c). + enable_warnings: If True, enables many useful warnings (uses -w). + disable_warnings: If True, disables all warnings (uses -X). This overrides other warning flags. + enable_all_warnings: If True, enables all warnings (uses -W). This is overridden by disable_warnings. + enable_taint_checks: If True, enables tainting checks for security (uses -T). + enable_optional_features_for_program: If True and `program` is specified, enables all optional features (uses -E instead of -e). + + Returns: + A dictionary containing the executed command, stdout, and stderr. + """ + # --- Input Validation --- + if not programfile and not program: + raise ValueError("Either 'programfile' or 'program' must be provided.") + if programfile and program: + raise ValueError("'programfile' and 'program' are mutually exclusive.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"The program file '{programfile}' does not exist.") + + if enable_optional_features_for_program and not program: + raise ValueError("'enable_optional_features_for_program' can only be True when 'program' is specified.") + + if include_dirs: + for directory in include_dirs: + if not directory.is_dir(): + raise FileNotFoundError(f"The include directory '{directory}' does not exist.") + + # --- Command Construction --- + cmd = ["perl"] + + # Handle warning flags (priority: -X > -W > -w) + if disable_warnings: + cmd.append("-X") + elif enable_all_warnings: + cmd.append("-W") + elif enable_warnings: + cmd.append("-w") + + if check_syntax_only: + cmd.append("-c") + + if enable_taint_checks: + cmd.append("-T") + + if include_dirs: + for directory in include_dirs: + cmd.extend(["-I", str(directory)]) + + if modules: + for module in modules: + cmd.extend(["-M", module]) + + # Handle program source + if program: + if enable_optional_features_for_program: + cmd.extend(["-E", program]) + else: + cmd.extend(["-e", program]) + elif programfile: + cmd.append(str(programfile)) + + # Add script arguments + if arguments: + cmd.extend(arguments) + + command_executed = " ".join(cmd) + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] # This tool does not explicitly create output files + } + except FileNotFoundError: + raise RuntimeError("Perl executable not found. Please ensure it is in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script execution failed with return code {e.returncode}", + "output_files": [] + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/app/perl-math-bezier_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/app/perl-math-bezier_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d1009f07bf93097bae339d647a6b1bfd81b07fce --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/app/perl-math-bezier_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/app/perl-math-bezier_server.py') +SERVER_NAME = 'biosci_perl_math_bezier' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..bcbe4db6c3bb16a4727957bd9bf6c56430ffdb2f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-math-bezier: + build: . + image: mcp-perl-math-bezier:latest + container_name: mcp-perl-math-bezier + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-math-bezier + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c7fb857c5b0096c00dc149299eb0d2fc44ae908d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-math-bezier + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-bezier/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..86136dd80799108ce940ccf5cea2cd829d6d3f6f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-math-cdf via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-math-cdf -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-math-cdf_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-math-cdf_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-math-cdf_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/app/perl-math-cdf_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/app/perl-math-cdf_server.py new file mode 100644 index 0000000000000000000000000000000000000000..032be6d07d2f60517f1de59ae1fb74fbe9282777 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/app/perl-math-cdf_server.py @@ -0,0 +1,595 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +# Since perl-math-cdf is a library without a direct CLI, +# we expose its functions as individual tools. Each tool +# executes a small Perl script to call the corresponding +# function from the Math::CDF module. + +# --- Beta Distribution --- + +@mcp.tool() +def pbeta(x: float, a: float, b: float): + """Calculates the cumulative probability for the beta distribution.""" + if not (0.0 <= x <= 1.0): + raise ValueError("Parameter 'x' must be between 0.0 and 1.0.") + if a <= 0.0: + raise ValueError("Parameter 'a' (shape1) must be positive.") + if b <= 0.0: + raise ValueError("Parameter 'b' (shape2) must be positive.") + + perl_script = f"use Math::CDF; print pbeta({x}, {a}, {b});" + cmd = ["perl", "-e", perl_script] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script execution failed with exit code {e.returncode}.", + "output_files": [] + } + +@mcp.tool() +def qbeta(p: float, a: float, b: float): + """Calculates the quantile (inverse CDF) for the beta distribution.""" + if not (0.0 <= p <= 1.0): + raise ValueError("Parameter 'p' (probability) must be between 0.0 and 1.0.") + if a <= 0.0: + raise ValueError("Parameter 'a' (shape1) must be positive.") + if b <= 0.0: + raise ValueError("Parameter 'b' (shape2) must be positive.") + + perl_script = f"use Math::CDF; print qbeta({p}, {a}, {b});" + cmd = ["perl", "-e", perl_script] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script execution failed with exit code {e.returncode}.", + "output_files": [] + } + +# --- Chi-square Distribution --- + +@mcp.tool() +def pchisq(x: float, df: int): + """Calculates the cumulative probability for the chi-square distribution.""" + if x < 0.0: + raise ValueError("Parameter 'x' must be non-negative.") + if df <= 0: + raise ValueError("Parameter 'df' (degrees of freedom) must be positive.") + + perl_script = f"use Math::CDF; print pchisq({x}, {df});" + cmd = ["perl", "-e", perl_script] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script execution failed with exit code {e.returncode}.", + "output_files": [] + } + +@mcp.tool() +def qchisq(p: float, df: int): + """Calculates the quantile (inverse CDF) for the chi-square distribution.""" + if not (0.0 <= p <= 1.0): + raise ValueError("Parameter 'p' (probability) must be between 0.0 and 1.0.") + if df <= 0: + raise ValueError("Parameter 'df' (degrees of freedom) must be positive.") + + perl_script = f"use Math::CDF; print qchisq({p}, {df});" + cmd = ["perl", "-e", perl_script] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script execution failed with exit code {e.returncode}.", + "output_files": [] + } + +# --- F-distribution --- + +@mcp.tool() +def pf(x: float, df1: int, df2: int): + """Calculates the cumulative probability for the F-distribution.""" + if x < 0.0: + raise ValueError("Parameter 'x' must be non-negative.") + if df1 <= 0: + raise ValueError("Parameter 'df1' (numerator degrees of freedom) must be positive.") + if df2 <= 0: + raise ValueError("Parameter 'df2' (denominator degrees of freedom) must be positive.") + + perl_script = f"use Math::CDF; print pf({x}, {df1}, {df2});" + cmd = ["perl", "-e", perl_script] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script execution failed with exit code {e.returncode}.", + "output_files": [] + } + +@mcp.tool() +def qf(p: float, df1: int, df2: int): + """Calculates the quantile (inverse CDF) for the F-distribution.""" + if not (0.0 <= p <= 1.0): + raise ValueError("Parameter 'p' (probability) must be between 0.0 and 1.0.") + if df1 <= 0: + raise ValueError("Parameter 'df1' (numerator degrees of freedom) must be positive.") + if df2 <= 0: + raise ValueError("Parameter 'df2' (denominator degrees of freedom) must be positive.") + + perl_script = f"use Math::CDF; print qf({p}, {df1}, {df2});" + cmd = ["perl", "-e", perl_script] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script execution failed with exit code {e.returncode}.", + "output_files": [] + } + +# --- Gamma Distribution --- + +@mcp.tool() +def pgamma(x: float, shape: float, scale: float = 1.0): + """Calculates the cumulative probability for the gamma distribution.""" + if x < 0.0: + raise ValueError("Parameter 'x' must be non-negative.") + if shape <= 0.0: + raise ValueError("Parameter 'shape' must be positive.") + if scale <= 0.0: + raise ValueError("Parameter 'scale' must be positive.") + + perl_script = f"use Math::CDF; print pgamma({x}, {shape}, {scale});" + cmd = ["perl", "-e", perl_script] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script execution failed with exit code {e.returncode}.", + "output_files": [] + } + +@mcp.tool() +def qgamma(p: float, shape: float, scale: float = 1.0): + """Calculates the quantile (inverse CDF) for the gamma distribution.""" + if not (0.0 <= p <= 1.0): + raise ValueError("Parameter 'p' (probability) must be between 0.0 and 1.0.") + if shape <= 0.0: + raise ValueError("Parameter 'shape' must be positive.") + if scale <= 0.0: + raise ValueError("Parameter 'scale' must be positive.") + + perl_script = f"use Math::CDF; print qgamma({p}, {shape}, {scale});" + cmd = ["perl", "-e", perl_script] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script execution failed with exit code {e.returncode}.", + "output_files": [] + } + +# --- Normal Distribution --- + +@mcp.tool() +def pnorm(x: float): + """Calculates the cumulative probability for the standard normal distribution.""" + perl_script = f"use Math::CDF; print pnorm({x});" + cmd = ["perl", "-e", perl_script] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script execution failed with exit code {e.returncode}.", + "output_files": [] + } + +@mcp.tool() +def qnorm(p: float): + """Calculates the quantile (inverse CDF) for the standard normal distribution.""" + if not (0.0 <= p <= 1.0): + raise ValueError("Parameter 'p' (probability) must be between 0.0 and 1.0.") + + perl_script = f"use Math::CDF; print qnorm({p});" + cmd = ["perl", "-e", perl_script] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script execution failed with exit code {e.returncode}.", + "output_files": [] + } + +# --- Student's t-distribution --- + +@mcp.tool() +def pt(x: float, df: int): + """Calculates the cumulative probability for Student's t-distribution.""" + if df <= 0: + raise ValueError("Parameter 'df' (degrees of freedom) must be positive.") + + perl_script = f"use Math::CDF; print pt({x}, {df});" + cmd = ["perl", "-e", perl_script] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script execution failed with exit code {e.returncode}.", + "output_files": [] + } + +@mcp.tool() +def qt(p: float, df: int): + """Calculates the quantile (inverse CDF) for Student's t-distribution.""" + if not (0.0 <= p <= 1.0): + raise ValueError("Parameter 'p' (probability) must be between 0.0 and 1.0.") + if df <= 0: + raise ValueError("Parameter 'df' (degrees of freedom) must be positive.") + + perl_script = f"use Math::CDF; print qt({p}, {df});" + cmd = ["perl", "-e", perl_script] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script execution failed with exit code {e.returncode}.", + "output_files": [] + } + +# --- Binomial Distribution --- + +@mcp.tool() +def pbinom(x: int, n: int, p: float): + """Calculates the cumulative probability for the binomial distribution.""" + if x < 0: + raise ValueError("Parameter 'x' (number of successes) must be non-negative.") + if n <= 0: + raise ValueError("Parameter 'n' (number of trials) must be positive.") + if not (0.0 <= p <= 1.0): + raise ValueError("Parameter 'p' (success probability) must be between 0.0 and 1.0.") + + perl_script = f"use Math::CDF; print pbinom({x}, {n}, {p});" + cmd = ["perl", "-e", perl_script] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script execution failed with exit code {e.returncode}.", + "output_files": [] + } + +@mcp.tool() +def qbinom(prob: float, n: int, p: float): + """Calculates the quantile (inverse CDF) for the binomial distribution.""" + if not (0.0 <= prob <= 1.0): + raise ValueError("Parameter 'prob' (probability) must be between 0.0 and 1.0.") + if n <= 0: + raise ValueError("Parameter 'n' (number of trials) must be positive.") + if not (0.0 <= p <= 1.0): + raise ValueError("Parameter 'p' (success probability) must be between 0.0 and 1.0.") + + perl_script = f"use Math::CDF; print qbinom({prob}, {n}, {p});" + cmd = ["perl", "-e", perl_script] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script execution failed with exit code {e.returncode}.", + "output_files": [] + } + +# --- Negative Binomial Distribution --- + +@mcp.tool() +def pnbinom(x: int, n: int, p: float): + """Calculates the cumulative probability for the negative binomial distribution.""" + if x < 0: + raise ValueError("Parameter 'x' (number of failures) must be non-negative.") + if n <= 0: + raise ValueError("Parameter 'n' (number of successes) must be positive.") + if not (0.0 <= p <= 1.0): + raise ValueError("Parameter 'p' (success probability) must be between 0.0 and 1.0.") + + perl_script = f"use Math::CDF; print pnbinom({x}, {n}, {p});" + cmd = ["perl", "-e", perl_script] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script execution failed with exit code {e.returncode}.", + "output_files": [] + } + +@mcp.tool() +def qnbinom(prob: float, n: int, p: float): + """Calculates the quantile (inverse CDF) for the negative binomial distribution.""" + if not (0.0 <= prob <= 1.0): + raise ValueError("Parameter 'prob' (probability) must be between 0.0 and 1.0.") + if n <= 0: + raise ValueError("Parameter 'n' (number of successes) must be positive.") + if not (0.0 <= p <= 1.0): + raise ValueError("Parameter 'p' (success probability) must be between 0.0 and 1.0.") + + perl_script = f"use Math::CDF; print qnbinom({prob}, {n}, {p});" + cmd = ["perl", "-e", perl_script] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script execution failed with exit code {e.returncode}.", + "output_files": [] + } + +# --- Poisson Distribution --- + +@mcp.tool() +def ppois(x: int, lambda_param: float): + """Calculates the cumulative probability for the Poisson distribution.""" + if x < 0: + raise ValueError("Parameter 'x' (number of events) must be non-negative.") + if lambda_param <= 0.0: + raise ValueError("Parameter 'lambda_param' (rate) must be positive.") + + perl_script = f"use Math::CDF; print ppois({x}, {lambda_param});" + cmd = ["perl", "-e", perl_script] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script execution failed with exit code {e.returncode}.", + "output_files": [] + } + +@mcp.tool() +def qpois(p: float, lambda_param: float): + """Calculates the quantile (inverse CDF) for the Poisson distribution.""" + if not (0.0 <= p <= 1.0): + raise ValueError("Parameter 'p' (probability) must be between 0.0 and 1.0.") + if lambda_param <= 0.0: + raise ValueError("Parameter 'lambda_param' (rate) must be positive.") + + perl_script = f"use Math::CDF; print qpois({p}, {lambda_param});" + cmd = ["perl", "-e", perl_script] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script execution failed with exit code {e.returncode}.", + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/app/perl-math-cdf_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/app/perl-math-cdf_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ef1dab619f09f204d98adaa3f1ef77a30980ae84 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/app/perl-math-cdf_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/app/perl-math-cdf_server.py') +SERVER_NAME = 'biosci_perl_math_cdf' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ed806955265b85a2f5ab3619730cd55b3af53e41 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-math-cdf: + build: . + image: mcp-perl-math-cdf:latest + container_name: mcp-perl-math-cdf + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-math-cdf + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cdd962bd77b072f7bd5d8cbd189d4bc9435825ce --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-math-cdf + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-cdf/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b42e8da9bd37d1ef99fcaa0933f749e78b4497fc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-math-derivative via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-math-derivative -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-math-derivative_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-math-derivative_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-math-derivative_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/app/perl-math-derivative_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/app/perl-math-derivative_server.py new file mode 100644 index 0000000000000000000000000000000000000000..24c71d0d5096eb91db895c385336ae8ae64ff4fc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/app/perl-math-derivative_server.py @@ -0,0 +1,167 @@ +import subprocess +import json +from typing import List, Optional +from pathlib import Path + +@mcp.tool() +def math_derivative_1st_order( + x_values: List[float], + y_values: List[float], +): + """ + Performs 1st order numeric differentiation using the Perl Math::Derivative module. + + Args: + x_values: List of independent variable values (must be sorted). + y_values: List of dependent variable values (must be same length as x_values). + """ + if len(x_values) != len(y_values): + return {"error": "x_values and y_values must have the same length."} + if len(x_values) < 2: + return {"error": "At least two points are required for 1st order differentiation."} + + # Prepare data for Perl + x_str = ",".join(map(str, x_values)) + y_str = ",".join(map(str, y_values)) + + # Construct Perl command + # We use a one-liner to import the module and execute the function + perl_script = ( + f"use Math::Derivative; " + f"my @x = split(',', '{x_str}'); " + f"my @y = split(',', '{y_str}'); " + f"my @d = Derivative1(\\@x, \\@y); " + f"print join(',', @d);" + ) + + cmd = ["perl", "-MMath::Derivative", "-e", perl_script] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + derivatives = [float(v) for v in result.stdout.strip().split(",") if v] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "derivatives": derivatives + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def math_derivative_2nd_order( + x_values: List[float], + y_values: List[float], + yp1: float = 1e30, + ypn: float = 1e30, +): + """ + Performs 2nd order numeric differentiation using the Perl Math::Derivative module. + This is typically used for cubic spline interpolation. + + Args: + x_values: List of independent variable values (must be sorted). + y_values: List of dependent variable values (must be same length as x_values). + yp1: The first derivative at the first point. Use 1e30 for a 'natural' spline. + ypn: The first derivative at the last point. Use 1e30 for a 'natural' spline. + """ + if len(x_values) != len(y_values): + return {"error": "x_values and y_values must have the same length."} + if len(x_values) < 3: + return {"error": "At least three points are required for 2nd order differentiation."} + + # Prepare data for Perl + x_str = ",".join(map(str, x_values)) + y_str = ",".join(map(str, y_values)) + + # Construct Perl command + perl_script = ( + f"use Math::Derivative; " + f"my @x = split(',', '{x_str}'); " + f"my @y = split(',', '{y_str}'); " + f"my @d = Derivative2(\\@x, \\@y, {yp1}, {ypn}); " + f"print join(',', @d);" + ) + + cmd = ["perl", "-MMath::Derivative", "-e", perl_script] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + derivatives = [float(v) for v in result.stdout.strip().split(",") if v] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "derivatives": derivatives + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def math_derivative_from_file( + input_file: str, + order: int = 1, + column_x: int = 0, + column_y: int = 1, + has_header: bool = False, + yp1: float = 1e30, + ypn: float = 1e30, +): + """ + Reads numeric data from a file and calculates the 1st or 2nd order derivatives. + + Args: + input_file: Path to the input text file (space, tab, or comma delimited). + order: Order of differentiation (1 or 2). + column_x: Index of the column containing X values (0-based). + column_y: Index of the column containing Y values (0-based). + has_header: Whether the file has a header row to skip. + yp1: (For 2nd order) First derivative at the first point. + ypn: (For 2nd order) First derivative at the last point. + """ + file_path = Path(input_file) + if not file_path.exists(): + return {"error": f"File not found: {input_file}"} + + x_values = [] + y_values = [] + + try: + with open(file_path, 'r') as f: + lines = f.readlines() + if has_header: + lines = lines[1:] + + for line in lines: + if not line.strip(): + continue + # Split by comma, tab, or whitespace + parts = line.replace(',', ' ').split() + if len(parts) > max(column_x, column_y): + x_values.append(float(parts[column_x])) + y_values.append(float(parts[column_y])) + except Exception as e: + return {"error": f"Failed to parse file: {str(e)}"} + + if order == 1: + return math_derivative_1st_order(x_values, y_values) + elif order == 2: + return math_derivative_2nd_order(x_values, y_values, yp1, ypn) + else: + return {"error": "Order must be 1 or 2."} diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/app/perl-math-derivative_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/app/perl-math-derivative_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5a4d17ac4f8d5b0a0ac15b3bf409bf0ceba85b7c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/app/perl-math-derivative_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/app/perl-math-derivative_server.py') +SERVER_NAME = 'biosci_perl_math_derivative' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b9cd06019f4e5d7b84782b58945207fdd3c532f4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-math-derivative: + build: . + image: mcp-perl-math-derivative:latest + container_name: mcp-perl-math-derivative + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-math-derivative + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..59f592c0d5bd2420f6d3f902f90f055d52f99431 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-math-derivative + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f2beb5ce2f042b8a3e9ce72d19c5505b0d5e4ac0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-math-random via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-math-random -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-math-random_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-math-random_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-math-random_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/app/perl-math-random_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/app/perl-math-random_server.py new file mode 100644 index 0000000000000000000000000000000000000000..57c6fec909ffcc5de0d363a12d76dfd2c3df2549 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/app/perl-math-random_server.py @@ -0,0 +1,230 @@ +import subprocess +import sys +from pathlib import Path +from typing import List, Optional + +# MCP-Bioinformatics Tool Definition +# +# Tool: perl-math-random +# Description: The 'perl-math-random' package is a Perl module (Math::Random) +# for generating random numbers from various distributions. It does not +# provide a standalone command-line executable. +# To make its functionality accessible, the following MCP tools act as +# wrappers. Each tool generates and executes a small Perl script +# that uses the Math::Random module to produce the desired random data. + +def _run_perl_script(script: str): + """Helper function to execute a Perl script string.""" + command = ["perl", "-e", script] + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: 'perl' command not found. Is Perl installed and in the system's PATH?", + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + +@mcp.tool() +def math_random_uniform( + n: int = 1, + min_val: float = 0.0, + max_val: float = 1.0 +): + """ + Generates uniformly distributed random numbers. + + Args: + n: The number of random values to generate. + min_val: The minimum value of the range (inclusive). + max_val: The maximum value of the range (exclusive). + """ + if n <= 0: + raise ValueError("Number of values (n) must be a positive integer.") + if min_val >= max_val: + raise ValueError("min_val must be less than max_val.") + + perl_script = f""" + use strict; + use warnings; + use Math::Random qw(random_uniform); + my @nums = random_uniform({n}, {min_val}, {max_val}); + print join("\\n", @nums), "\\n"; + """ + return _run_perl_script(perl_script) + +@mcp.tool() +def math_random_normal( + n: int = 1, + mean: float = 0.0, + stddev: float = 1.0 +): + """ + Generates normally distributed (Gaussian) random numbers. + + Args: + n: The number of random values to generate. + mean: The mean of the normal distribution. + stddev: The standard deviation of the normal distribution. + """ + if n <= 0: + raise ValueError("Number of values (n) must be a positive integer.") + if stddev < 0: + raise ValueError("Standard deviation (stddev) cannot be negative.") + + perl_script = f""" + use strict; + use warnings; + use Math::Random qw(random_normal); + my @nums = random_normal({n}, {mean}, {stddev}); + print join("\\n", @nums), "\\n"; + """ + return _run_perl_script(perl_script) + +@mcp.tool() +def math_random_binomial( + n: int, + trials: int, + prob: float +): + """ + Generates binomially distributed random numbers. + + Args: + n: The number of random values to generate. + trials: The number of trials for the binomial distribution. + prob: The probability of success for each trial. + """ + if n <= 0: + raise ValueError("Number of values (n) must be a positive integer.") + if trials <= 0: + raise ValueError("Number of trials must be a positive integer.") + if not (0.0 <= prob <= 1.0): + raise ValueError("Probability (prob) must be between 0.0 and 1.0.") + + perl_script = f""" + use strict; + use warnings; + use Math::Random qw(random_binomial); + my @nums = random_binomial({n}, {trials}, {prob}); + print join("\\n", @nums), "\\n"; + """ + return _run_perl_script(perl_script) + +@mcp.tool() +def math_random_poisson( + n: int, + mean: float +): + """ + Generates Poisson-distributed random numbers. + + Args: + n: The number of random values to generate. + mean: The mean of the Poisson distribution. + """ + if n <= 0: + raise ValueError("Number of values (n) must be a positive integer.") + if mean <= 0: + raise ValueError("Mean must be a positive number.") + + perl_script = f""" + use strict; + use warnings; + use Math::Random qw(random_poisson); + my @nums = random_poisson({n}, {mean}); + print join("\\n", @nums), "\\n"; + """ + return _run_perl_script(perl_script) + +@mcp.tool() +def math_random_permutation( + size: Optional[int] = None, + items: Optional[List[str]] = None +): + """ + Generates a random permutation of a list of items or a sequence of numbers. + + Provide either 'size' to permute numbers 1..size, or 'items' to permute the given list. + + Args: + size: The size of the set {1, ..., size} to permute. + items: A list of strings to permute. + """ + if (size is None and items is None) or (size is not None and items is not None): + raise ValueError("Exactly one of 'size' or 'items' must be provided.") + + if size is not None: + if size <= 0: + raise ValueError("Size must be a positive integer.") + perl_script = f""" + use strict; + use warnings; + use Math::Random qw(random_permutation); + my @perm = random_permutation({size}); + print join("\\n", @perm), "\\n"; + """ + else: # items is not None + if not items: + raise ValueError("The 'items' list cannot be empty.") + # Safely quote items for the Perl script + quoted_items = ", ".join([f'"{item}"' for item in items]) + perl_script = f""" + use strict; + use warnings; + use Math::Random qw(random_permutation); + my @items = ({quoted_items}); + my @perm = random_permutation(\\@items); + print join("\\n", @perm), "\\n"; + """ + + return _run_perl_script(perl_script) + +@mcp.tool() +def math_random_integer( + n: int, + min_val: int, + max_val: int +): + """ + Generates random integers within a specified range. + + Args: + n: The number of random integers to generate. + min_val: The minimum value of the range (inclusive). + max_val: The maximum value of the range (inclusive). + """ + if n <= 0: + raise ValueError("Number of values (n) must be a positive integer.") + if min_val > max_val: + raise ValueError("min_val cannot be greater than max_val.") + + perl_script = f""" + use strict; + use warnings; + use Math::Random qw(random_integer); + my @nums = random_integer({n}, {min_val}, {max_val}); + print join("\\n", @nums), "\\n"; + """ + return _run_perl_script(perl_script) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/app/perl-math-random_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/app/perl-math-random_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a3feaa2e6301de3d8016fed48d54aa73bcf005c9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/app/perl-math-random_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/app/perl-math-random_server.py') +SERVER_NAME = 'biosci_perl_math_random' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..adbde75558b356f71cdb95e27ac057132b6954a4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-math-random: + build: . + image: mcp-perl-math-random:latest + container_name: mcp-perl-math-random + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-math-random + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e5cff7a214ebeba3d56a11013a9a1e6ea6594bd5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-math-random + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-random/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f1f60858ada6305621dde7004d097462801db3ea --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-math-round via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-math-round -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-math-round_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-math-round_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-math-round_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/app/perl-math-round_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/app/perl-math-round_server.py new file mode 100644 index 0000000000000000000000000000000000000000..af08b6661cf3f1bf496a2a56615586e586fb9159 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/app/perl-math-round_server.py @@ -0,0 +1,99 @@ +import subprocess +from typing import List, Optional, Literal + +# MCP decorator is omitted as per instructions, but would be present in a real MCP environment. +# from mcp import mcp + +@mcp.tool() +def math_round( + numbers: List[float], + method: Literal[ + "round", "round_even", "round_odd", "round_rand", + "nearest", "nlowmult", "nhimult" + ] = "round", + multiple: Optional[float] = None, +) -> dict: + """ + Rounds a list of numbers using various methods from the Perl Math::Round module. + + This tool acts as a wrapper around the Perl Math::Round library, allowing + access to its rounding functions from the command line. + + Args: + numbers: A list of floating-point numbers to be rounded. + method: The rounding method to use. + - 'round': Rounds to the nearest integer (0.5 rounds up). + - 'round_even': Rounds to the nearest even integer. + - 'round_odd': Rounds to the nearest odd integer. + - 'round_rand': Rounds 0.5 up or down randomly. + - 'nearest': Rounds to the nearest multiple of the 'multiple' parameter. + - 'nlowmult': Finds the next lower or equal multiple. + - 'nhimult': Finds the next higher or equal multiple. + multiple: The multiple to use for 'nearest', 'nlowmult', and 'nhimult' methods. + This parameter is required and only used for these methods. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + The stdout will contain the rounded numbers, each on a new line. + """ + # --- Input Validation --- + if not numbers: + raise ValueError("The 'numbers' list cannot be empty.") + + if method in ["nearest", "nlowmult", "nhimult"]: + if multiple is None: + raise ValueError(f"The 'multiple' parameter is required for the '{method}' method.") + if multiple == 0: + raise ValueError("The 'multiple' parameter cannot be zero for 'nearest' methods.") + perl_function = f"{method}({multiple}, $_)" + else: + if multiple is not None: + # This is a user-guidance check, not a hard failure. + print(f"Warning: The 'multiple' parameter is ignored for the '{method}' method.") + perl_function = f"{method}($_)" + + # --- Command Construction --- + # We construct a Perl one-liner to perform the rounding. + # -MMath::Round: Loads the required module. + # -n: Wraps the script in a `while (<>) { ... }` loop, reading from STDIN. + # -e: Executes the following string as a script. + # 'chomp; print ... "\\n"': Removes the input newline, calls the rounding function on the + # current line variable ($_), and prints the result followed by a new newline. + perl_script = f'chomp; print {perl_function}, "\\n"' + cmd = ["perl", "-MMath::Round", "-n", "-e", perl_script] + + # The list of numbers will be passed to the process via standard input. + input_str = "\n".join(map(str, numbers)) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + input=input_str, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except FileNotFoundError: + # This handles the case where 'perl' is not in the system's PATH. + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Make sure Perl and the perl-math-round conda package are installed in the environment.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + # This handles errors from the Perl script itself (e.g., syntax errors). + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/app/perl-math-round_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/app/perl-math-round_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..25b4d492618a3850c176e9721768bbfbddc30b7f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/app/perl-math-round_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/app/perl-math-round_server.py') +SERVER_NAME = 'biosci_perl_math_round' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3d14063a9c2044d6df6d3859fa46d62c5f5e6aa0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-math-round: + build: . + image: mcp-perl-math-round:latest + container_name: mcp-perl-math-round + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-math-round + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..595eb23329f9bad4e8867f4e32907a8bd52998e5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-math-round + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-round/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f65e692434c73f1aa389475f19cd01851794b062 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-math-spline via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-math-spline -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-math-spline_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-math-spline_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-math-spline_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/app/perl-math-spline_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/app/perl-math-spline_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2a643636295c70195f1ce87d3ffe3ae81ecbe179 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/app/perl-math-spline_server.py @@ -0,0 +1,158 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, List, Optional + +# The mcp.tool decorator is assumed to be available in the execution environment. +# from mcp import tool as mcp + +@mcp.tool() +def math_spline_interpolate( + input_data: Path, + query_points: Path, + output_file: Optional[Path] = None, +) -> Dict: + """ + Performs cubic spline interpolation using the Perl Math::Spline library. + + This tool acts as a wrapper around the 'perl-math-spline' library, which does not + provide a direct command-line interface. It dynamically creates and executes a + Perl script to perform the interpolation. + + Args: + input_data: Path to a file containing the known data points. The file should + have two whitespace-separated columns: x and y values. + query_points: Path to a file containing the x-values for which to interpolate + y-values. Each x-value should be on a new line. + output_file: Optional path to save the interpolation results. If not provided, + results are returned in stdout. The output will be a two-column, + tab-separated file of query-x and interpolated-y values. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list + of output files generated. + """ + # --- Input Validation --- + if not input_data.is_file(): + raise FileNotFoundError(f"Input data file not found: {input_data}") + if not query_points.is_file(): + raise FileNotFoundError(f"Query points file not found: {query_points}") + if output_file and not output_file.parent.is_dir(): + raise NotADirectoryError(f"Output directory does not exist: {output_file.parent}") + + # --- Perl Wrapper Script --- + # This script reads the data, creates a spline, and evaluates it at query points. + perl_script_content = f""" + #!/usr/bin/env perl + + use strict; + use warnings; + use Math::Spline; + + # Ensure correct number of arguments + if (@ARGV != 2) {{ + die "Usage: $0 \\n"; + }} + + my ($input_data_file, $query_points_file) = @ARGV; + + # Read known X and Y data points + my (@x, @y); + open my $data_fh, '<', $input_data_file or die "Could not open $input_data_file: $!"; + while (my $line = <$data_fh>) {{ + chomp $line; + next if $line =~ /^\\s*$/; # Skip empty lines + my ($x_val, $y_val) = split /\\s+/, $line; + push @x, $x_val; + push @y, $y_val; + }} + close $data_fh; + + # Check if we have enough data points for interpolation + if (@x < 2) {{ + die "Error: At least 2 data points are required for spline interpolation.\\n"; + }} + + # Create the spline object + my $spline; + eval {{ + $spline = Math::Spline->new(\\@x, \\@y); + }}; + if ($@) {{ + die "Error creating spline object: $@"; + }} + + # Read query points and perform interpolation + open my $query_fh, '<', $query_points_file or die "Could not open $query_points_file: $!"; + while (my $query_x = <$query_fh>) {{ + chomp $query_x; + next if $query_x =~ /^\\s*$/; # Skip empty lines + my $interp_y = $spline->evaluate($query_x); + print "$query_x\\t$interp_y\\n"; + }} + close $query_fh; + """ + + output_files: List[str] = [] + command_executed = "" + + try: + with tempfile.NamedTemporaryFile( + mode="w", delete=False, suffix=".pl" + ) as tmp_script: + tmp_script.write(perl_script_content) + tmp_script.flush() + tmp_script_path = Path(tmp_script.name) + + # --- Command Construction --- + cmd = [ + "perl", + str(tmp_script_path), + str(input_data), + str(query_points), + ] + command_executed = " ".join(cmd) + + # --- Subprocess Execution --- + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout_str = result.stdout + stderr_str = result.stderr + + # --- Output Handling --- + if output_file: + output_file.write_text(stdout_str) + output_files.append(str(output_file)) + + except FileNotFoundError: + # This error is caught if 'perl' is not in the system's PATH + return { + "command_executed": "perl ...", + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + # This handles errors from the Perl script itself (e.g., file not found, not enough data points) + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": output_files, + } + finally: + # Ensure temporary script is cleaned up + if 'tmp_script_path' in locals() and tmp_script_path.exists(): + tmp_script_path.unlink() + + # --- Structured Result Return --- + return { + "command_executed": command_executed, + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/app/perl-math-spline_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/app/perl-math-spline_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5b30b12ae1cad365226bae7d9e6a97ea38646e26 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/app/perl-math-spline_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/app/perl-math-spline_server.py') +SERVER_NAME = 'biosci_perl_math_spline' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3db92fca86f0596702e09e56191f890e24455f07 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-math-spline: + build: . + image: mcp-perl-math-spline:latest + container_name: mcp-perl-math-spline + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-math-spline + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b022697aea26aab714283873cdf92c4f7a58d9ba --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-math-spline + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-spline/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..58feb88645de8905618770820033a4a98058b04b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-math-vecstat via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-math-vecstat -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-math-vecstat_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-math-vecstat_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-math-vecstat_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/app/perl-math-vecstat_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/app/perl-math-vecstat_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b5a9726ce8d4770d4a3fd00072c5fe36081be33d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/app/perl-math-vecstat_server.py @@ -0,0 +1,196 @@ +import subprocess +import tempfile +import json +from pathlib import Path +from typing import List, Optional, Dict, Any, Literal + +# MCP decorator would be here in a real MCP environment +# from mcp import mcp + +# Define the allowed operations as a Literal type for better static analysis and validation. +# This list is derived from the official Math::VecStat CPAN documentation. +AllowedOperation = Literal[ + "sum", "sum_sq", "mean", "median", "min", "max", "prod", "count", + "stddev", "var", "stderr", "rms", "correl", "covar", "mape", "lsfit" +] + +@mcp.tool() +def run_math_vecstat( + vector1: List[float], + operations: List[AllowedOperation], + vector2: Optional[List[float]] = None, +) -> Dict[str, Any]: + """ + Calculates descriptive statistics for numeric vectors using Perl's Math::VecStat. + + This tool serves as a wrapper around the Perl Math::VecStat library, which does not + provide a direct command-line interface. It executes a temporary Perl script + to perform the requested calculations on the input data. + + Args: + vector1: The primary list of numbers for statistical analysis. + operations: A list of statistical operations to perform. + vector2: An optional second list of numbers for two-vector operations + (e.g., 'correl', 'covar'). Must be the same length as vector1. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + 'statistics' key with the calculated results. + """ + # 1. Input Validation + if not vector1: + raise ValueError("Input 'vector1' cannot be empty.") + if not operations: + raise ValueError("The 'operations' list cannot be empty.") + + two_vector_ops = {"correl", "covar", "mape", "lsfit"} + requested_ops = set(operations) + + if requested_ops.intersection(two_vector_ops): + if vector2 is None: + raise ValueError( + f"Operations {two_vector_ops.intersection(requested_ops)} " + "require 'vector2' to be provided." + ) + if len(vector1) != len(vector2): + raise ValueError( + "'vector1' and 'vector2' must have the same length for " + "two-vector operations." + ) + + # 2. Embedded Perl script to wrap the Math::VecStat library + perl_script = """ + use strict; + use warnings; + use Math::VecStat; + use JSON::PP; + + # Disable buffering on stdout for immediate output + $| = 1; + + # Read arguments passed after '--' + my $file1 = shift @ARGV; + my $file2 = shift @ARGV; + my @ops = @ARGV; + + sub read_vector { + my ($filename) = @_; + open my $fh, '<', $filename or die "Cannot open $filename: $!"; + my @vec = <$fh>; + chomp @vec; + close $fh; + # Ensure all data is numeric + for my $val (@vec) { + die "Non-numeric value '$val' found in $filename" unless $val =~ /^-?\d+(\.\d+)?(e[+-]?\d+)?$/i; + } + return @vec; + } + + my @vec1 = read_vector($file1); + my @vec2; + if ($file2 ne 'NONE') { + @vec2 = read_vector($file2); + } + + my %results; + my $error = ''; + + for my $op (@ops) { + eval { + if ($op eq 'sum') { $results{$op} = Math::VecStat::sum(@vec1); } + elsif ($op eq 'sum_sq') { $results{$op} = Math::VecStat::sum_sq(@vec1); } + elsif ($op eq 'mean') { $results{$op} = Math::VecStat::mean(@vec1); } + elsif ($op eq 'median') { $results{$op} = Math::VecStat::median(@vec1); } + elsif ($op eq 'min') { $results{$op} = Math::VecStat::min(@vec1); } + elsif ($op eq 'max') { $results{$op} = Math::VecStat::max(@vec1); } + elsif ($op eq 'prod') { $results{$op} = Math::VecStat::prod(@vec1); } + elsif ($op eq 'count') { $results{$op} = Math::VecStat::count(@vec1); } + elsif ($op eq 'stddev') { $results{$op} = Math::VecStat::stddev(@vec1); } + elsif ($op eq 'var') { $results{$op} = Math::VecStat::var(@vec1); } + elsif ($op eq 'stderr') { $results{$op} = Math::VecStat::stderr(@vec1); } + elsif ($op eq 'rms') { $results{$op} = Math::VecStat::rms(@vec1); } + elsif ($op eq 'correl') { $results{$op} = Math::VecStat::correl(\\@vec1, \\@vec2); } + elsif ($op eq 'covar') { $results{$op} = Math::VecStat::covar(\\@vec1, \\@vec2); } + elsif ($op eq 'mape') { $results{$op} = Math::VecStat::mape(\\@vec1, \\@vec2); } + elsif ($op eq 'lsfit') { + my ($b, $a) = Math::VecStat::lsfit(\\@vec1, \\@vec2); + $results{$op} = { 'intercept' => $a, 'slope' => $b }; + } + }; + if ($@) { + # Capture any errors from the eval block + $error .= "Error calculating '$op': $@"; + } + } + + if ($error) { + die $error; + } + + # Output results as a single JSON string for easy parsing + print encode_json(\\%results); + """ + + # 3. Prepare input data in a temporary directory + with tempfile.TemporaryDirectory() as tempdir: + temp_path = Path(tempdir) + input1_path = temp_path / "vector1.txt" + with open(input1_path, "w") as f: + f.write("\n".join(map(str, vector1))) + + input2_path_str = "NONE" + if vector2 is not None: + input2_path = temp_path / "vector2.txt" + with open(input2_path, "w") as f: + f.write("\n".join(map(str, vector2))) + input2_path_str = str(input2_path) + + # 4. Construct and execute the command + cmd = [ + "perl", "-e", perl_script, "--", + str(input1_path), + input2_path_str + ] + cmd.extend(operations) + + command_executed = " ".join(f"'{arg}'" if " " in arg else arg for arg in cmd) + + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + # 5. Parse JSON output from the script + stats = json.loads(process.stdout) + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "statistics": stats, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Perl script execution failed.", + "return_code": e.returncode, + } + except json.JSONDecodeError as e: + # This case handles if the Perl script outputs non-JSON text + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "error": f"Failed to parse JSON output from Perl script: {e}", + } + except Exception as e: + # Catch any other unexpected errors + return { + "command_executed": command_executed, + "error": f"An unexpected error occurred: {e}", + "stdout": "", + "stderr": "", + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/app/perl-math-vecstat_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/app/perl-math-vecstat_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..45f0af52dcb114eb6a1a93ae54a51523670447fb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/app/perl-math-vecstat_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/app/perl-math-vecstat_server.py') +SERVER_NAME = 'biosci_perl_math_vecstat' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..51f710177aef2efafab6d3ef26af8eeb20610b06 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-math-vecstat: + build: . + image: mcp-perl-math-vecstat:latest + container_name: mcp-perl-math-vecstat + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-math-vecstat + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f67ff4440933138ee61821490a490bfc98db53fe --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-math-vecstat + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-vecstat/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..979dffd1e0bd9d5ec1b634be5441d48b54b58e04 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-mce via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-mce -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-mce_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-mce_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-mce_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/app/perl-mce_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/app/perl-mce_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0e9764445b9fcecdacc2db2c26aa1012b35f6e89 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/app/perl-mce_server.py @@ -0,0 +1,243 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Mock decorator for standalone execution +class mcp: + def tool(func): + return func + +@mcp.tool +def perl_run( + programfile: Optional[Path] = None, + e_program: Optional[List[str]] = None, + E_program: Optional[List[str]] = None, + arguments: Optional[List[str]] = None, + no_switch_processing: bool = False, + record_separator_octal: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + in_place_edit_extension: Optional[str] = None, + include_dirs: Optional[List[Path]] = None, + line_ending_octal: Optional[str] = None, + use_module: Optional[List[str]] = None, + no_use_module: Optional[List[str]] = None, + use_module_no_import: Optional[List[str]] = None, + no_use_module_no_import: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + parse_switches: bool = False, + search_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core: bool = False, + unsafe_operations: bool = False, + print_version: bool = False, + print_config: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang_dir: Optional[str] = None, + disable_all_warnings: bool = False, +) -> Dict[str, Any]: + """ + Executes a Perl program using the Perl interpreter. + + This tool is provided in the context of the 'perl-mce' (Many-Core Engine) + package. The MCE modules are available for use within the executed script + to enable parallel processing. Exactly one of 'programfile', 'e_program', + or 'E_program' must be provided as the source for the code to be executed. + + Args: + programfile: Path to the Perl program file to execute. + e_program: A list of strings, where each string is a line of program to be executed. + E_program: Like e_program, but enables all optional features. + arguments: A list of arguments to be passed to the program file. + no_switch_processing: If True, adds '--' to the command, stopping switch processing. + record_separator_octal: Specify record separator as an octal value (e.g., '077'). + autosplit: Autosplit mode with -n or -p (splits $_ into @F). + unicode_features: Enables the listed Unicode features (e.g., 'UTF8'). + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). + debugger: Run program under debugger. Provide a module name (e.g., 'Devel::NYTProf') + to use a specific one. Provide an empty string "" to use the default debugger. + debugging_flags: Set debugging flags (argument is a bit mask or alphabets). + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. + split_pattern: split() pattern for -a switch (//'s are optional). + in_place_edit_extension: Edit <> files in place. If an extension is supplied (e.g., '.bak'), + a backup is made. Provide an empty string "" for no backup. + include_dirs: List of directories to specify @INC/#include path. + line_ending_octal: Enable line ending processing, specifies line terminator. + use_module: Execute "use module..." before executing program (corresponds to -M). + no_use_module: Execute "no module..." before executing program (corresponds to -M-). + use_module_no_import: Execute "use module ()" before executing program (corresponds to -m). + no_use_module_no_import: Execute "no module ()" before executing program (corresponds to -m-). + loop_around_program: Assume "while (<>) { ... }" loop around program. + loop_and_print: Assume loop like -n but print line also, like sed. + parse_switches: Enable rudimentary parsing for switches after programfile. + search_path: Look for programfile using PATH environment variable. + tainting_warnings: Enable tainting warnings. + tainting_checks: Enable tainting checks. + dump_core: Dump core after parsing program. + unsafe_operations: Allow unsafe operations. + print_version: Print version, patchlevel and license. + print_config: Print configuration summary. Provide a variable name to print only that + variable. Provide an empty string "" for the full summary. + enable_warnings: Enable many useful warnings. + enable_all_warnings: Enable all warnings. + ignore_text_before_shebang_dir: Ignore text before #!perl line. Optionally provide a + directory path to cd into. Provide an empty string "" + to ignore text without changing directory. + disable_all_warnings: Disable all warnings. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # Input Validation + program_source_count = sum(p is not None for p in [programfile, e_program, E_program]) + if program_source_count != 1: + raise ValueError("Exactly one of 'programfile', 'e_program', or 'E_program' must be provided.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"Program file not found: {programfile}") + + if split_pattern and not autosplit: + raise ValueError("'split_pattern' requires 'autosplit' to be True.") + + if ignore_text_before_shebang_dir is not None and not programfile: + raise ValueError("'-x' flag can only be used with a 'programfile'.") + + cmd = ["perl"] + + # Build command with switches + if record_separator_octal is not None: + cmd.append(f"-0{record_separator_octal}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if debugger is not None: + cmd.append(f"-d{':' + debugger if debugger else ''}") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if in_place_edit_extension is not None: + cmd.append(f"-i{in_place_edit_extension}") + if include_dirs: + for d in include_dirs: + cmd.extend(["-I", str(d)]) + if line_ending_octal is not None: + cmd.append(f"-l{line_ending_octal}") + if use_module: + for m in use_module: + cmd.append(f"-M{m}") + if no_use_module: + for m in no_use_module: + cmd.append(f"-M-{m}") + if use_module_no_import: + for m in use_module_no_import: + cmd.append(f"-m{m}") + if no_use_module_no_import: + for m in no_use_module_no_import: + cmd.append(f"-m-{m}") + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if parse_switches: + cmd.append("-s") + if search_path: + cmd.append("-S") + if tainting_warnings: + cmd.append("-t") + if tainting_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config is not None: + cmd.append(f"-V{':' + print_config if print_config else ''}") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if ignore_text_before_shebang_dir is not None: + if ignore_text_before_shebang_dir: + p = Path(ignore_text_before_shebang_dir) + if not p.is_dir(): + raise ValueError(f"Directory for -x does not exist: {p}") + cmd.append(f"-x{str(p)}") + else: + cmd.append("-x") + if disable_all_warnings: + cmd.append("-X") + + # Add program source + if e_program: + for line in e_program: + cmd.extend(["-e", line]) + if E_program: + for line in E_program: + cmd.extend(["-E", line]) + + if no_switch_processing: + cmd.append("--") + + if programfile: + cmd.append(str(programfile)) + + if arguments: + cmd.extend(arguments) + + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = result.stdout + stderr = result.stderr + return_code = result.returncode + except subprocess.CalledProcessError as e: + stdout = e.stdout + stderr = e.stderr + return_code = e.returncode + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' executable not found. Make sure Perl is installed and in the system's PATH.", + "return_code": 1, + "output_files": [] + } + + output_files = [] + if in_place_edit_extension is not None and in_place_edit_extension and arguments: + for arg_file_str in arguments: + p = Path(arg_file_str) + if p.is_file(): + backup_file = p.with_name(f"{p.name}{in_place_edit_extension}") + if backup_file.exists(): + output_files.append(str(backup_file)) + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "return_code": return_code, + "output_files": output_files + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/app/perl-mce_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/app/perl-mce_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a10b687cdf675095af1836363fed7a1af8757495 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/app/perl-mce_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/app/perl-mce_server.py') +SERVER_NAME = 'biosci_perl_mce' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..294e08c0622a200ae4be4e8e2272ae4295ebe967 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-mce: + build: . + image: mcp-perl-mce:latest + container_name: mcp-perl-mce + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-mce + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e35d8c070178800596eb36cedbb4e7a03d472231 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-mce + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mce/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-base64/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-base64/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-base64/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d6e2422a560e4b54f9efa545020651aea67081ef --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-mime-lite via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-mime-lite -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-mime-lite_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-mime-lite_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-mime-lite_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/app/perl-mime-lite_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/app/perl-mime-lite_server.py new file mode 100644 index 0000000000000000000000000000000000000000..021d66220505d6a41bef732877ff1ad0a3499729 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/app/perl-mime-lite_server.py @@ -0,0 +1,261 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +@mcp.tool() +def mime_lite_send_email( + sender: str, + recipient: str, + subject: str, + body: str, + content_type: str = "text/plain", + cc: str = "", + bcc: str = "", + attachments: Optional[List[str]] = None, + send_method: str = "sendmail", + smtp_server: str = "localhost", +) -> Dict[str, Any]: + """ + Send an email with optional attachments using Perl's MIME::Lite. + + Args: + sender: Email address of the sender (From). + recipient: Email address of the recipient (To). + subject: Subject line of the email. + body: The main text content of the email. + content_type: MIME type of the body (e.g., 'text/plain' or 'text/html'). + cc: Carbon copy recipients (comma-separated). + bcc: Blind carbon copy recipients (comma-separated). + attachments: List of file paths to attach to the email. + send_method: Method to send the mail ('sendmail' or 'smtp'). + smtp_server: SMTP server address (only used if send_method is 'smtp'). + """ + # Validate inputs + if not sender or "@" not in sender: + return {"error": "Invalid sender email address."} + if not recipient or "@" not in recipient: + return {"error": "Invalid recipient email address."} + + # Prepare attachment logic for Perl script + attachment_code = "" + if attachments: + for file_path in attachments: + path = Path(file_path) + if not path.exists(): + return {"error": f"Attachment file not found: {file_path}"} + + # Escape single quotes for Perl string + safe_path = str(path).replace("'", "\\'") + attachment_code += f""" +$msg->attach( + Type => 'AUTO', + Path => '{safe_path}', + Filename => '{path.name}', + Disposition => 'attachment' +); +""" + + # Determine sending logic + if send_method.lower() == "smtp": + send_logic = f"MIME::Lite->send('smtp', '{smtp_server}', Timeout=>60);" + else: + send_logic = "MIME::Lite->send('sendmail');" + + # Construct Perl script + # We use double quotes for Perl variables and escape them where necessary + perl_script = f""" +use MIME::Lite; + +my $msg = MIME::Lite->new( + From => '{sender}', + To => '{recipient}', + Cc => '{cc}', + Bcc => '{bcc}', + Subject => '{subject}', + Type => '{content_type}', + Data => '{body}' +); + +{attachment_code} + +{send_logic} +$msg->send(); +""" + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.pl', delete=False) as tmp: + tmp.write(perl_script) + tmp_path = tmp.name + + cmd = ["perl", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + # Cleanup + Path(tmp_path).unlink() + + return { + "command_executed": "perl ", + "status": "success", + "stdout": result.stdout, + "stderr": result.stderr + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": "perl ", + "status": "error", + "stdout": e.stdout, + "stderr": e.stderr, + "exit_code": e.returncode + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def mime_lite_generate_source( + sender: str, + recipient: str, + subject: str, + body: str, + content_type: str = "text/plain", + attachments: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Generate the raw MIME source text for an email without sending it. + Useful for debugging or manual inspection of the MIME structure. + + Args: + sender: Email address of the sender. + recipient: Email address of the recipient. + subject: Subject line. + body: Main content. + content_type: MIME type of the body. + attachments: List of file paths to attach. + """ + attachment_code = "" + if attachments: + for file_path in attachments: + path = Path(file_path) + if not path.exists(): + return {"error": f"Attachment file not found: {file_path}"} + safe_path = str(path).replace("'", "\\'") + attachment_code += f"$msg->attach(Type=>'AUTO', Path=>'{safe_path}');\n" + + perl_script = f""" +use MIME::Lite; +my $msg = MIME::Lite->new( + From => '{sender}', + To => '{recipient}', + Subject => '{subject}', + Type => '{content_type}', + Data => '{body}' +); +{attachment_code} +print $msg->as_string; +""" + + try: + result = subprocess.run( + ["perl", "-e", perl_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "perl -e '...'", + "mime_source": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to generate MIME source", + "stderr": e.stderr + } + +@mcp.tool() +def mime_lite_check_installation() -> Dict[str, Any]: + """ + Verify if the MIME::Lite Perl module is correctly installed and accessible. + """ + try: + # -MModule checks if module can be loaded + result = subprocess.run( + ["perl", "-MMIME::Lite", "-e", "print $MIME::Lite::VERSION"], + capture_output=True, + text=True, + check=True + ) + return { + "status": "installed", + "version": result.stdout.strip(), + "perl_info": subprocess.run(["perl", "-v"], capture_output=True, text=True).stdout.splitlines()[1] + } + except subprocess.CalledProcessError: + return { + "status": "not_found", + "error": "MIME::Lite is not installed in the current Perl environment." + } + +@mcp.tool() +def perl_interpreter_info( + show_config: bool = False, +) -> Dict[str, Any]: + """ + Get information about the Perl interpreter and its configuration. + Equivalent to 'perl -v' or 'perl -V'. + + Args: + show_config: If True, runs 'perl -V' to show full configuration. If False, runs 'perl -v'. + """ + flag = "-V" if show_config else "-v" + try: + result = subprocess.run(["perl", flag], capture_output=True, text=True, check=True) + return { + "command": f"perl {flag}", + "output": result.stdout + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr} + +@mcp.tool() +def mime_lite_advanced_execute( + script_content: str, + include_paths: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Execute a custom Perl script that utilizes MIME::Lite. + Use this for complex MIME operations not covered by standard tools. + + Args: + script_content: The full Perl script content. + include_paths: Optional list of directories to add to @INC (Perl's library path). + """ + cmd = ["perl"] + + if include_paths: + for path in include_paths: + cmd.extend(["-I", path]) + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.pl', delete=False) as tmp: + tmp.write(script_content) + tmp_path = tmp.name + + cmd.append(tmp_path) + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + Path(tmp_path).unlink() + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "status": "error", + "stdout": e.stdout, + "stderr": e.stderr, + "exit_code": e.returncode + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/app/perl-mime-lite_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/app/perl-mime-lite_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2bca921375cc7708397f26dedb14de94e3f92378 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/app/perl-mime-lite_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/app/perl-mime-lite_server.py') +SERVER_NAME = 'biosci_perl_mime_lite' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5044c28dd7b7b7897733b7eddaad46bae45dad72 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-mime-lite: + build: . + image: mcp-perl-mime-lite:latest + container_name: mcp-perl-mime-lite + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-mime-lite + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b73e77534a07fc4ca37c416de5d197d3afdb4280 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-mime-lite + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-lite/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..132d59b2fea8012dcd42e4adfbd4e5ac19442595 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-mime-tools via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-mime-tools -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-mime-tools_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-mime-tools_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-mime-tools_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/app/perl-mime-tools_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/app/perl-mime-tools_server.py new file mode 100644 index 0000000000000000000000000000000000000000..37901552cca53e88f1dc66e2e3248255649974cb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/app/perl-mime-tools_server.py @@ -0,0 +1,239 @@ +import os +import subprocess +from pathlib import Path +from typing import Optional, List + +# MCP-ready implementations for the 'mime-tool' executable +# provided by the 'perl-mime-tools' package. + +# @mcp.tool() +def mime_tool_decode( + input_file: Path, + output_path: Optional[Path] = None, +) -> dict: + """ + Decodes a MIME message from a file. + + The 'mime-tool decode' command reads a MIME message from standard input + and decodes it. + + Args: + input_file: Path to the input MIME message file. + output_path: Optional path to save the decoded output. If not provided, + the decoded content will be returned in stdout. + + Returns: + A dictionary containing the command executed, stdout, stderr, + and a list of output files. + """ + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + cmd = ["mime-tool", "decode"] + if output_path: + # Ensure parent directory exists + output_path.parent.mkdir(parents=True, exist_ok=True) + cmd.extend(["-o", str(output_path)]) + + try: + with open(input_file, "r") as f_in: + result = subprocess.run( + cmd, + stdin=f_in, + capture_output=True, + text=True, + check=True + ) + + output_files = [str(output_path)] if output_path else [] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except FileNotFoundError: + raise RuntimeError("mime-tool command not found. Is perl-mime-tools installed and in the PATH?") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"MIME tool decode failed with return code {e.returncode}.", + } + +# @mcp.tool() +def mime_tool_encode( + input_file: Path, + output_file: Optional[Path] = None, + encoding: Optional[str] = None, +) -> dict: + """ + Encodes a file into a MIME message. + + The 'mime-tool encode' command creates a MIME message from a given file. + + Args: + input_file: Path to the file to be encoded. + output_file: Optional path to save the resulting MIME message. If not provided, + the MIME message is returned in stdout. + encoding: The encoding to use (e.g., 'base64', 'quoted-printable', '7bit', '8bit', 'binary'). + + Returns: + A dictionary containing the command executed, stdout, stderr, + and a list of output files. + """ + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + cmd = ["mime-tool", "encode"] + if encoding: + cmd.extend(["-e", encoding]) + + cmd.append(str(input_file)) + + try: + if output_file: + # Ensure parent directory exists + output_file.parent.mkdir(parents=True, exist_ok=True) + with open(output_file, "w") as f_out: + result = subprocess.run( + cmd, + stdout=f_out, + capture_output=True, # To capture stderr + text=True, + check=True + ) + stdout_content = f"Output successfully written to {output_file}" + output_files = [str(output_file)] + else: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout_content = result.stdout + output_files = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_content, + "stderr": result.stderr, + "output_files": output_files + } + except FileNotFoundError: + raise RuntimeError("mime-tool command not found. Is perl-mime-tools installed and in the PATH?") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"MIME tool encode failed with return code {e.returncode}.", + } + +# @mcp.tool() +def mime_tool_explode( + input_file: Path, + output_dir: Path, + use_original_filenames: bool = False, +) -> dict: + """ + Explodes a MIME message into its component files in a directory. + + The 'mime-tool explode' command reads a MIME message from standard input + and unpacks its parts into a specified directory. + + Args: + input_file: Path to the input MIME message file. + output_dir: The directory to place the exploded files into. It will be created if it doesn't exist. + use_original_filenames: If True, use the original filenames from the MIME headers (-t flag). + + Returns: + A dictionary containing the command executed, stdout, stderr, + and a list of the created output files. + """ + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = ["mime-tool", "explode", "-f", str(output_dir)] + if use_original_filenames: + cmd.append("-t") + + try: + with open(input_file, "r") as f_in: + result = subprocess.run( + cmd, + stdin=f_in, + capture_output=True, + text=True, + check=True + ) + + created_files = [str(output_dir / f) for f in os.listdir(output_dir)] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": created_files + } + except FileNotFoundError: + raise RuntimeError("mime-tool command not found. Is perl-mime-tools installed and in the PATH?") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"MIME tool explode failed with return code {e.returncode}.", + } + +# @mcp.tool() +def mime_tool_test( + input_file: Path, +) -> dict: + """ + Test-parses a MIME message from a file for correctness. + + The 'mime-tool test' command reads a MIME message from standard input + and reports on whether it could be parsed successfully. + + Args: + input_file: Path to the input MIME message file to test. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + cmd = ["mime-tool", "test"] + + try: + with open(input_file, "r") as f_in: + result = subprocess.run( + cmd, + stdin=f_in, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + raise RuntimeError("mime-tool command not found. Is perl-mime-tools installed and in the PATH?") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"MIME tool test failed with return code {e.returncode}.", + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/app/perl-mime-tools_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/app/perl-mime-tools_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..737ab69215eff365faccfce617cf85bf902dafdd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/app/perl-mime-tools_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/app/perl-mime-tools_server.py') +SERVER_NAME = 'biosci_perl_mime_tools' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..534096f6b65897fd6a50a0bc8643786e040122c0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-mime-tools: + build: . + image: mcp-perl-mime-tools:latest + container_name: mcp-perl-mime-tools + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-mime-tools + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6fb532b68924ea8113f1880adf369336dc61c44f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-mime-tools + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-tools/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cdb9f30ee85a0d49bada42196d0894cbe5cd5d33 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-mime-types via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-mime-types -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-mime-types_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-mime-types_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-mime-types_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/app/perl-mime-types_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/app/perl-mime-types_server.py new file mode 100644 index 0000000000000000000000000000000000000000..208c692b02ef23eebc4325012545d7feaf3713ec --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/app/perl-mime-types_server.py @@ -0,0 +1,183 @@ +import subprocess +import shlex +from pathlib import Path +from typing import Optional, List, Dict + +# MCP decorator is not needed for the final code, as per instructions. +# Assuming @mcp.tool() is available in the execution environment. + +# @mcp.tool() +def run_perl( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + execute_program: Optional[List[str]] = None, + execute_program_extended: Optional[List[str]] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + run_under_debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + in_place_edit: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + enable_line_ending_processing: Optional[str] = None, + use_module: Optional[List[str]] = None, + use_module_no_import: Optional[List[str]] = None, + no_module: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + enable_switch_parsing: bool = False, + search_path_for_program: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_pre_hashbang_text: bool = False, + change_to_directory_x: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> Dict[str, any]: + """ + Executes the Perl interpreter with specified switches and a program file or one-liner. + + This tool wraps the `perl` command-line interpreter. The `perl-mime-types` package + is a library and does not provide a direct executable. You can use this tool to run + Perl scripts that may utilize the `perl-mime-types` library. + """ + # --- Input Validation --- + if programfile and (execute_program or execute_program_extended): + raise ValueError("Cannot specify both a 'programfile' and an 'execute_program' or 'execute_program_extended' one-liner.") + if not programfile and not execute_program and not execute_program_extended and not print_version and print_config is None: + raise ValueError("Must provide a 'programfile', 'execute_program', 'execute_program_extended', 'print_version', or 'print_config'.") + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"Program file not found: {programfile}") + if change_to_directory_x and not change_to_directory_x.is_dir(): + raise NotADirectoryError(f"Directory specified for -x not found: {change_to_directory_x}") + + # --- Command Construction --- + cmd = ["perl"] + + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if run_under_debugger is not None: + cmd.append(f"-d:{run_under_debugger}" if run_under_debugger else "-d") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if in_place_edit is not None: + cmd.append(f"-i{in_place_edit}") + if include_directories: + for directory in include_directories: + cmd.extend(["-I", str(directory)]) + if enable_line_ending_processing is not None: + cmd.append(f"-l{enable_line_ending_processing}") + if use_module: + for module in use_module: + cmd.append(f"-M{module}") + if use_module_no_import: + for module in use_module_no_import: + cmd.append(f"-m{module}") + if no_module: + for module in no_module: + cmd.append(f"-M-{module}") + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if enable_switch_parsing: + cmd.append("-s") + if search_path_for_program: + cmd.append("-S") + if tainting_warnings: + cmd.append("-t") + if tainting_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if allow_unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config is not None: + cmd.append(f"-V:{print_config}" if print_config else "-V") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if change_to_directory_x: + cmd.append(f"-x{change_to_directory_x}") + elif ignore_pre_hashbang_text: + cmd.append("-x") + if disable_all_warnings: + cmd.append("-X") + + if execute_program: + for prog_line in execute_program: + cmd.extend(["-e", prog_line]) + if execute_program_extended: + for prog_line in execute_program_extended: + cmd.extend(["-E", prog_line]) + + if programfile: + cmd.append(str(programfile)) + + if arguments: + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = shlex.join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # --- Structured Result Return --- + output_files = [] + if in_place_edit is not None and programfile: + # The original file is modified in place. + output_files.append(str(programfile)) + # A backup file might be created. + if in_place_edit: + backup_file = Path(f"{programfile}{in_place_edit}") + if backup_file.exists(): + output_files.append(str(backup_file)) + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/app/perl-mime-types_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/app/perl-mime-types_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..49615336511dbcbfc22545c0a70c750f059337c2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/app/perl-mime-types_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/app/perl-mime-types_server.py') +SERVER_NAME = 'biosci_perl_mime_types' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..84bc80de9d55ee188aa8eb7ef7e7d44f32e584da --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-mime-types: + build: . + image: mcp-perl-mime-types:latest + container_name: mcp-perl-mime-types + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-mime-types + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9a4ef1d9e6cb5659c05d4bbd4b15bffa6a9849bd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-mime-types + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mime-types/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..71c066710e467aa2b86746204b4008b036557f51 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-mldbm via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-mldbm -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-mldbm_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-mldbm_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-mldbm_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/app/perl-mldbm_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/app/perl-mldbm_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fc8b5d0a61e5e8ec8d5845b360a8f9e2605967e9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/app/perl-mldbm_server.py @@ -0,0 +1,521 @@ +import subprocess +from pathlib import Path +from typing import Optional, Dict, Any + +# MCP-compliant server for the perl-mldbm command-line tool. +# This script assumes that the @mcp.tool decorator is available in the execution environment +# and that the 'perl-mldbm' command is in the system's PATH. + +@mcp.tool() +def mldbm_store( + db_file: Path, + key: str, + value: str, + serializer: Optional[str] = None, + lock: bool = False, + mode: Optional[str] = None, +) -> Dict[str, Any]: + """ + Stores a key-value pair in an MLDBM database file. + + The value is evaluated as Perl code. For example, a simple string would be "'my string'", + a number would be "123", and an array reference would be "['a', 'b', 'c']". + + Args: + db_file: Path to the MLDBM database file. It will be created if it doesn't exist. + key: The key to store. + value: The value to store, expressed as a Perl literal. + serializer: Serializer to use. Valid options: 'Storable', 'FreezeThaw', 'Data::Dumper'. + lock: Use file locking during the operation. + mode: File creation mode in octal (e.g., '0644'). + """ + if not db_file.parent.exists(): + raise ValueError(f"Parent directory for db_file does not exist: {db_file.parent}") + if not key: + raise ValueError("The 'key' parameter cannot be empty.") + + valid_serializers = ["Storable", "FreezeThaw", "Data::Dumper"] + if serializer and serializer not in valid_serializers: + raise ValueError(f"Invalid serializer '{serializer}'. Must be one of {valid_serializers}.") + + if mode: + try: + int(mode, 8) + except ValueError: + raise ValueError(f"Invalid mode '{mode}'. Must be a valid octal string (e.g., '0644').") + + command = ["perl-mldbm"] + if serializer: + command.extend(["--serializer", serializer]) + if lock: + command.append("--lock") + if mode: + command.extend(["--mode", mode]) + + command.extend([str(db_file), "store", key, value]) + command_str = " ".join(command) + + try: + result = subprocess.run( + command, capture_output=True, text=True, check=True + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(db_file)] + } + except FileNotFoundError: + raise RuntimeError("perl-mldbm command not found. Is it installed and in your PATH?") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "error": "Command failed with a non-zero exit code.", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + +@mcp.tool() +def mldbm_fetch( + db_file: Path, + key: str, + serializer: Optional[str] = None, + lock: bool = False, +) -> Dict[str, Any]: + """ + Fetches the value for a given key from an MLDBM database file. + + Args: + db_file: Path to the MLDBM database file. + key: The key to fetch. + serializer: Serializer to use. Valid options: 'Storable', 'FreezeThaw', 'Data::Dumper'. + lock: Use file locking during the operation. + """ + if not db_file.exists(): + raise FileNotFoundError(f"Database file not found: {db_file}") + if not key: + raise ValueError("The 'key' parameter cannot be empty.") + + valid_serializers = ["Storable", "FreezeThaw", "Data::Dumper"] + if serializer and serializer not in valid_serializers: + raise ValueError(f"Invalid serializer '{serializer}'. Must be one of {valid_serializers}.") + + command = ["perl-mldbm"] + if serializer: + command.extend(["--serializer", serializer]) + if lock: + command.append("--lock") + + command.extend([str(db_file), "fetch", key]) + command_str = " ".join(command) + + try: + result = subprocess.run( + command, capture_output=True, text=True, check=True + ) + return { + "command_executed": command_str, + "value": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + raise RuntimeError("perl-mldbm command not found. Is it installed and in your PATH?") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "error": "Command failed. The key may not exist.", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + +@mcp.tool() +def mldbm_delete( + db_file: Path, + key: str, + serializer: Optional[str] = None, + lock: bool = False, +) -> Dict[str, Any]: + """ + Deletes a key-value pair from an MLDBM database file. + + Args: + db_file: Path to the MLDBM database file. + key: The key to delete. + serializer: Serializer to use. Valid options: 'Storable', 'FreezeThaw', 'Data::Dumper'. + lock: Use file locking during the operation. + """ + if not db_file.exists(): + raise FileNotFoundError(f"Database file not found: {db_file}") + if not key: + raise ValueError("The 'key' parameter cannot be empty.") + + valid_serializers = ["Storable", "FreezeThaw", "Data::Dumper"] + if serializer and serializer not in valid_serializers: + raise ValueError(f"Invalid serializer '{serializer}'. Must be one of {valid_serializers}.") + + command = ["perl-mldbm"] + if serializer: + command.extend(["--serializer", serializer]) + if lock: + command.append("--lock") + + command.extend([str(db_file), "delete", key]) + command_str = " ".join(command) + + try: + result = subprocess.run( + command, capture_output=True, text=True, check=True + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(db_file)] + } + except FileNotFoundError: + raise RuntimeError("perl-mldbm command not found. Is it installed and in your PATH?") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "error": "Command failed. The key may not have existed.", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + +@mcp.tool() +def mldbm_exists( + db_file: Path, + key: str, + serializer: Optional[str] = None, + lock: bool = False, +) -> Dict[str, Any]: + """ + Checks if a key exists in an MLDBM database file. + + Args: + db_file: Path to the MLDBM database file. + key: The key to check for existence. + serializer: Serializer to use. Valid options: 'Storable', 'FreezeThaw', 'Data::Dumper'. + lock: Use file locking during the operation. + """ + if not db_file.exists(): + raise FileNotFoundError(f"Database file not found: {db_file}") + if not key: + raise ValueError("The 'key' parameter cannot be empty.") + + valid_serializers = ["Storable", "FreezeThaw", "Data::Dumper"] + if serializer and serializer not in valid_serializers: + raise ValueError(f"Invalid serializer '{serializer}'. Must be one of {valid_serializers}.") + + command = ["perl-mldbm"] + if serializer: + command.extend(["--serializer", serializer]) + if lock: + command.append("--lock") + + command.extend([str(db_file), "exists", key]) + command_str = " ".join(command) + + try: + result = subprocess.run( + command, capture_output=True, text=True, check=False + ) + + if result.returncode == 0: + exists_status = True + elif result.returncode == 1: + exists_status = False + else: + return { + "command_executed": command_str, + "error": "Command failed with an unexpected error.", + "stdout": result.stdout, + "stderr": result.stderr, + "return_code": result.returncode, + } + + return { + "command_executed": command_str, + "exists": exists_status, + "stdout": result.stdout, + "stderr": result.stderr, + "return_code": result.returncode, + } + except FileNotFoundError: + raise RuntimeError("perl-mldbm command not found. Is it installed and in your PATH?") + +@mcp.tool() +def mldbm_keys( + db_file: Path, + serializer: Optional[str] = None, + lock: bool = False, +) -> Dict[str, Any]: + """ + Lists all keys in an MLDBM database file. + + Args: + db_file: Path to the MLDBM database file. + serializer: Serializer to use. Valid options: 'Storable', 'FreezeThaw', 'Data::Dumper'. + lock: Use file locking during the operation. + """ + if not db_file.exists(): + raise FileNotFoundError(f"Database file not found: {db_file}") + + valid_serializers = ["Storable", "FreezeThaw", "Data::Dumper"] + if serializer and serializer not in valid_serializers: + raise ValueError(f"Invalid serializer '{serializer}'. Must be one of {valid_serializers}.") + + command = ["perl-mldbm"] + if serializer: + command.extend(["--serializer", serializer]) + if lock: + command.append("--lock") + + command.extend([str(db_file), "keys"]) + command_str = " ".join(command) + + try: + result = subprocess.run( + command, capture_output=True, text=True, check=True + ) + return { + "command_executed": command_str, + "keys": result.stdout.splitlines(), + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + raise RuntimeError("perl-mldbm command not found. Is it installed and in your PATH?") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "error": "Command failed with a non-zero exit code.", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + +@mcp.tool() +def mldbm_values( + db_file: Path, + serializer: Optional[str] = None, + lock: bool = False, +) -> Dict[str, Any]: + """ + Lists all values in an MLDBM database file. + + Args: + db_file: Path to the MLDBM database file. + serializer: Serializer to use. Valid options: 'Storable', 'FreezeThaw', 'Data::Dumper'. + lock: Use file locking during the operation. + """ + if not db_file.exists(): + raise FileNotFoundError(f"Database file not found: {db_file}") + + valid_serializers = ["Storable", "FreezeThaw", "Data::Dumper"] + if serializer and serializer not in valid_serializers: + raise ValueError(f"Invalid serializer '{serializer}'. Must be one of {valid_serializers}.") + + command = ["perl-mldbm"] + if serializer: + command.extend(["--serializer", serializer]) + if lock: + command.append("--lock") + + command.extend([str(db_file), "values"]) + command_str = " ".join(command) + + try: + result = subprocess.run( + command, capture_output=True, text=True, check=True + ) + return { + "command_executed": command_str, + "values": result.stdout.splitlines(), + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + raise RuntimeError("perl-mldbm command not found. Is it installed and in your PATH?") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "error": "Command failed with a non-zero exit code.", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + +@mcp.tool() +def mldbm_dump( + db_file: Path, + serializer: Optional[str] = None, + lock: bool = False, +) -> Dict[str, Any]: + """ + Dumps the entire content of an MLDBM database file to stdout. + + Args: + db_file: Path to the MLDBM database file. + serializer: Serializer to use. Valid options: 'Storable', 'FreezeThaw', 'Data::Dumper'. + lock: Use file locking during the operation. + """ + if not db_file.exists(): + raise FileNotFoundError(f"Database file not found: {db_file}") + + valid_serializers = ["Storable", "FreezeThaw", "Data::Dumper"] + if serializer and serializer not in valid_serializers: + raise ValueError(f"Invalid serializer '{serializer}'. Must be one of {valid_serializers}.") + + command = ["perl-mldbm"] + if serializer: + command.extend(["--serializer", serializer]) + if lock: + command.append("--lock") + + command.extend([str(db_file), "dump"]) + command_str = " ".join(command) + + try: + result = subprocess.run( + command, capture_output=True, text=True, check=True + ) + return { + "command_executed": command_str, + "dump": result.stdout, + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + raise RuntimeError("perl-mldbm command not found. Is it installed and in your PATH?") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "error": "Command failed with a non-zero exit code.", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + +@mcp.tool() +def mldbm_load( + db_file: Path, + input_data: str, + serializer: Optional[str] = None, + lock: bool = False, + mode: Optional[str] = None, +) -> Dict[str, Any]: + """ + Loads data from STDIN into an MLDBM database file. + + The input data should be formatted as key-value pairs, separated by a tab, one per line. + The value is evaluated as Perl code. + + Args: + db_file: Path to the MLDBM database file. It will be created if it doesn't exist. + input_data: A string containing the data to load, typically key\\tvalue\\n. + serializer: Serializer to use. Valid options: 'Storable', 'FreezeThaw', 'Data::Dumper'. + lock: Use file locking during the operation. + mode: File creation mode in octal (e.g., '0644'). + """ + if not db_file.parent.exists(): + raise ValueError(f"Parent directory for db_file does not exist: {db_file.parent}") + if not input_data: + raise ValueError("The 'input_data' parameter cannot be empty.") + + valid_serializers = ["Storable", "FreezeThaw", "Data::Dumper"] + if serializer and serializer not in valid_serializers: + raise ValueError(f"Invalid serializer '{serializer}'. Must be one of {valid_serializers}.") + + if mode: + try: + int(mode, 8) + except ValueError: + raise ValueError(f"Invalid mode '{mode}'. Must be a valid octal string (e.g., '0644').") + + command = ["perl-mldbm"] + if serializer: + command.extend(["--serializer", serializer]) + if lock: + command.append("--lock") + if mode: + command.extend(["--mode", mode]) + + command.extend([str(db_file), "load"]) + command_str = " ".join(command) + + try: + result = subprocess.run( + command, input=input_data, capture_output=True, text=True, check=True + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(db_file)] + } + except FileNotFoundError: + raise RuntimeError("perl-mldbm command not found. Is it installed and in your PATH?") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "error": "Command failed with a non-zero exit code.", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + +@mcp.tool() +def mldbm_clear( + db_file: Path, + serializer: Optional[str] = None, + lock: bool = False, +) -> Dict[str, Any]: + """ + Removes all entries from an MLDBM database file. + + Args: + db_file: Path to the MLDBM database file. + serializer: Serializer to use. Valid options: 'Storable', 'FreezeThaw', 'Data::Dumper'. + lock: Use file locking during the operation. + """ + if not db_file.exists(): + raise FileNotFoundError(f"Database file not found: {db_file}") + + valid_serializers = ["Storable", "FreezeThaw", "Data::Dumper"] + if serializer and serializer not in valid_serializers: + raise ValueError(f"Invalid serializer '{serializer}'. Must be one of {valid_serializers}.") + + command = ["perl-mldbm"] + if serializer: + command.extend(["--serializer", serializer]) + if lock: + command.append("--lock") + + command.extend([str(db_file), "clear"]) + command_str = " ".join(command) + + try: + result = subprocess.run( + command, capture_output=True, text=True, check=True + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(db_file)] + } + except FileNotFoundError: + raise RuntimeError("perl-mldbm command not found. Is it installed and in your PATH?") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "error": "Command failed with a non-zero exit code.", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/app/perl-mldbm_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/app/perl-mldbm_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9b233dfc46b49ec124a083ae4980db473411dbf9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/app/perl-mldbm_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/app/perl-mldbm_server.py') +SERVER_NAME = 'biosci_perl_mldbm' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..afe2f8b10a6f0c4cab6b58eb2fe7e6d7ad7f5008 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-mldbm: + build: . + image: mcp-perl-mldbm:latest + container_name: mcp-perl-mldbm + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-mldbm + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4e9d1fe947ead7c66945cbca8ee186b29e456fdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-mldbm + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mldbm/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2a1dc9ba79ad58ef6606d2d57209d8463fbe4254 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-module-build via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-module-build -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-module-build_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-module-build_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-module-build_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/app/perl-module-build_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/app/perl-module-build_server.py new file mode 100644 index 0000000000000000000000000000000000000000..944fa6f3e3dd0bc46277eb13dd838a31766ac6aa --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/app/perl-module-build_server.py @@ -0,0 +1,214 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +@mcp.tool() +def perl_module_build_configure( + build_pl_path: str = "Build.PL", + install_base: Optional[str] = None, + prefix: Optional[str] = None, + installdirs: Optional[str] = None, + destdir: Optional[str] = None, + verbose: bool = False, + uninst: bool = False, + extra_args: Optional[List[str]] = None, +): + """ + Runs the initial configuration step for a Perl module using Module::Build (perl Build.PL). + + Args: + build_pl_path: Path to the Build.PL script (default: "Build.PL"). + install_base: Install all files relative to this directory. + prefix: Target directory for installation (standard Unix-style). + installdirs: Where to install: 'core', 'site', or 'vendor'. + destdir: Staging directory for installation (useful for packaging). + verbose: Enable verbose output during configuration. + uninst: Uninstall conflicting files before installing. + extra_args: Additional command-line arguments for Build.PL. + """ + build_pl = Path(build_pl_path) + if not build_pl.exists(): + return { + "error": f"Configuration script '{build_pl_path}' not found.", + "command_executed": f"perl {build_pl_path}" + } + + cmd = ["perl", str(build_pl)] + + if install_base: + cmd.append(f"--install_base={install_base}") + if prefix: + cmd.append(f"--prefix={prefix}") + if installdirs: + if installdirs not in ["core", "site", "vendor"]: + return {"error": "installdirs must be one of: core, site, vendor"} + cmd.append(f"--installdirs={installdirs}") + if destdir: + cmd.append(f"--destdir={destdir}") + if verbose: + cmd.append("--verbose=1") + if uninst: + cmd.append("--uninst=1") + + if extra_args: + cmd.extend(extra_args) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "failed" + } + +@mcp.tool() +def perl_module_build_action( + action: str = "build", + build_script_path: str = "./Build", + verbose: bool = False, + extra_args: Optional[List[str]] = None, +): + """ + Executes an action using the generated 'Build' script. + + Args: + action: The action to perform (e.g., 'build', 'test', 'install', 'clean', 'dist', 'manifest'). + build_script_path: Path to the 'Build' executable generated by Build.PL (default: "./Build"). + verbose: Enable verbose output for the action. + extra_args: Additional arguments to pass to the Build script. + """ + # Common actions: build, test, install, clean, realclean, dist, distcheck, disttest, manifest, help + build_script = Path(build_script_path) + if not build_script.exists(): + return { + "error": f"Build script '{build_script_path}' not found. Did you run perl_module_build_configure first?", + "command_executed": f"{build_script_path} {action}" + } + + cmd = [str(build_script), action] + + if verbose: + cmd.append("--verbose=1") + + if extra_args: + cmd.extend(extra_args) + + try: + # Ensure the script is executable + if not build_script.suffix == ".bat": # On Unix-like systems + subprocess.run(["chmod", "+x", str(build_script)], check=False) + + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "failed" + } + +@mcp.tool() +def perl_interpreter( + program_file: Optional[str] = None, + one_liner: Optional[str] = None, + switches: Optional[List[str]] = None, + arguments: Optional[List[str]] = None, + check_syntax_only: bool = False, + warnings: bool = False, + include_dirs: Optional[List[str]] = None, +): + """ + General Perl interpreter tool to execute scripts or one-liners, covering standard perl CLI switches. + + Args: + program_file: Path to the perl script to execute. + one_liner: Perl code to execute (equivalent to -e). + switches: List of perl switches (e.g., ['-a', '-n', '-T']). + arguments: Arguments to pass to the perl script. + check_syntax_only: If True, runs perl with -c (syntax check only). + warnings: If True, enables warnings (-w). + include_dirs: List of directories to add to @INC (equivalent to -I). + """ + cmd = ["perl"] + + if warnings: + cmd.append("-w") + + if check_syntax_only: + cmd.append("-c") + + if include_dirs: + for d in include_dirs: + cmd.append(f"-I{d}") + + if switches: + cmd.extend(switches) + + if one_liner: + cmd.extend(["-e", one_liner]) + + if program_file: + p_file = Path(program_file) + if not p_file.exists() and not one_liner: + return {"error": f"Program file '{program_file}' not found."} + cmd.append(str(p_file)) + + if arguments: + cmd.extend(arguments) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "failed" + } + +@mcp.tool() +def perl_module_build_help(): + """ + Returns the help documentation for Module::Build actions. + """ + build_script = Path("./Build") + if build_script.exists(): + cmd = [str(build_script), "help"] + else: + cmd = ["perldoc", "Module::Build"] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Could not retrieve help. Ensure perl-module-build is installed.", + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/app/perl-module-build_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/app/perl-module-build_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..05f8deab28368e640f696fad867f1f9c16a95bc7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/app/perl-module-build_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/app/perl-module-build_server.py') +SERVER_NAME = 'biosci_perl_module_build' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..232bb3fc687defd38d62b842ae3a3c61d9430237 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-module-build: + build: . + image: mcp-perl-module-build:latest + container_name: mcp-perl-module-build + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-module-build + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ee9f4ec95814319e6e6014286a1fbb386d28510f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-module-build + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-build/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cb9f25b0f4529b2a654370ff1da38faab3ab983f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-module-corelist via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-module-corelist -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-module-corelist_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-module-corelist_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-module-corelist_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/app/perl-module-corelist_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/app/perl-module-corelist_server.py new file mode 100644 index 0000000000000000000000000000000000000000..de138f1fa04dbca2bfaf9123cdbeadec2f66d370 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/app/perl-module-corelist_server.py @@ -0,0 +1,360 @@ +import subprocess +import sys +from pathlib import Path +from typing import List, Optional + +# Note: The provided help was for the 'perl' interpreter. +# The actual tool is 'corelist', and its options have been sourced +# from standard documentation for the Module::CoreList package. + + +@mcp.tool() +def query_module( + module_name: str, + list_all_versions: bool = False +): + """ + Finds in which version(s) of perl a given module was shipped in the core distribution. + + Args: + module_name: The name of the Perl module to query (e.g., 'Test::More'). + list_all_versions: If True, lists all versions of perl that shipped with the module. + """ + if not module_name: + raise ValueError("module_name cannot be empty.") + + cmd = ["corelist"] + if list_all_versions: + cmd.append("-a") + cmd.append(module_name) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'corelist' command not found. Please ensure the perl-module-corelist package is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + +@mcp.tool() +def query_perl_version( + perl_version: str, + list_deprecated: bool = False +): + """ + Lists all modules or only deprecated modules shipped with a specific version of perl. + + Args: + perl_version: The specific version of perl to query (e.g., '5.014002'). + list_deprecated: If True, lists only modules that were deprecated in this perl version. + """ + if not perl_version: + raise ValueError("perl_version cannot be empty.") + + cmd = ["corelist"] + if list_deprecated: + cmd.append("-d") + else: + cmd.append("-v") + cmd.append(perl_version) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'corelist' command not found. Please ensure the perl-module-corelist package is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + +@mcp.tool() +def compare_perl_versions( + perl_version1: str, + perl_version2: str, + output_format: str = "text", + diff_type: str = "modules" +): + """ + Shows the differences in modules between two perl versions. + + Args: + perl_version1: The first perl version for comparison. + perl_version2: The second perl version for comparison. + output_format: The format for the output ('text' or 'json'). JSON is only for 'modules' diff_type. + diff_type: The type of difference to show ('modules', 'pre-release', 'deprecated'). + """ + if not perl_version1 or not perl_version2: + raise ValueError("perl_version1 and perl_version2 cannot be empty.") + + allowed_formats = ["text", "json"] + if output_format not in allowed_formats: + raise ValueError(f"Invalid output_format '{output_format}'. Allowed values are: {allowed_formats}") + + allowed_diff_types = ["modules", "pre-release", "deprecated"] + if diff_type not in allowed_diff_types: + raise ValueError(f"Invalid diff_type '{diff_type}'. Allowed values are: {allowed_diff_types}") + + if output_format == "json" and diff_type != "modules": + raise ValueError("JSON output format is only available for diff_type 'modules'.") + + cmd = ["corelist"] + flag_map = { + ("text", "modules"): "--diff", + ("json", "modules"): "--json-diff", + ("text", "pre-release"): "--diff-pre", + ("text", "deprecated"): "--diff-deprecated" + } + flag = flag_map[(output_format, diff_type)] + cmd.extend([flag, perl_version1, perl_version2]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'corelist' command not found. Please ensure the perl-module-corelist package is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + +@mcp.tool() +def list_perl_versions(): + """ + Lists all perl versions for which Module::CoreList has data. + """ + cmd = ["corelist", "--list-perl"] + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'corelist' command not found. Please ensure the perl-module-corelist package is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + +@mcp.tool() +def list_all_modules(): + """ + Lists all modules for which Module::CoreList has data. + """ + cmd = ["corelist", "--list-modules"] + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'corelist' command not found. Please ensure the perl-module-corelist package is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + +@mcp.tool() +def list_all_deprecated_modules(): + """ + Lists all deprecated modules for which Module::CoreList has data. + """ + cmd = ["corelist", "--list-deprecated"] + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'corelist' command not found. Please ensure the perl-module-corelist package is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + +@mcp.tool() +def query_feature( + feature_name: str +): + """ + Shows in which perl version a given feature (e.g., 'say') appeared. + + Args: + feature_name: The name of the feature to query. + """ + if not feature_name: + raise ValueError("feature_name cannot be empty.") + + cmd = ["corelist", "--feature", feature_name] + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'corelist' command not found. Please ensure the perl-module-corelist package is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + +@mcp.tool() +def get_version(): + """ + Shows the version of the Module::CoreList data. + """ + cmd = ["corelist", "--version"] + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'corelist' command not found. Please ensure the perl-module-corelist package is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/app/perl-module-corelist_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/app/perl-module-corelist_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2ca626ddbc6224c444280ed89a0779f548876452 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/app/perl-module-corelist_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/app/perl-module-corelist_server.py') +SERVER_NAME = 'biosci_perl_module_corelist' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f4457379cdfa31b5028a94047524d696ccdd6421 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-module-corelist: + build: . + image: mcp-perl-module-corelist:latest + container_name: mcp-perl-module-corelist + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-module-corelist + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6ee1d6223feabda981b56e7d8a70e5387c0c6cc9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-module-corelist + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-corelist/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ab41ce88cc3e3840609c59ff8f5bedb77ff9f46f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-module-implementation via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-module-implementation -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-module-implementation_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-module-implementation_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-module-implementation_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/app/perl-module-implementation_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/app/perl-module-implementation_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a0432e1b29463db34a9b7236da31e6c188646e60 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/app/perl-module-implementation_server.py @@ -0,0 +1,221 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# @mcp.tool() decorator is assumed to be available in the environment. +# No need to import it. + +@mcp.tool() +def perl_interpreter( + programfile: Optional[Path] = None, + execute_program: Optional[List[str]] = None, + execute_program_features: Optional[List[str]] = None, + arguments: Optional[List[str]] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + run_under_debugger: bool = False, + debugger_module: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + in_place_edit: Optional[str] = None, + include_dirs: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + modules: Optional[List[str]] = None, + loop_n: bool = False, + loop_p: bool = False, + parse_switches: bool = False, + search_path: bool = False, + taint_warnings: bool = False, + taint_checks: bool = False, + dump_core: bool = False, + allow_unsafe: bool = False, + print_version: bool = False, + print_config: Optional[str] = None, + warnings_useful: bool = False, + warnings_all: bool = False, + extract_script: Optional[str] = None, + warnings_disable: bool = False, +) -> Dict[str, Any]: + """ + Executes the Perl interpreter with a wide range of command-line switches. + + This tool is a wrapper for the `perl` command-line executable. It allows running Perl scripts, + checking syntax, and utilizing Perl's powerful one-liner capabilities. + + Args: + programfile: Path to the Perl program file to execute. + execute_program: One or more lines of a program to be executed via the -e switch. + execute_program_features: Like -e, but enables all optional features (-E switch). + arguments: A list of arguments to be passed to the program file. + record_separator: Specify the record separator (-0). For the null separator, provide an empty string "". + autosplit: Enable autosplit mode with -n or -p (-a). + unicode_features: Enable listed Unicode features (-C). + check_syntax_only: Check syntax only; does not execute the program (-c). + run_under_debugger: Run the program under the default Perl debugger (-d). + debugger_module: Run the program under a specific debugger module (-d:debugger). + debugging_flags: Set debugging flags (-D). + no_sitecustomize: Don't run $sitelib/sitecustomize.pl at startup (-f). + split_pattern: Specify the split() pattern for the -a switch (-F). + in_place_edit: Edit files in place (-i). Provide an extension for backups (e.g., ".bak"). + include_dirs: Specify @INC/#include directories (-I). + line_ending_processing: Enable line ending processing (-l). Provide an octal value for a custom terminator. + modules: Execute "use/no module..." before the program (-M or -m). Prefix with '-' for 'no'. + loop_n: Assume a "while (<>) { ... }" loop around the program (-n). + loop_p: Assume a loop like -n but also print the line (-p). + parse_switches: Enable rudimentary parsing for switches after the program file (-s). + search_path: Look for the program file using the PATH environment variable (-S). + taint_warnings: Enable tainting warnings (-t). + taint_checks: Enable tainting checks (-T). + dump_core: Dump core after parsing the program (-u). + allow_unsafe: Allow unsafe operations (-U). + print_version: Print the Perl version, patchlevel, and license, then exit (-v). + print_config: Print configuration summary (-V). Provide a variable name for specific config. + warnings_useful: Enable many useful warnings (-w). + warnings_all: Enable all warnings (-W). + extract_script: Ignore text before #!perl line (-x). Optionally provide a directory to cd into. + warnings_disable: Disable all warnings (-X). + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + script_sources = sum([ + programfile is not None, + execute_program is not None, + execute_program_features is not None + ]) + action_flags_set = print_version or print_config is not None or check_syntax_only + + if not action_flags_set and script_sources == 0: + raise ValueError("A script source ('programfile', 'execute_program', or 'execute_program_features') must be provided for execution.") + if script_sources > 1: + raise ValueError("Only one of 'programfile', 'execute_program', or 'execute_program_features' can be provided at a time.") + + if loop_n and loop_p: + raise ValueError("The '-n' (loop_n) and '-p' (loop_p) flags are mutually exclusive.") + + if run_under_debugger and debugger_module is not None: + raise ValueError("'run_under_debugger' (-d) and 'debugger_module' (-d:debugger) are mutually exclusive.") + + if programfile and not programfile.exists(): + raise FileNotFoundError(f"Input program file not found: {programfile}") + + # --- Command Construction --- + cmd = ["perl"] + + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if run_under_debugger: + cmd.append("-d") + if debugger_module is not None: + cmd.append(f"-d:{debugger_module}") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if in_place_edit is not None: + cmd.append(f"-i{in_place_edit}") + if include_dirs: + for directory in include_dirs: + cmd.append(f"-I{directory}") + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + if modules: + for module in modules: + # Assuming -M is the desired default, user can include -m or - in the string + if not module.startswith(("-m", "-M")): + cmd.append(f"-M{module}") + else: + cmd.append(module) + if loop_n: + cmd.append("-n") + if loop_p: + cmd.append("-p") + if parse_switches: + cmd.append("-s") + if search_path: + cmd.append("-S") + if taint_warnings: + cmd.append("-t") + if taint_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if allow_unsafe: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config is not None: + cmd.append(f"-V:{print_config}") + if warnings_useful: + cmd.append("-w") + if warnings_all: + cmd.append("-W") + if extract_script is not None: + cmd.append(f"-x{extract_script}") + if warnings_disable: + cmd.append("-X") + + # Add script source + if execute_program: + for line in execute_program: + cmd.extend(["-e", line]) + if execute_program_features: + for line in execute_program_features: + cmd.extend(["-E", line]) + + # Add program file and arguments + if programfile: + cmd.append(str(programfile)) + if arguments: + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = result.stdout + stderr = result.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed with return code {e.returncode}", + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in the system's PATH.", + "error": "Command not found", + "output_files": [] + } + + # --- Structured Result Return --- + # Perl itself doesn't manage output files via flags; scripts handle I/O. + # The output_files list is returned empty as it cannot be determined from the command. + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/app/perl-module-implementation_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/app/perl-module-implementation_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9898fd78cc1050d71eb26f0c424fc2a71765406b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/app/perl-module-implementation_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/app/perl-module-implementation_server.py') +SERVER_NAME = 'biosci_perl_module_implementation' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5fc28b7ffe191f3510aa4282d9e67d9b15fa549f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-module-implementation: + build: . + image: mcp-perl-module-implementation:latest + container_name: mcp-perl-module-implementation + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-module-implementation + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..162ddf105f8661449f931a1b8c93d84945ef0669 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-module-implementation + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-implementation/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..826c4a07b1387a2463dedae2af6fc771f7046c79 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-module-load-conditional via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-module-load-conditional -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-module-load-conditional_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-module-load-conditional_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-module-load-conditional_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/app/perl-module-load-conditional_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/app/perl-module-load-conditional_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e88b4b438289fb322193f3cbdbd77b1ca9678a4f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/app/perl-module-load-conditional_server.py @@ -0,0 +1,289 @@ +import subprocess +import json +import tempfile +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Helper function to run Perl scripts +def _run_perl_script(script_content: str, env_vars: Optional[Dict[str, str]] = None) -> Dict[str, Any]: + """ + Executes a Perl script and captures its stdout/stderr. + + Args: + script_content: The Perl script content as a string. + env_vars: A dictionary of environment variables to set for the Perl process. + + Returns: + A dictionary containing execution details, stdout, stderr, and parsed output. + """ + script_path: Optional[Path] = None + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".pl") as tmp_script: + tmp_script.write(script_content) + script_path = Path(tmp_script.name) + + command = ["perl", str(script_path)] + + # Prepare environment variables for the subprocess + full_env = os.environ.copy() + if env_vars: + full_env.update(env_vars) + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + env=full_env + ) + stdout = process.stdout.strip() + stderr = process.stderr.strip() + + # Attempt to parse JSON output + parsed_output: Any + try: + parsed_output = json.loads(stdout) + except json.JSONDecodeError: + parsed_output = {"raw_stdout": stdout} # Fallback if not JSON + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output": parsed_output, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "error": f"Perl script execution failed with exit code {e.returncode}", + "returncode": e.returncode, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'perl' executable not found. Please ensure Perl is installed and in your PATH.", + "error": "Perl executable not found", + "returncode": 127, + "output_files": [] + } + finally: + # Clean up the temporary script file + if script_path and script_path.exists(): + os.remove(script_path) + +@mcp.tool() +def check_module_install( + module_name: str, + min_version: Optional[str] = None, + verbose: bool = False, + find_version: bool = True, + check_inc_hash: bool = False, + force_safe_inc: bool = False, + check_deprecated: bool = False, +) -> Dict[str, Any]: + """ + Verifies if a Perl module is installed and optionally checks its version using Module::Load::Conditional. + + Args: + module_name: The name of the Perl module to verify (e.g., 'LWP'). + min_version: The minimum version the module needs to be. If not provided, any version is considered good. + verbose: Controls whether Module::Load::Conditional will issue warnings and explanations. + Defaults to False. + find_version: Controls whether Module::Load::Conditional will try to parse (and eval) + the version from the module. Set to False for security/performance if version + comparisons are not needed. Defaults to True. + check_inc_hash: Controls whether Module::Load::Conditional checks the %INC hash + (already loaded modules) in addition to @INC (filesystem). Defaults to False. + force_safe_inc: Controls whether Module::Load::Conditional sanitizes @INC by removing ".". + Defaults to False. + check_deprecated: Controls whether Module::Load::Conditional checks if a dual-life core module + has been deprecated. If True, check_install will return false to 'uptodate' + if a deprecated dual-life module is loaded from $Config{privlibexp}. Defaults to False. + + Returns: + A dictionary containing execution details, stdout, stderr, and parsed output. + The 'output' key will contain a dictionary with 'file', 'dir', 'version', 'uptodate' + if the module is found, or an 'error' key if not. + """ + if not module_name: + raise ValueError("Module name cannot be empty.") + + perl_script_template = """ + use strict; + use warnings; + use JSON; + use Module::Load::Conditional qw[check_install]; + + $Module::Load::Conditional::VERBOSE = $ENV{MCP_VERBOSE}; + $Module::Load::Conditional::FIND_VERSION = $ENV{MCP_FIND_VERSION}; + $Module::Load::Conditional::CHECK_INC_HASH = $ENV{MCP_CHECK_INC_HASH}; + $Module::Load::Conditional::FORCE_SAFE_INC = $ENV{MCP_FORCE_SAFE_INC}; + $Module::Load::Conditional::DEPRECATED = $ENV{MCP_DEPRECATED}; + + my %%args = ( module => $ENV{MCP_MODULE_NAME} ); + if (defined $ENV{MCP_MIN_VERSION} && $ENV{MCP_MIN_VERSION} ne '') { + $args{version} = $ENV{MCP_MIN_VERSION}; + } + + my $result = check_install(%%args); + + if (defined $result) { + print encode_json($result) . "\\n"; + } else { + print encode_json({ error => "Module '$ENV{MCP_MODULE_NAME}' not found or could not be installed." }) . "\\n"; + } + """ + + env_vars = { + "MCP_MODULE_NAME": module_name, + "MCP_MIN_VERSION": min_version if min_version is not None else "", + "MCP_VERBOSE": "1" if verbose else "0", + "MCP_FIND_VERSION": "1" if find_version else "0", + "MCP_CHECK_INC_HASH": "1" if check_inc_hash else "0", + "MCP_FORCE_SAFE_INC": "1" if force_safe_inc else "0", + "MCP_DEPRECATED": "1" if check_deprecated else "0", + } + + return _run_perl_script(perl_script_template, env_vars) + +@mcp.tool() +def can_load_modules( + modules: Dict[str, Optional[str]], + verbose: bool = False, + nocache: bool = False, + autoload: bool = False, + check_inc_hash: bool = False, + force_safe_inc: bool = False, + clear_cache: bool = False, +) -> Dict[str, Any]: + """ + Determines if a list of Perl modules can be loaded, and loads them if all are possible. + If one or more are unloadable, none will be loaded. + + Args: + modules: A dictionary where keys are module names (e.g., 'CPANPLUS') and values + are optional minimum version strings (e.g., '0.05') or None. + verbose: Controls whether Module::Load::Conditional will issue warnings and explanations. + Defaults to False. + nocache: If True, can_load will not use its internal cache and will attempt to load + modules even if they previously failed or were already loaded. Defaults to False. + autoload: If True, imports the functions of loaded modules into the caller package. + Defaults to False. + check_inc_hash: Controls whether Module::Load::Conditional checks the %INC hash + (already loaded modules) in addition to @INC (filesystem). Defaults to False. + force_safe_inc: Controls whether Module::Load::Conditional sanitizes @INC by removing ".". + Defaults to False. + clear_cache: If True, clears the internal cache of can_load before execution. Defaults to False. + + Returns: + A dictionary containing execution details, stdout, stderr, and parsed output. + The 'output' key will contain a dictionary with 'success' (boolean) and 'error' (string, if any). + """ + if not modules: + raise ValueError("The 'modules' dictionary cannot be empty.") + if not isinstance(modules, dict): + raise TypeError("The 'modules' argument must be a dictionary.") + for module_name, version in modules.items(): + if not isinstance(module_name, str): + raise ValueError(f"Module name '{module_name}' must be a string.") + if version is not None and not isinstance(version, str): + raise ValueError(f"Version for module '{module_name}' must be a string or None.") + + modules_json = json.dumps(modules) + + perl_script_template = """ + use strict; + use warnings; + use JSON; + use Module::Load::Conditional qw[can_load]; + + $Module::Load::Conditional::VERBOSE = $ENV{MCP_VERBOSE}; + $Module::Load::Conditional::CHECK_INC_HASH = $ENV{MCP_CHECK_INC_HASH}; + $Module::Load::Conditional::FORCE_SAFE_INC = $ENV{MCP_FORCE_SAFE_INC}; + + if ($ENV{MCP_CLEAR_CACHE}) { + undef $Module::Load::Conditional::CACHE; + } + + my $modules_hash_ref = decode_json($ENV{MCP_MODULES_JSON}); + my %%args = ( modules => $modules_hash_ref ); + if ($ENV{MCP_NOCACHE}) { + $args{nocache} = 1; + } + if ($ENV{MCP_AUTOLOAD}) { + $args{autoload} = 1; + } + + my $result = can_load(%%args); + + print encode_json({ success => $result ? 1 : 0, error => $Module::Load::Conditional::ERROR }) . "\\n"; + """ + + env_vars = { + "MCP_MODULES_JSON": modules_json, + "MCP_VERBOSE": "1" if verbose else "0", + "MCP_NOCACHE": "1" if nocache else "0", + "MCP_AUTOLOAD": "1" if autoload else "0", + "MCP_CHECK_INC_HASH": "1" if check_inc_hash else "0", + "MCP_FORCE_SAFE_INC": "1" if force_safe_inc else "0", + "MCP_CLEAR_CACHE": "1" if clear_cache else "0", + } + + return _run_perl_script(perl_script_template, env_vars) + +@mcp.tool() +def get_module_requirements( + module_name: str, + check_inc_hash: bool = False, + force_safe_inc: bool = False, +) -> Dict[str, Any]: + """ + Retrieves a list of other modules that a particular Perl module requires. + + Args: + module_name: The name of the Perl module to query for requirements. + check_inc_hash: Controls whether Module::Load::Conditional checks the %INC hash + (already loaded modules) in addition to @INC (filesystem). Defaults to False. + force_safe_inc: Controls whether Module::Load::Conditional sanitizes @INC by removing ".". + Defaults to False. + + Returns: + A dictionary containing execution details, stdout, stderr, and parsed output. + The 'output' key will contain a dictionary with a 'requires' list of module names, + or an 'error' key if requirements could not be determined. + """ + if not module_name: + raise ValueError("Module name cannot be empty.") + + perl_script_template = """ + use strict; + use warnings; + use JSON; + use Module::Load::Conditional qw[requires]; + + $Module::Load::Conditional::CHECK_INC_HASH = $ENV{MCP_CHECK_INC_HASH}; + $Module::Load::Conditional::FORCE_SAFE_INC = $ENV{MCP_FORCE_SAFE_INC}; + + my $module_name = $ENV{MCP_MODULE_NAME}; + my @list = requires($module_name); + + if (defined @list) { + print encode_json({ requires => \\@list }) . "\\n"; + } else { + print encode_json({ error => "Could not determine requirements for module '$module_name'. It might not be installed or loadable." }) . "\\n"; + } + """ + + env_vars = { + "MCP_MODULE_NAME": module_name, + "MCP_CHECK_INC_HASH": "1" if check_inc_hash else "0", + "MCP_FORCE_SAFE_INC": "1" if force_safe_inc else "0", + } + + return _run_perl_script(perl_script_template, env_vars) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/app/perl-module-load-conditional_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/app/perl-module-load-conditional_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bf049a8ba7b7caab08e847571887c95a96b93919 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/app/perl-module-load-conditional_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/app/perl-module-load-conditional_server.py') +SERVER_NAME = 'biosci_perl_module_load_conditional' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0e2d34cd17c901164b412fdffd779fa7b952de14 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-module-load-conditional: + build: . + image: mcp-perl-module-load-conditional:latest + container_name: mcp-perl-module-load-conditional + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-module-load-conditional + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..324df456d09bee71c32c59a9e44110a83614df53 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-module-load-conditional + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load-conditional/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0a4d69fd256cb52436ef0906d26e47ed6b2a0554 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-module-load via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-module-load -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-module-load_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-module-load_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-module-load_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/app/perl-module-load_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/app/perl-module-load_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a1e8ba51e0b6c7a092b1d699bb05c00f5ffa0611 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/app/perl-module-load_server.py @@ -0,0 +1,188 @@ +import subprocess +import shlex +from pathlib import Path +from typing import Optional, List + +# @mcp.tool() decorator is implied +def perl_interpreter( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + e_program: Optional[List[str]] = None, + E_program: Optional[List[str]] = None, + check_syntax_only: bool = False, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + include_directories: Optional[List[Path]] = None, + use_modules: Optional[List[str]] = None, + use_modules_no_import: Optional[List[str]] = None, + no_modules: Optional[List[str]] = None, + loop_n: bool = False, + loop_p: bool = False, + autosplit: bool = False, + split_pattern: Optional[str] = None, + in_place_edit: Optional[str] = None, + line_ending: Optional[str] = None, + record_separator: Optional[str] = None, + parse_switches: bool = False, + search_path: bool = False, + tainting_checks: bool = False, + tainting_warnings: bool = False, + unsafe_operations: bool = False, + unicode_features: Optional[str] = None, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + dump_core: bool = False, + extract_script: Optional[str] = None, + print_version: bool = False, + print_config: Optional[str] = None, +): + """ + Executes a Perl script or one-liner using the Perl interpreter. + + This tool is a wrapper for the `perl` command-line executable, providing access + to its full range of switches for script execution, module loading, syntax + checking, and more. + + Args: + programfile: Path to the Perl program file to be executed. + arguments: A list of arguments to be passed to the program file. + e_program: Provides one line of a program. Multiple lines can be provided in a list. + E_program: Like -e, but enables all optional features. + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). Corresponds to the -c flag. + enable_warnings: Enable many useful warnings. Corresponds to the -w flag. + enable_all_warnings: Enable all warnings. Corresponds to the -W flag. + disable_all_warnings: Disable all warnings. Corresponds to the -X flag. + include_directories: Specifies @INC/#include directories. Corresponds to the -I flag. + use_modules: Executes "use module..." before the program. Corresponds to the -M flag. + use_modules_no_import: Executes "use module ()..." before the program. Corresponds to the -m flag. + no_modules: Executes "no module..." before the program. Corresponds to the -M- or -m- flag. + loop_n: Assume a "while (<>) { ... }" loop around the program. Corresponds to the -n flag. + loop_p: Assume a loop like -n but also print the line. Corresponds to the -p flag. + autosplit: Enable autosplit mode with -n or -p. Corresponds to the -a flag. + split_pattern: Specifies the split() pattern for the -a switch. Corresponds to the -F flag. + in_place_edit: Edit files in place. Provide an extension (e.g., '.bak') to create backups. Corresponds to the -i flag. + line_ending: Enable line ending processing and specify the terminator. Corresponds to the -l flag. + record_separator: Specify the record separator. Corresponds to the -0 flag. + parse_switches: Enable rudimentary parsing for switches after the program file. Corresponds to the -s flag. + search_path: Look for the program file using the PATH environment variable. Corresponds to the -S flag. + tainting_checks: Enable tainting checks. Corresponds to the -T flag. + tainting_warnings: Enable tainting warnings. Corresponds to the -t flag. + unsafe_operations: Allow unsafe operations. Corresponds to the -U flag. + unicode_features: Enable listed Unicode features. Corresponds to the -C flag. + debugger: Run the program under a debugger. Can specify the debugger (e.g., ':PerlDB'). Corresponds to the -d flag. + debugging_flags: Set debugging flags. Corresponds to the -D flag. + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. Corresponds to the -f flag. + dump_core: Dump core after parsing the program. Corresponds to the -u flag. + extract_script: Ignore text before #!perl line. Optionally cd to the specified directory. Corresponds to the -x flag. + print_version: Print version, patchlevel, and license. Corresponds to the -v flag. + print_config: Print configuration summary, or a single Config.pm variable. Corresponds to the -V flag. + + Returns: + A dictionary containing the executed command, stdout, stderr, and output file paths. + """ + # --- Input Validation --- + if programfile and (e_program or E_program): + raise ValueError("Cannot specify both a 'programfile' and a one-liner ('e_program' or 'E_program').") + + action_flags = print_version or (print_config is not None) + script_flags = programfile or e_program or E_program + if not action_flags and not script_flags: + raise ValueError("A script (programfile, e_program, E_program) or an action (print_version, print_config) must be provided.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"The specified program file does not exist: {programfile}") + + # --- Command Construction --- + cmd = ["perl"] + + # Boolean flags + if check_syntax_only: cmd.append("-c") + if enable_warnings: cmd.append("-w") + if enable_all_warnings: cmd.append("-W") + if disable_all_warnings: cmd.append("-X") + if loop_n: cmd.append("-n") + if loop_p: cmd.append("-p") + if autosplit: cmd.append("-a") + if parse_switches: cmd.append("-s") + if search_path: cmd.append("-S") + if tainting_checks: cmd.append("-T") + if tainting_warnings: cmd.append("-t") + if unsafe_operations: cmd.append("-U") + if no_sitecustomize: cmd.append("-f") + if dump_core: cmd.append("-u") + if print_version: cmd.append("-v") + + # Flags with values (no space between flag and value) + if record_separator is not None: cmd.append(f"-0{record_separator}") + if unicode_features is not None: cmd.append(f"-C{unicode_features}") + if debugger is not None: cmd.append(f"-d{debugger}") + if debugging_flags is not None: cmd.append(f"-D{debugging_flags}") + if split_pattern is not None: cmd.append(f"-F{split_pattern}") + if in_place_edit is not None: cmd.append(f"-i{in_place_edit}") + if line_ending is not None: cmd.append(f"-l{line_ending}") + if print_config is not None: cmd.append(f"-V{print_config}") + if extract_script is not None: cmd.append(f"-x{extract_script}") + + # List-based flags + if include_directories: + for directory in include_directories: + cmd.append(f"-I{directory}") + if use_modules: + for module in use_modules: + cmd.append(f"-M{module}") + if use_modules_no_import: + for module in use_modules_no_import: + cmd.append(f"-m{module}") + if no_modules: + for module in no_modules: + cmd.append(f"-M-{module}") + if e_program: + for line in e_program: + cmd.extend(["-e", line]) + if E_program: + for line in E_program: + cmd.extend(["-E", line]) + + # Program file and arguments + if programfile: + cmd.append("--") + cmd.append(str(programfile)) + + if arguments: + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = shlex.join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your system's PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # --- Structured Result Return --- + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [] # Perl execution does not have a standard output file parameter + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/app/perl-module-load_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/app/perl-module-load_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b418bbb75eb930eddd8116477a158b2bc533936a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/app/perl-module-load_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/app/perl-module-load_server.py') +SERVER_NAME = 'biosci_perl_module_load' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0588ee9bd2444455cf09435a266a7688c473b044 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-module-load: + build: . + image: mcp-perl-module-load:latest + container_name: mcp-perl-module-load + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-module-load + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..41b83d70d72bce3c2a1ec2764e58b5a969077cd0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-module-load + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-load/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..542d3b3a1f2fc69c5630c24c2d5143f5ebb14fbf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-module-metadata via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-module-metadata -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-module-metadata_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-module-metadata_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-module-metadata_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/app/perl-module-metadata_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/app/perl-module-metadata_server.py new file mode 100644 index 0000000000000000000000000000000000000000..de5a7b2a226d8eed59a68150cd9278d79179d8e3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/app/perl-module-metadata_server.py @@ -0,0 +1,241 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +# This tool is based on the `module-metadata` command-line utility, +# which is part of the Perl Module::Metadata distribution. +# The user specified the tool name as `perl-module-metadata`, which will be used +# as the executable name. + +def _run_module_metadata_command( + base_args: List[str], + files: List[Path], + no_index: bool, + inc: Optional[List[Path]] +) -> Dict[str, Any]: + """ + A helper function to build and execute the perl-module-metadata command. + + Args: + base_args: A list of primary command arguments (e.g., ['--determine-packages']). + files: A list of input file paths to analyze. + no_index: If True, adds the --no-index flag. + inc: An optional list of directories to add to the library search path. + + Returns: + A dictionary containing the execution details and results. + """ + # 1. Input Validation + if not files: + raise ValueError("At least one input file must be provided.") + for file_path in files: + if not file_path.is_file(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + if inc: + for dir_path in inc: + if not dir_path.is_dir(): + raise NotADirectoryError(f"Include path is not a directory: {dir_path}") + + # 2. Command Construction + command = ["perl-module-metadata"] + command.extend(base_args) + + if no_index: + command.append("--no-index") + + if inc: + for dir_path in inc: + command.extend(["--inc", str(dir_path)]) + + command.extend([str(f) for f in files]) + command_str = " ".join(command) + + # 3. Subprocess Execution and Error Handling + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_str, + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "output_files": [] # This tool primarily outputs to stdout + } + except FileNotFoundError: + raise RuntimeError( + "Error: 'perl-module-metadata' command not found. " + "Please ensure it is installed and in your system's PATH." + ) from None + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "error": f"Command failed with exit code {e.returncode}" + } + +@mcp.tool() +def determine_packages( + files: List[Path], + no_index: bool = False, + inc: Optional[List[Path]] = None, +): + """ + Determines packages from given Perl module files. Corresponds to the --determine-packages flag. + """ + base_args = ["--determine-packages"] + return _run_module_metadata_command(base_args, files, no_index, inc) + +@mcp.tool() +def get_package_version( + package: str, + files: List[Path], + no_index: bool = False, + inc: Optional[List[Path]] = None, +): + """ + Determines the version of a given package from Perl module files. Corresponds to the --package-version flag. + """ + if not package: + raise ValueError("Package name cannot be empty.") + base_args = [f"--package-version={package}"] + return _run_module_metadata_command(base_args, files, no_index, inc) + +@mcp.tool() +def get_module_version( + module: str, + files: List[Path], + no_index: bool = False, + inc: Optional[List[Path]] = None, +): + """ + Determines the version of a given module from Perl module files. Corresponds to the --module-version flag. + """ + if not module: + raise ValueError("Module name cannot be empty.") + base_args = [f"--module-version={module}"] + return _run_module_metadata_command(base_args, files, no_index, inc) + +@mcp.tool() +def get_module_requires( + module: str, + files: List[Path], + no_index: bool = False, + inc: Optional[List[Path]] = None, +): + """ + Determines the requirements of a given module. Corresponds to the --requires flag. + """ + if not module: + raise ValueError("Module name cannot be empty.") + base_args = [f"--requires={module}"] + return _run_module_metadata_command(base_args, files, no_index, inc) + +@mcp.tool() +def get_module_optional_requires( + module: str, + files: List[Path], + no_index: bool = False, + inc: Optional[List[Path]] = None, +): + """ + Determines the optional requirements of a given module. Corresponds to the --optional-requires flag. + """ + if not module: + raise ValueError("Module name cannot be empty.") + base_args = [f"--optional-requires={module}"] + return _run_module_metadata_command(base_args, files, no_index, inc) + +@mcp.tool() +def get_module_recommends( + module: str, + files: List[Path], + no_index: bool = False, + inc: Optional[List[Path]] = None, +): + """ + Determines the recommended requirements of a given module. Corresponds to the --recommends flag. + """ + if not module: + raise ValueError("Module name cannot be empty.") + base_args = [f"--recommends={module}"] + return _run_module_metadata_command(base_args, files, no_index, inc) + +@mcp.tool() +def get_module_suggests( + module: str, + files: List[Path], + no_index: bool = False, + inc: Optional[List[Path]] = None, +): + """ + Determines the suggested requirements of a given module. Corresponds to the --suggests flag. + """ + if not module: + raise ValueError("Module name cannot be empty.") + base_args = [f"--suggests={module}"] + return _run_module_metadata_command(base_args, files, no_index, inc) + +@mcp.tool() +def get_module_conflicts( + module: str, + files: List[Path], + no_index: bool = False, + inc: Optional[List[Path]] = None, +): + """ + Determines the conflicting requirements of a given module. Corresponds to the --conflicts flag. + """ + if not module: + raise ValueError("Module name cannot be empty.") + base_args = [f"--conflicts={module}"] + return _run_module_metadata_command(base_args, files, no_index, inc) + +@mcp.tool() +def get_module_build_requires( + module: str, + files: List[Path], + no_index: bool = False, + inc: Optional[List[Path]] = None, +): + """ + Determines the build requirements of a given module. Corresponds to the --build-requires flag. + """ + if not module: + raise ValueError("Module name cannot be empty.") + base_args = [f"--build-requires={module}"] + return _run_module_metadata_command(base_args, files, no_index, inc) + +@mcp.tool() +def get_module_configure_requires( + module: str, + files: List[Path], + no_index: bool = False, + inc: Optional[List[Path]] = None, +): + """ + Determines the configure requirements of a given module. Corresponds to the --configure-requires flag. + """ + if not module: + raise ValueError("Module name cannot be empty.") + base_args = [f"--configure-requires={module}"] + return _run_module_metadata_command(base_args, files, no_index, inc) + +@mcp.tool() +def get_module_test_requires( + module: str, + files: List[Path], + no_index: bool = False, + inc: Optional[List[Path]] = None, +): + """ + Determines the test requirements of a given module. Corresponds to the --test-requires flag. + """ + if not module: + raise ValueError("Module name cannot be empty.") + base_args = [f"--test-requires={module}"] + return _run_module_metadata_command(base_args, files, no_index, inc) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/app/perl-module-metadata_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/app/perl-module-metadata_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7b91b978e4023279cd9aa84c6be2c12a5677292d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/app/perl-module-metadata_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/app/perl-module-metadata_server.py') +SERVER_NAME = 'biosci_perl_module_metadata' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..48a6aede419a5d961268890933fcaabc97b5713d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-module-metadata: + build: . + image: mcp-perl-module-metadata:latest + container_name: mcp-perl-module-metadata + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-module-metadata + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1db954feb1a1ccb1070351d5bbafb5d901b41b03 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-module-metadata + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-metadata/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..36ae1de89a3a46a5207eb1e7126337ea9c0de0dd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-module-runtime-conflicts via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-module-runtime-conflicts -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-module-runtime-conflicts_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-module-runtime-conflicts_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-module-runtime-conflicts_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/app/perl-module-runtime-conflicts_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/app/perl-module-runtime-conflicts_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cb55048b62f96a1f4082a3d2b26acb99c4aeb011 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/app/perl-module-runtime-conflicts_server.py @@ -0,0 +1,89 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, List, Any + +# @mcp.tool() is a placeholder for the actual decorator. +# The user does not want the import statement for mcp. +class mcp: + def tool(func): + return func + +@mcp.tool +def check_module_runtime_conflicts() -> Dict[str, Any]: + """ + Checks for version conflicts related to the Perl module Module::Runtime. + + This tool executes a small Perl script that uses Module::Runtime::Conflicts + to check for known version conflicts with other installed Perl modules. + If conflicts are found, the tool will exit with an error and print details + to stderr. If no conflicts are found, it will report success to stdout. + This functionality is typically used by other tools like 'moose-outdated'. + """ + # The Perl code to execute, based on the module's SYNOPSIS. + # The check_conflicts() function 'dies' (exits with an error) if a conflict is found. + # We wrap it in an eval block to catch the error message and control the output. + perl_script_content = """ + use strict; + use warnings; + use Module::Runtime::Conflicts; + + eval { + Module::Runtime::Conflicts->check_conflicts; + }; + if ($@) { + # The check_conflicts function dies on conflict. + # We catch it, print the error message to STDERR, and exit with an error code. + print STDERR $@; + exit 1; + } + + print "No conflicts found for Module::Runtime.\\n"; + exit 0; + """ + + script_path = None + try: + # Using a temporary file is robust for multi-line scripts. + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".pl", encoding='utf-8') as temp_script: + script_path_str = temp_script.name + temp_script.write(perl_script_content) + + script_path = Path(script_path_str) + command = ["perl", str(script_path)] + command_str = " ".join(command) + + # Execute the perl script + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + # This happens if 'perl' is not in the system's PATH + return { + "command_executed": "perl ", + "stdout": "", + "stderr": "Error: 'perl' executable not found. Please ensure Perl is installed and in your system's PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + # This happens if the script returns a non-zero exit code (i.e., conflicts found) + return { + "command_executed": " ".join(["perl", str(script_path)]) if script_path else "perl ", + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + finally: + # Ensure the temporary file is always cleaned up + if script_path and script_path.exists(): + script_path.unlink() diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/app/perl-module-runtime-conflicts_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/app/perl-module-runtime-conflicts_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..980a51e3bd5b6ba3fed58d5d27a13bf49ac682da --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/app/perl-module-runtime-conflicts_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/app/perl-module-runtime-conflicts_server.py') +SERVER_NAME = 'biosci_perl_module_runtime_conflicts' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4821a20f946b707cfb7ad0b5900028ad713249f5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-module-runtime-conflicts: + build: . + image: mcp-perl-module-runtime-conflicts:latest + container_name: mcp-perl-module-runtime-conflicts + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-module-runtime-conflicts + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..aa0fe5e007443813c16fc0c0a824e7f062e4817d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-module-runtime-conflicts + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime-conflicts/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d293c58ae5adaee852045a01914f241450964afd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-module-runtime via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-module-runtime -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-module-runtime_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-module-runtime_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-module-runtime_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/app/perl-module-runtime_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/app/perl-module-runtime_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ba879bee7a8418bb4628f457287e3fc55595f1d1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/app/perl-module-runtime_server.py @@ -0,0 +1,26 @@ +from typing import Optional, List +import subprocess +from pathlib import Path +import tempfile + +@mcp.tool() +def perl_module_runtime_info(): + """ + This function serves as a placeholder to address the request for 'perl-module-runtime'. + + Please note: 'perl-module-runtime' (Module::Runtime on CPAN) is a Perl *library* + designed for managing module loading at runtime within Perl scripts. It does not + provide any standalone command-line executables or subcommands that can be + directly wrapped as an MCP server tool. + + Therefore, there are no command-line parameters, subcommands, or internal functions + to parse from documentation or execute via subprocess. This function merely + informs about the nature of the specified Perl module. + """ + return { + "command_executed": "No command executed as 'perl-module-runtime' is a Perl library.", + "stdout": "Module::Runtime is a Perl library, not a command-line tool. It does not expose any command-line interface or subcommands to wrap.", + "stderr": "Cannot wrap 'perl-module-runtime' as an MCP tool because it lacks a command-line interface.", + "output_files": [], + "error": "The specified tool 'perl-module-runtime' is a Perl library, not a command-line executable. It does not have any command-line functions to convert into an MCP server tool." + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/app/perl-module-runtime_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/app/perl-module-runtime_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0796bd248d19de7caf17778281f823b141eef481 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/app/perl-module-runtime_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/app/perl-module-runtime_server.py') +SERVER_NAME = 'biosci_perl_module_runtime' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..65e751a2099ab1b714993ff0135d8d012e8fca69 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-module-runtime: + build: . + image: mcp-perl-module-runtime:latest + container_name: mcp-perl-module-runtime + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-module-runtime + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9285fdc54765621f56bebc5df4dc01170f124bb3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-module-runtime + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-module-runtime/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1fe909d9ff33039e1b5d67c1a250d94c66665c94 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-moo via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-moo -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-moo_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-moo_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-moo_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/app/perl-moo_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/app/perl-moo_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ccf31e6e26e96926c8a0cd83ec7d11eed1fe4d92 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/app/perl-moo_server.py @@ -0,0 +1,216 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +@mcp.tool() +def run_perl_script( + program_file: Optional[Path] = None, + program_string: Optional[List[str]] = None, + program_string_with_features: Optional[List[str]] = None, + program_arguments: Optional[List[str]] = None, + record_separator: Optional[str] = None, + autosplit_mode: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + modules_to_use: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + rudimentary_switch_parsing: bool = False, + search_path_for_programfile: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core_after_parsing: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: Optional[str] = None, # Use "" for -V, None for no -V, "variable" for -V:variable + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_perl_line: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> dict: + """ + Executes a Perl script or one-liner using the Perl interpreter. + + This tool provides access to the various command-line switches of the Perl + interpreter, allowing for flexible execution of Perl code. The 'perl-moo' + package is a Perl module, not a standalone executable, and is used within + Perl scripts executed by the 'perl' interpreter. + + Args: + program_file: Path to the Perl program file to execute. + program_string: One or more lines of Perl program code to execute. + Can be specified multiple times via a list. + program_string_with_features: One or more lines of Perl program code, + like `program_string`, but enables all + optional features. Can be specified multiple times. + program_arguments: Arguments to pass to the Perl program. + record_separator: Specify record separator (e.g., '\\0' for null, or an octal value). + autosplit_mode: Enable autosplit mode with -n or -p (splits $_ into @F). + unicode_features: Enables the listed Unicode features (number or list). + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). + debugger: Run program under debugger (optional debugger name). + debugging_flags: Set debugging flags (argument is a bit mask or alphabets). + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. + split_pattern: split() pattern for -a switch (e.g., '/pattern/'). + edit_in_place_extension: Edit <> files in place (makes backup if extension supplied). + include_directories: Specify @INC/#include directory (can be multiple). + line_ending_processing: Enable line ending processing, specifies line terminator (octal). + modules_to_use: Execute "use/no module..." before executing program. + Each string in the list should be the module name (e.g., "Moo") + or a full flag (e.g., "-Mstrict", "-m-warnings"). + loop_around_program: Assume "while (<>) { ... }" loop around program. + loop_and_print: Assume loop like -n but print line also, like sed. + rudimentary_switch_parsing: Enable rudimentary parsing for switches after programfile. + search_path_for_programfile: Look for programfile using PATH environment variable. + tainting_warnings: Enable tainting warnings. + tainting_checks: Enable tainting checks. + dump_core_after_parsing: Dump core after parsing program. + allow_unsafe_operations: Allow unsafe operations. + print_version: Print Perl version, patchlevel and license. + print_config_summary: Print configuration summary. Pass an empty string `""` for `-V` + or a variable name (e.g., `"archname"`) for `-V:archname`. + enable_warnings: Enable many useful warnings. + enable_all_warnings: Enable all warnings. + ignore_text_before_perl_line: Ignore text before #!perl line (optionally cd to directory). + disable_all_warnings: Disable all warnings. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + command = ["perl"] + output_files: List[str] = [] + + # Input validation + if not (program_file or program_string or program_string_with_features or print_version or print_config_summary is not None): + raise ValueError( + "At least one of 'program_file', 'program_string', 'program_string_with_features', " + "'print_version', or 'print_config_summary' must be provided for a meaningful execution." + ) + + if loop_around_program and loop_and_print: + raise ValueError("Options 'loop_around_program' (-n) and 'loop_and_print' (-p) are mutually exclusive.") + + # Build the command list + if record_separator is not None: + command.append(f"-0{record_separator}") + if autosplit_mode: + command.append("-a") + if unicode_features is not None: + command.append(f"-C{unicode_features}") + if check_syntax_only: + command.append("-c") + if debugger is not None: + command.append(f"-d:{debugger}") + if debugging_flags is not None: + command.append(f"-D{debugging_flags}") + if program_string: + for p_str in program_string: + command.extend(["-e", p_str]) + if program_string_with_features: + for p_str in program_string_with_features: + command.extend(["-E", p_str]) + if no_sitecustomize: + command.append("-f") + if split_pattern is not None: + command.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + command.append(f"-i{edit_in_place_extension}") + if include_directories: + for inc_dir in include_directories: + if not inc_dir.is_dir(): + raise ValueError(f"Include directory '{inc_dir}' does not exist or is not a directory.") + command.extend(["-I", str(inc_dir)]) + if line_ending_processing is not None: + command.append(f"-l{line_ending_processing}") + if modules_to_use: + for module in modules_to_use: + # If module string doesn't start with -m or -M, prepend -M by default. + if not module.startswith(("-m", "-M")): + command.append(f"-M{module}") + else: + command.append(module) + if loop_around_program: + command.append("-n") + if loop_and_print: + command.append("-p") + if rudimentary_switch_parsing: + command.append("-s") + if search_path_for_programfile: + command.append("-S") + if tainting_warnings: + command.append("-t") + if tainting_checks: + command.append("-T") + if dump_core_after_parsing: + command.append("-u") + if allow_unsafe_operations: + command.append("-U") + if print_version: + command.append("-v") + if print_config_summary is not None: + command.append(f"-V:{print_config_summary}" if print_config_summary else "-V") + if enable_warnings: + command.append("-w") + if enable_all_warnings: + command.append("-W") + if ignore_text_before_perl_line is not None: + if not ignore_text_before_perl_line.is_dir(): + raise ValueError(f"Directory for -x '{ignore_text_before_perl_line}' does not exist or is not a directory.") + command.append(f"-x{ignore_text_before_perl_line}") + if disable_all_warnings: + command.append("-X") + + # Add program file and its arguments + if program_file: + if not program_file.is_file(): + raise FileNotFoundError(f"Perl program file '{program_file}' not found.") + command.append(str(program_file)) + + if program_arguments: + command.extend(program_arguments) + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + encoding="utf-8" + ) + stdout = process.stdout + stderr = process.stderr + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + except ValueError as e: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": f"Input validation error: {e}", + "output_files": [], + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/app/perl-moo_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/app/perl-moo_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0619f3266b0f8b54e439d29f915d93171466cbe7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/app/perl-moo_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/app/perl-moo_server.py') +SERVER_NAME = 'biosci_perl_moo' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f5eef285b4d280cdfa1ebd00737b062ebd47872b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-moo: + build: . + image: mcp-perl-moo:latest + container_name: mcp-perl-moo + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-moo + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cfde2e7404f7b59df9e9bf83e7ea5b3dcef00f02 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-moo + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moo/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7139289a40a4222e610016961dec2d808edbb423 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-moose via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-moose -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-moose_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-moose_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-moose_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/app/perl-moose_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/app/perl-moose_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5bc93d0dbdb32d68f17b7f1422cd97d8ba964c7e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/app/perl-moose_server.py @@ -0,0 +1,202 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def perl_interpreter( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + execute_program: Optional[List[str]] = None, + execute_program_extended: Optional[List[str]] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + in_place_edit: Optional[str] = None, + include_dirs: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + modules: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + enable_switch_parsing: bool = False, + search_path_for_program: bool = False, + taint_warnings: bool = False, + taint_checks: bool = False, + dump_core: bool = False, + allow_unsafe: bool = False, + print_version: bool = False, + print_config: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + extract_from_text: Optional[str] = None, + disable_all_warnings: bool = False, +) -> Dict[str, Any]: + """ + Executes a script using the Perl interpreter. + + This tool is a wrapper for the `perl` command-line executable. It can run any + Perl script, including those that use modules like Moose. + + Args: + programfile: Path to the Perl program file to execute. + arguments: A list of arguments to pass to the program file. + execute_program: One or more lines of a program passed as a string (-e). + execute_program_extended: Like -e, but enables all optional features (-E). + record_separator: Specify record separator, e.g., '777' for octal (-0). + autosplit: Enable autosplit mode with -n or -p (-a). + unicode_features: Enable listed Unicode features, e.g., 'A' or '8' (-C). + check_syntax_only: Check syntax only; does not execute the program (-c). + debugger: Run program under the specified debugger, e.g., 'Deparse' (-d). + debugging_flags: Set debugging flags, e.g., 'p' or '14' (-D). + no_sitecustomize: Don't run $sitelib/sitecustomize.pl at startup (-f). + split_pattern: Specify the split() pattern for the -a switch (-F). + in_place_edit: Edit files in place. Provide an extension for backups, e.g., '.bak' (-i). + include_dirs: List of directories to add to @INC search path (-I). + line_ending_processing: Enable line ending processing; can specify octal terminator (-l). + modules: List of modules to use/no, e.g., ["-Mstrict", "-mwarnings", "-M-CGI"]. + loop_around_program: Assume a "while (<>) { ... }" loop around the program (-n). + loop_and_print: Like -n, but also prints the line, similar to sed (-p). + enable_switch_parsing: Enable rudimentary parsing for switches after programfile (-s). + search_path_for_program: Look for programfile using the PATH environment variable (-S). + taint_warnings: Enable tainting warnings (-t). + taint_checks: Enable tainting checks (-T). + dump_core: Dump core after parsing the program (-u). + allow_unsafe: Allow unsafe operations (-U). + print_version: Print Perl version, patchlevel, and license (-v). + print_config: Print configuration summary or a single variable, e.g., 'archname' (-V). + enable_warnings: Enable many useful warnings (-w). + enable_all_warnings: Enable all warnings (-W). + extract_from_text: Ignore text before #!perl line; optionally cd to a directory (-x). + disable_all_warnings: Disable all warnings (-X). + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # --- Input Validation --- + source_provided = any([ + programfile, + execute_program, + execute_program_extended, + print_version, + print_config is not None + ]) + if not source_provided: + raise ValueError( + "No program source provided. You must specify 'programfile', " + "'execute_program', 'execute_program_extended', 'print_version', " + "or 'print_config'." + ) + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"The specified program file does not exist: {programfile}") + + if loop_around_program and loop_and_print: + raise ValueError("The flags '-n' (loop_around_program) and '-p' (loop_and_print) are mutually exclusive.") + + warning_flags = [enable_warnings, enable_all_warnings, disable_all_warnings] + if sum(warning_flags) > 1: + raise ValueError("Warning flags '-w' (enable_warnings), '-W' (enable_all_warnings), and '-X' (disable_all_warnings) are mutually exclusive.") + + # --- Command Construction --- + cmd = ["perl"] + + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if debugger is not None: + cmd.append(f"-d:{debugger}" if debugger else "-d") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if in_place_edit is not None: + cmd.append(f"-i{in_place_edit}") + if include_dirs: + for directory in include_dirs: + if not directory.is_dir(): + raise NotADirectoryError(f"Include directory does not exist or is not a directory: {directory}") + cmd.extend(["-I", str(directory)]) + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + if modules: + for mod in modules: + if not (mod.startswith("-M") or mod.startswith("-m")): + raise ValueError(f"Invalid module string '{mod}'. Must start with '-M' or '-m'.") + cmd.extend(modules) + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if enable_switch_parsing: + cmd.append("-s") + if search_path_for_program: + cmd.append("-S") + if taint_warnings: + cmd.append("-t") + if taint_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if allow_unsafe: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config is not None: + cmd.append(f"-V:{print_config}" if print_config else "-V") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if extract_from_text is not None: + cmd.append(f"-x{extract_from_text}") + if disable_all_warnings: + cmd.append("-X") + + if execute_program: + for prog_line in execute_program: + cmd.extend(["-e", prog_line]) + if execute_program_extended: + for prog_line in execute_program_extended: + cmd.extend(["-E", prog_line]) + + if programfile: + cmd.append(str(programfile)) + + if arguments: + cmd.extend(arguments) + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + raise RuntimeError("`perl` command not found. Please ensure Perl is installed and in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed with return code {e.returncode}", + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/app/perl-moose_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/app/perl-moose_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..74908e6e9a92ba777e97c292114aa915ec8d9ef7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/app/perl-moose_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/app/perl-moose_server.py') +SERVER_NAME = 'biosci_perl_moose' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ea5ead0b736ccc6d790844e6bef0d388547d315a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-moose: + build: . + image: mcp-perl-moose:latest + container_name: mcp-perl-moose + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-moose + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1c33b8a778306043ae6cc792b3b0c93f53a5fa74 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-moose + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-moose/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mozilla-ca/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mozilla-ca/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mozilla-ca/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a9c1a25e576ec317ed0888f394d05409825ae60d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-mro-compat via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-mro-compat -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-mro-compat_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-mro-compat_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-mro-compat_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/app/perl-mro-compat_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/app/perl-mro-compat_server.py new file mode 100644 index 0000000000000000000000000000000000000000..31f0e47bdb791995c7e8654f0bf884491a1f4ccb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/app/perl-mro-compat_server.py @@ -0,0 +1,195 @@ +import subprocess +from typing import Optional, List +from pathlib import Path + +@mcp.tool() +def mro_get_linear_isa( + class_name: str, + setup_code: str = "", + mro_type: Optional[str] = None +) -> dict: + """ + Returns the linear inheritance hierarchy (ISA) for a given class using MRO::Compat. + + Args: + class_name: The name of the Perl class to inspect. + setup_code: Optional Perl code to define the class hierarchy (e.g., 'package Parent; package Child; @Child::ISA = ("Parent");'). + mro_type: Optional MRO type to use ('dfs' or 'c3'). If not provided, uses the class's current MRO. + """ + # Construct the Perl script + # We use MRO::Compat to ensure compatibility across Perl versions + mro_call = f"mro::get_linear_isa('{class_name}'" + if mro_type: + if mro_type not in ['dfs', 'c3']: + return {"error": "mro_type must be 'dfs' or 'c3'"} + mro_call += f", '{mro_type}'" + mro_call += ")" + + perl_script = f""" +use MRO::Compat; +{setup_code} +my $linear_isa = {mro_call}; +print join("\\n", @$linear_isa); +""" + + try: + cmd = ["perl", "-e", perl_script] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + isa_list = result.stdout.strip().split("\n") if result.stdout.strip() else [] + + return { + "command_executed": f"perl -MMRO::Compat -e ...", + "class_name": class_name, + "linear_isa": isa_list, + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to execute Perl MRO command", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(e.cmd) + } + +@mcp.tool() +def mro_get_mro( + class_name: str, + setup_code: str = "" +) -> dict: + """ + Returns the current MRO type (dfs or c3) for a given class. + + Args: + class_name: The name of the Perl class to inspect. + setup_code: Optional Perl code to define the class (e.g., 'package MyClass; use mro "c3";'). + """ + perl_script = f""" +use MRO::Compat; +{setup_code} +print mro::get_mro('{class_name}'); +""" + + try: + cmd = ["perl", "-e", perl_script] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": f"perl -MMRO::Compat -e ...", + "class_name": class_name, + "mro_type": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to retrieve MRO type", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def mro_set_mro( + class_name: str, + mro_type: str, + setup_code: str = "" +) -> dict: + """ + Sets the MRO type for a class and verifies the change. + + Args: + class_name: The name of the Perl class to modify. + mro_type: The MRO type to set ('dfs' or 'c3'). + setup_code: Optional Perl code to define the class before setting MRO. + """ + if mro_type not in ['dfs', 'c3']: + return {"error": "mro_type must be 'dfs' or 'c3'"} + + perl_script = f""" +use MRO::Compat; +{setup_code} +mro::set_mro('{class_name}', '{mro_type}'); +print mro::get_mro('{class_name}'); +""" + + try: + cmd = ["perl", "-e", perl_script] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": f"perl -MMRO::Compat -e ...", + "class_name": class_name, + "new_mro_type": result.stdout.strip(), + "success": result.stdout.strip() == mro_type, + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to set MRO type", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def mro_get_is_universal( + class_name: str +) -> dict: + """ + Checks if a class is considered 'UNIVERSAL' in the context of MRO. + + Args: + class_name: The name of the Perl class to check. + """ + perl_script = f""" +use MRO::Compat; +print mro::get_is_universal('{class_name}') ? '1' : '0'; +""" + + try: + cmd = ["perl", "-e", perl_script] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": f"perl -MMRO::Compat -e ...", + "class_name": class_name, + "is_universal": result.stdout.strip() == '1', + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to check universal status", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def mro_compat_version_check() -> dict: + """ + Checks if MRO::Compat is installed and returns the version and Perl environment info. + """ + perl_script = """ +use MRO::Compat; +print "Module Version: " . $MRO::Compat::VERSION . "\\n"; +print "Perl Version: " . $^V . "\\n"; +""" + + try: + cmd = ["perl", "-e", perl_script] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": "perl -MMRO::Compat -e ...", + "installed": True, + "details": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "installed": False, + "error": "MRO::Compat is not installed or perl is not in PATH", + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/app/perl-mro-compat_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/app/perl-mro-compat_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..95b9ab8a74b185ddb11f4d6ebdc1486997d23c46 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/app/perl-mro-compat_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/app/perl-mro-compat_server.py') +SERVER_NAME = 'biosci_perl_mro_compat' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..293c3044a4b1f7d0b3104a0db99718ddaa7844e6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-mro-compat: + build: . + image: mcp-perl-mro-compat:latest + container_name: mcp-perl-mro-compat + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-mro-compat + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2ceaa88a73a3840b140e939b1db2c76946722fc8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-mro-compat + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-mro-compat/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6e8167ea238c1e670b44d45bab39db35e23a4df8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-net-http via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-net-http -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-net-http_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-net-http_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-net-http_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/app/perl-net-http_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/app/perl-net-http_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f4ca28df4d5b830faf241f8205630c561c27f489 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/app/perl-net-http_server.py @@ -0,0 +1,248 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def net_http_request( + host: str, + method: str = "GET", + uri: str = "/", + port: int = 80, + headers: Optional[List[str]] = None, + content: str = "", + keep_alive: bool = False, + send_te: bool = False, + http_version: str = "1.1", + max_line_length: int = 8192, + max_header_lines: int = 128, + laxed: bool = False, +): + """ + Performs a low-level HTTP request using the Net::HTTP Perl module. + This tool covers the lifecycle of a connection: new(), write_request(), + read_response_headers(), and read_entity_body(). + + Args: + host: The target host (e.g., 'www.example.com'). + method: HTTP method (GET, POST, HEAD, etc.). + uri: The request URI path. + port: TCP port to connect to. + headers: List of header strings in "Key: Value" format. + content: The request body content (for POST/PUT). + keep_alive: Whether to request a persistent connection. + send_te: Whether to send the TE header for transfer encodings. + http_version: HTTP version to announce ('1.0' or '1.1'). + max_line_length: Limit on the length of response lines. + max_header_lines: Limit on the number of response headers. + laxed: If True, be more forgiving with non-standard server responses. + """ + # Input validation + if not host: + return {"error": "Host must be specified"} + if http_version not in ["1.0", "1.1"]: + return {"error": "http_version must be '1.0' or '1.1'"} + if not (1 <= port <= 65535): + return {"error": "Port must be between 1 and 65535"} + if max_line_length < 0 or max_header_lines < 0: + return {"error": "Limits must be non-negative"} + + # Prepare headers for Perl + perl_headers = [] + if headers: + for h in headers: + if ":" in h: + k, v = h.split(":", 1) + perl_headers.extend([k.strip(), v.strip()]) + + # Create Perl script + perl_script_content = f""" +use Net::HTTP; +use strict; +use warnings; + +my $s = Net::HTTP->new( + Host => "{host}", + PeerPort => {port}, + KeepAlive => {1 if keep_alive else 0}, + SendTE => {1 if send_te else 0}, + HTTPVersion => "{http_version}", + MaxLineLength => {max_line_length}, + MaxHeaderLines => {max_header_lines} +) or die "Connection failed: $@"; + +my @headers = ({", ".join([f"'{x}'" for x in perl_headers])}); +my $content = q({content}); + +$s->write_request("{method}", "{uri}", @headers, $content) or die "Write failed: $!"; + +my ($code, $mess, %h) = $s->read_response_headers(laxed => {1 if laxed else 0}); + +print "---STATUS---\\n"; +print "$code $mess\\n"; +print "---HEADERS---\\n"; +while (my ($k, $v) = each %h) {{ + print "$k: $v\\n"; +}} +print "---BODY---\\n"; +while (1) {{ + my $buf; + my $n = $s->read_entity_body($buf, 4096); + die "Read failed: $!" unless defined $n; + last unless $n; + print $buf; +}} +""" + + with tempfile.NamedTemporaryFile(suffix=".pl", mode="w", delete=False) as tmp: + tmp.write(perl_script_content) + tmp_path = tmp.name + + try: + cmd = ["perl", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Perl script execution failed" + } + finally: + Path(tmp_path).unlink(missing_ok=True) + +@mcp.tool() +def net_http_format_request( + host: str, + method: str = "GET", + uri: str = "/", + headers: Optional[List[str]] = None, + content: str = "", + keep_alive: bool = False, + http_version: str = "1.1", +): + """ + Formats an HTTP request message and returns it as a string without sending it. + Corresponds to the format_request() method in Net::HTTP. + + Args: + host: The Host header value. + method: HTTP method. + uri: Request URI. + headers: List of "Key: Value" header strings. + content: Request body content. + keep_alive: Whether to include Keep-Alive headers. + http_version: HTTP version ('1.0' or '1.1'). + """ + perl_headers = [] + if headers: + for h in headers: + if ":" in h: + k, v = h.split(":", 1) + perl_headers.extend([k.strip(), v.strip()]) + + perl_script_content = f""" +use Net::HTTP; +my $s = Net::HTTP->new(Host => "{host}", HTTPVersion => "{http_version}", KeepAlive => {1 if keep_alive else 0}, DoNotConnect => 1); +my @headers = ({", ".join([f"'{x}'" for x in perl_headers])}); +print $s->format_request("{method}", "{uri}", @headers, q({content})); +""" + + with tempfile.NamedTemporaryFile(suffix=".pl", mode="w", delete=False) as tmp: + tmp.write(perl_script_content) + tmp_path = tmp.name + + try: + result = subprocess.run(["perl", tmp_path], capture_output=True, text=True, check=True) + return { + "formatted_request": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr} + finally: + Path(tmp_path).unlink(missing_ok=True) + +@mcp.tool() +def net_http_format_chunk(data: str): + """ + Returns the string to be written for a given chunk of data in a chunked transfer. + Corresponds to the format_chunk() method in Net::HTTP. + + Args: + data: The data to be chunked. + """ + perl_script_content = f""" +use Net::HTTP; +my $s = Net::HTTP->new(Host => "localhost", DoNotConnect => 1); +print $s->format_chunk(q({data})); +""" + with tempfile.NamedTemporaryFile(suffix=".pl", mode="w", delete=False) as tmp: + tmp.write(perl_script_content) + tmp_path = tmp.name + + try: + result = subprocess.run(["perl", tmp_path], capture_output=True, text=True, check=True) + return {"chunked_data": result.stdout} + except subprocess.CalledProcessError as e: + return {"error": e.stderr} + finally: + Path(tmp_path).unlink(missing_ok=True) + +@mcp.tool() +def net_http_format_chunk_eof(trailers: Optional[List[str]] = None): + """ + Returns the string to be written for signaling EOF when a Transfer-Encoding of chunked is used. + Corresponds to the format_chunk_eof() method in Net::HTTP. + + Args: + trailers: Optional list of trailer headers in "Key: Value" format. + """ + perl_trailers = [] + if trailers: + for t in trailers: + if ":" in t: + k, v = t.split(":", 1) + perl_trailers.extend([k.strip(), v.strip()]) + + perl_script_content = f""" +use Net::HTTP; +my $s = Net::HTTP->new(Host => "localhost", DoNotConnect => 1); +my @trailers = ({", ".join([f"'{x}'" for x in perl_trailers])}); +print $s->format_chunk_eof(@trailers); +""" + with tempfile.NamedTemporaryFile(suffix=".pl", mode="w", delete=False) as tmp: + tmp.write(perl_script_content) + tmp_path = tmp.name + + try: + result = subprocess.run(["perl", tmp_path], capture_output=True, text=True, check=True) + return {"chunk_eof": result.stdout} + except subprocess.CalledProcessError as e: + return {"error": e.stderr} + finally: + Path(tmp_path).unlink(missing_ok=True) + +@mcp.tool() +def net_http_get_config(): + """ + Returns the configuration summary of the installed Perl environment and Net::HTTP version. + Useful for debugging dependency issues. + """ + try: + perl_v = subprocess.run(["perl", "-v"], capture_output=True, text=True, check=True) + net_http_v = subprocess.run( + ["perl", "-MNet::HTTP", "-e", "print $Net::HTTP::VERSION"], + capture_output=True, text=True, check=True + ) + return { + "perl_version": perl_v.stdout.splitlines()[1] if len(perl_v.stdout.splitlines()) > 1 else perl_v.stdout, + "net_http_version": net_http_v.stdout, + } + except subprocess.CalledProcessError as e: + return {"error": "Could not retrieve configuration", "stderr": e.stderr} \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/app/perl-net-http_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/app/perl-net-http_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ca232df921d648f3fe73ee1320893dc849fc0010 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/app/perl-net-http_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/app/perl-net-http_server.py') +SERVER_NAME = 'biosci_perl_net_http' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f07f5c30b4cc51c212b34b0b50e203b812fe7e7e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-net-http: + build: . + image: mcp-perl-net-http:latest + container_name: mcp-perl-net-http + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-net-http + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6ad4e3530ddbd07d922adf2c273904168581494b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-net-http + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-http/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..205d2551fefa77f450fc2bb61085a34c3e5b8a0b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-net-ssleay via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-net-ssleay -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-net-ssleay_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-net-ssleay_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-net-ssleay_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/app/perl-net-ssleay_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/app/perl-net-ssleay_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0854ad2cf10a394046e32ad818f6f154233135bb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/app/perl-net-ssleay_server.py @@ -0,0 +1,203 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, Literal + +# MCP decorator is assumed to be available in the execution environment. +# No import is needed as per the instructions. + +@mcp.tool() +def ssleay_version( + all_info: bool = False, + build_info: bool = False, + compiler_info: bool = False, + dir_info: bool = False, + engines: bool = False, + features: bool = False, + openssl_version: bool = False, + platform: bool = False, + seeding: bool = False, + build_targets: bool = False, + script_version: bool = False, +): + """ + Retrieves version and build information for the OpenSSL library used by Net::SSLeay. + + This tool wraps the `ssleay-version` command-line utility, which is part of + the perl-net-ssleay package. It provides detailed information about the + underlying OpenSSL library's configuration and capabilities. + + Args: + all_info: Display all available information. + build_info: Display build information. + compiler_info: Display compiler information. + dir_info: Display directory information. + engines: Display available crypto engines. + features: Display OpenSSL features. + openssl_version: Display the OpenSSL version (default action if no flags are given). + platform: Display the platform information. + seeding: Display the pseudo-random number generator seeding strategy. + build_targets: Display build targets. + script_version: Display the version of the ssleay-version script itself. + """ + command = ["ssleay-version"] + + if all_info: + command.append("-a") + if build_info: + command.append("-b") + if compiler_info: + command.append("-c") + if dir_info: + command.append("-d") + if engines: + command.append("-e") + if features: + command.append("-f") + if openssl_version: + command.append("-o") + if platform: + command.append("-p") + if seeding: + command.append("-s") + if build_targets: + command.append("-t") + if script_version: + command.append("-v") + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [] + } + except FileNotFoundError: + err_msg = "ssleay-version not found. Is perl-net-ssleay installed and in the system's PATH?" + logging.error(err_msg) + raise RuntimeError(err_msg) from None + except subprocess.CalledProcessError as e: + logging.error(f"ssleay-version execution failed with exit code {e.returncode}") + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +SSLProtocol = Literal["ssl2", "ssl3", "tls1", "tls1_1", "tls1_2", "dtls1", "dtls1_2"] + +@mcp.tool() +def sslecho( + host_port: str, + cert_file: Optional[Path] = None, + key_file: Optional[Path] = None, + ca_path: Optional[Path] = None, + ca_file: Optional[Path] = None, + verify_level: Optional[int] = None, + verbose: bool = False, + debug: bool = False, + ssl_protocol: Optional[SSLProtocol] = None, +): + """ + A simple SSL/TLS echo client for testing server connections. + + This tool wraps the `sslecho.pl` command-line utility, often included with + the perl-net-ssleay package. It attempts to connect to a specified server, + sends a newline character to test the connection, and then closes. + + Args: + host_port: The target server in 'host:port' format. + cert_file: Path to the client certificate file to use. + key_file: Path to the client private key file to use. + ca_path: Path to a directory containing CA certificates. + ca_file: Path to a file containing CA certificates. + verify_level: The verification level for the server certificate. + verbose: Enable verbose output. + debug: Enable debug output. + ssl_protocol: Specify the SSL/TLS protocol to use. + """ + # Input validation + if ":" not in host_port: + raise ValueError("host_port must be in the format 'host:port'") + + if cert_file and not cert_file.is_file(): + raise FileNotFoundError(f"Certificate file not found: {cert_file}") + + if key_file and not key_file.is_file(): + raise FileNotFoundError(f"Key file not found: {key_file}") + + if ca_path and not ca_path.is_dir(): + raise FileNotFoundError(f"CA path not found or is not a directory: {ca_path}") + + if ca_file and not ca_file.is_file(): + raise FileNotFoundError(f"CA file not found: {ca_file}") + + if verify_level is not None and verify_level < 0: + raise ValueError("verify_level must be a non-negative integer") + + command = ["sslecho.pl"] + + if cert_file: + command.extend(["-cert", str(cert_file)]) + if key_file: + command.extend(["-key", str(key_file)]) + if ca_path: + command.extend(["-CApath", str(ca_path)]) + if ca_file: + command.extend(["-CAfile", str(ca_file)]) + if verify_level is not None: + command.extend(["-verify", str(verify_level)]) + if verbose: + command.append("-v") + if debug: + command.append("-d") + if ssl_protocol: + command.append(f"-{ssl_protocol}") + + command.append(host_port) + + try: + # sslecho.pl is interactive. We send a newline to it via stdin + # to make it perform the echo and then exit. + # A timeout is added to prevent it from hanging indefinitely. + process = subprocess.run( + command, + input="\n", + capture_output=True, + text=True, + check=True, + timeout=30 + ) + return { + "command_executed": " ".join(map(str, command)), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [] + } + except FileNotFoundError: + err_msg = "sslecho.pl not found. Is perl-net-ssleay installed and in the system's PATH?" + logging.error(err_msg) + raise RuntimeError(err_msg) from None + except subprocess.TimeoutExpired as e: + logging.error(f"sslecho.pl timed out after {e.timeout} seconds.") + return { + "command_executed": " ".join(map(str, command)), + "stdout": e.stdout or "", + "stderr": e.stderr or f"Process timed out after {e.timeout} seconds.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + logging.error(f"sslecho.pl execution failed with exit code {e.returncode}") + return { + "command_executed": " ".join(map(str, command)), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/app/perl-net-ssleay_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/app/perl-net-ssleay_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ade81f461575a4f894adc9de3fbeeee3679b302d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/app/perl-net-ssleay_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/app/perl-net-ssleay_server.py') +SERVER_NAME = 'biosci_perl_net_ssleay' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..026978f74ca9b562ee9ff7179c7519a43765b847 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-net-ssleay: + build: . + image: mcp-perl-net-ssleay:latest + container_name: mcp-perl-net-ssleay + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-net-ssleay + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ce0eb93334779385852bdc749a64b534589eec36 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-net-ssleay + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-net-ssleay/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..adc5755b323931e293ddc60e91b9e507a7766683 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-ntlm via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-ntlm -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-ntlm_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-ntlm_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-ntlm_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/app/perl-ntlm_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/app/perl-ntlm_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4f075f3fa68d4bcc84048162ac6e1d84dca8442e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/app/perl-ntlm_server.py @@ -0,0 +1,234 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any, Union + +@mcp.tool() +def run_perl_script( + program_file: Optional[Path] = None, + script_arguments: Optional[List[str]] = None, + record_separator_octal: Optional[str] = None, + autosplit_mode: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + program_lines: Optional[List[str]] = None, + program_lines_extended: Optional[List[str]] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + modules_to_use: Optional[List[str]] = None, + modules_to_no_use: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + rudimentary_switch_parsing: bool = False, + search_path_for_programfile: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core_on_parse_error: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary_variable: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang_dir: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> Dict[str, Any]: + """ + Executes a Perl script or one-liner with various command-line options. + + This function allows running Perl scripts, passing arguments to them, + and configuring the Perl interpreter's behavior using a comprehensive + set of command-line switches. + + Args: + program_file: Path to the Perl script file to execute. + Usually omitted if `program_lines` or `program_lines_extended` are used. + script_arguments: A list of arguments to be passed to the Perl script. + record_separator_octal: Specifies the input record separator. If an empty string is provided, + it corresponds to '-0' (null character). If a string like '123' is + provided, it corresponds to '-0123'. + autosplit_mode: Enables autosplit mode with -n or -p (splits $_ into @F). + unicode_features: Enables the listed Unicode features (number or list). + check_syntax_only: Checks syntax only (runs BEGIN and CHECK blocks). + debugger: Runs the program under the debugger (optional debugger name). + debugging_flags: Sets debugging flags (argument is a bit mask or alphabets). + program_lines: A list of Perl program lines to execute directly from the command line (-e). + Can be specified multiple times. + program_lines_extended: A list of Perl program lines to execute directly from the command line (-E). + Like -e, but enables all optional features. Can be specified multiple times. + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. + split_pattern: The split() pattern for the -a switch (e.g., '/pattern/'). + edit_in_place_extension: Edits <> files in place. If an empty string is provided, + it corresponds to '-i' (no backup). If a string like '.bak' is + provided, it corresponds to '-i.bak' (makes backup). + include_directories: A list of directories to add to @INC/#include path (-I). + Can be specified multiple times. + line_ending_processing: Enables line ending processing, specifies line terminator (octal). + modules_to_use: A list of modules to execute "use module..." before executing the program (-m or -M). + Each string should be the module name, optionally with arguments (e.g., "CGI=:all"). + modules_to_no_use: A list of modules to execute "no module..." before executing the program (-m- or -M-). + Each string should be the module name. + loop_around_program: Assumes "while (<>) { ... }" loop around the program (-n). + loop_and_print: Assumes loop like -n but prints line also, like sed (-p). + rudimentary_switch_parsing: Enables rudimentary parsing for switches after programfile (-s). + search_path_for_programfile: Looks for programfile using PATH environment variable (-S). + tainting_warnings: Enables tainting warnings (-t). + tainting_checks: Enables tainting checks (-T). + dump_core_on_parse_error: Dumps core after parsing program (-u). + allow_unsafe_operations: Allows unsafe operations (-U). + print_version: Prints version, patchlevel and license (-v). + print_config_summary_variable: Prints configuration summary. If an empty string is provided, + it corresponds to '-V' (full summary). If a string like 'archname' + is provided, it corresponds to '-V:archname' (single Config.pm variable). + enable_warnings: Enables many useful warnings (-w). + enable_all_warnings: Enables all warnings (-W). + ignore_text_before_shebang_dir: Ignores text before #!perl line. If Path('.') is provided, + it corresponds to '-x' (current directory). If a specific + directory path is provided, it corresponds to '-x/path/to/dir'. + disable_all_warnings: Disables all warnings (-X). + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + cmd = ["perl"] + output_files: List[Path] = [] + + # Input validation + if program_file: + if not program_file.is_file(): + raise FileNotFoundError(f"Program file not found: {program_file}") + + if program_file and (program_lines or program_lines_extended): + raise ValueError("Cannot specify both a program file and -e/-E program lines.") + + if program_lines and program_lines_extended: + raise ValueError("Cannot specify both -e and -E program lines.") + + # Command construction + if record_separator_octal is not None: + cmd.append(f"-0{record_separator_octal}") + if autosplit_mode: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if debugger is not None: + cmd.append(f"-d:{debugger}") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + + if program_lines: + for line in program_lines: + cmd.extend(["-e", line]) + if program_lines_extended: + for line in program_lines_extended: + cmd.extend(["-E", line]) + + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + cmd.append(f"-i{edit_in_place_extension}") + if include_directories: + for directory in include_directories: + if not directory.is_dir(): + raise NotADirectoryError(f"Include directory not found or is not a directory: {directory}") + cmd.extend(["-I", str(directory)]) + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + + if modules_to_use: + for module in modules_to_use: + # Using -M as it's generally more flexible for module loading + cmd.extend(["-M", module]) + if modules_to_no_use: + for module in modules_to_no_use: + cmd.extend(["-M-", module]) # Using -M- for 'no module;' + + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if rudimentary_switch_parsing: + cmd.append("-s") + if search_path_for_programfile: + cmd.append("-S") + if tainting_warnings: + cmd.append("-t") + if tainting_checks: + cmd.append("-T") + if dump_core_on_parse_error: + cmd.append("-u") + if allow_unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + + if print_config_summary_variable is not None: + if print_config_summary_variable == "": + cmd.append("-V") + else: + cmd.append(f"-V:{print_config_summary_variable}") + + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + + if ignore_text_before_shebang_dir is not None: + if ignore_text_before_shebang_dir == Path("."): + cmd.append("-x") + else: + if not ignore_text_before_shebang_dir.is_dir(): + raise NotADirectoryError(f"Directory for -x not found or is not a directory: {ignore_text_before_shebang_dir}") + cmd.append(f"-x{ignore_text_before_shebang_dir}") + + if disable_all_warnings: + cmd.append("-X") + + # Add program file and its arguments + if program_file: + cmd.append(str(program_file)) + + if script_arguments: + cmd.extend(script_arguments) + + # Execute the command + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout = process.stdout + stderr = process.stderr + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script failed with exit code {e.returncode}: {e.stderr}", + "returncode": e.returncode, + "output_files": output_files, + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "error": "Perl executable not found", + "returncode": 127, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/app/perl-ntlm_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/app/perl-ntlm_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e5dba57763bbcf9640e0ecebba302b62a7bfd64b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/app/perl-ntlm_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/app/perl-ntlm_server.py') +SERVER_NAME = 'biosci_perl_ntlm' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..9eca42968e5b769b6eb2370682c26089243d92fd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-ntlm: + build: . + image: mcp-perl-ntlm:latest + container_name: mcp-perl-ntlm + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-ntlm + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..833bc7abc1c29c2fc552a1551952dd628474b052 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-ntlm + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ntlm/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..29df605dc7a34ea9ee5a61031530e46728f62dfa --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-number-format via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-number-format -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-number-format_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-number-format_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-number-format_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/app/perl-number-format_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/app/perl-number-format_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2c0914ea18812e3bf424a48a3c46ce21b360e8ce --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/app/perl-number-format_server.py @@ -0,0 +1,165 @@ +import subprocess +from typing import Optional, List, Dict, Any +from pathlib import Path + +def _run_perl_format(method: str, *args: Any) -> Dict[str, Any]: + """ + Helper function to execute Number::Format methods via Perl one-liners. + """ + # Construct the Perl script + # We use Number::Format->new() and then call the requested method + # Arguments are passed via @ARGV to ensure safe handling + perl_script = ( + f"use Number::Format; " + f"my $formatter = Number::Format->new(); " + f"print $formatter->{method}(@ARGV);" + ) + + cmd = ["perl", "-MNumber::Format", "-e", perl_script, "--"] + [str(arg) for arg in args] + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "status": "error", + "error_message": f"Perl execution failed: {e.stderr}" + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Perl or Number::Format module not found", + "status": "error", + "error_message": "Ensure perl and Number::Format are installed." + } + +@mcp.tool() +def format_number( + number: float, + precision: int = 2, + trailing_zeros: bool = True +) -> Dict[str, Any]: + """ + Formats a number with a specific precision and grouping separators (commas). + + :param number: The numeric value to format. + :param precision: Number of decimal places. + :param trailing_zeros: Whether to keep trailing zeros. + """ + if precision < 0: + precision = 0 + + # Perl's format_number(number, precision, trailing_zeros) + tz = 1 if trailing_zeros else 0 + return _run_perl_format("format_number", number, precision, tz) + +@mcp.tool() +def format_negative( + number: float, + picture: str = "(-)" +) -> Dict[str, Any]: + """ + Formats a negative number according to a specified format (picture). + + :param number: The numeric value to format. + :param picture: The format string (e.g., '(-)' for parentheses, '-' for prefix). + """ + if number >= 0: + return { + "command_executed": "None", + "stdout": str(number), + "stderr": "Warning: Number is not negative, returning as string.", + "status": "success" + } + + return _run_perl_format("format_negative", picture, number) + +@mcp.tool() +def format_currency( + number: float, + symbol: str = "$", + precision: int = 2 +) -> Dict[str, Any]: + """ + Formats a number as a currency string. + + :param number: The numeric value to format. + :param symbol: The currency symbol to use (e.g., '$', '£'). + :param precision: Number of decimal places. + """ + if precision < 0: + precision = 0 + + # Perl's format_currency(symbol, number, precision) + return _run_perl_format("format_currency", symbol, number, precision) + +@mcp.tool() +def format_bytes( + number: float, + precision: int = 2 +) -> Dict[str, Any]: + """ + Formats a number of bytes into a human-readable string (K, M, G, etc.). + + :param number: The number of bytes. + :param precision: Number of decimal places for the result. + """ + if number < 0: + return {"status": "error", "error_message": "Byte count cannot be negative."} + + return _run_perl_format("format_bytes", number, precision) + +@mcp.tool() +def format_percentage( + number: float, + precision: int = 2 +) -> Dict[str, Any]: + """ + Formats a number as a percentage string. + + :param number: The numeric value (e.g., 0.5 for 50%). + :param precision: Number of decimal places. + """ + return _run_perl_format("format_percentage", number, precision) + +@mcp.tool() +def unformat_number( + formatted_string: str +) -> Dict[str, Any]: + """ + Converts a formatted string back into a raw numeric value. + + :param formatted_string: The string to unformat (e.g., '1,234.56'). + """ + if not formatted_string: + return {"status": "error", "error_message": "Input string is empty."} + + return _run_perl_format("unformat_number", formatted_string) + +@mcp.tool() +def format_price( + number: float, + precision: int = 2 +) -> Dict[str, Any]: + """ + A specialized version of format_number often used for prices, ensuring + standard decimal formatting without currency symbols. + + :param number: The price value. + :param precision: Decimal precision. + """ + return _run_perl_format("format_price", number, precision) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/app/perl-number-format_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/app/perl-number-format_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f87d7c871ecde868a6d6144d3ac9d19454b19013 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/app/perl-number-format_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/app/perl-number-format_server.py') +SERVER_NAME = 'biosci_perl_number_format' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..036a37ebcbf15c297a999072eed8b21930e4035a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-number-format: + build: . + image: mcp-perl-number-format:latest + container_name: mcp-perl-number-format + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-number-format + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e26be88a55360fbcc4792d50f392f6e0445773a0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-number-format + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-number-format/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f9ec26503ae19d0dea8bf9eb2d40b8f0d558a466 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-ole-storage_lite via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-ole-storage_lite -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-ole-storage_lite_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-ole-storage_lite_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-ole-storage_lite_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/app/perl-ole-storage_lite_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/app/perl-ole-storage_lite_server.py new file mode 100644 index 0000000000000000000000000000000000000000..28155771ccba37d8c333138b93574d4e4ab0e280 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/app/perl-ole-storage_lite_server.py @@ -0,0 +1,248 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union +import tempfile +import os + +@mcp.tool() +def run_perl_script( + program_file: Optional[Path] = None, + program_string: Optional[List[str]] = None, + program_string_extended: Optional[List[str]] = None, + program_arguments: Optional[List[str]] = None, + record_separator_octal: Optional[str] = None, + autosplit_mode: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + use_module: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + rudimentary_parsing_switches: bool = False, + look_for_programfile_in_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_perl_line: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> dict: + """ + Executes a Perl script or one-liner using the Perl interpreter, providing access + to its full range of command-line switches. This tool can be used to run Perl + scripts that utilize modules like OLE-Storage_Lite, which is a Perl module + for reading and writing OLE storage files. + + Args: + program_file: Path to the Perl program file to execute. + program_string: One or more lines of Perl program code to execute. + Can be specified multiple times via -e. + program_string_extended: One or more lines of Perl program code to execute, + like -e, but enables all optional features. + Can be specified multiple times via -E. + program_arguments: Arguments to pass to the Perl program. These are passed + after the program file/string. + record_separator_octal: Specify record separator (e.g., '0' for null, '0777' for paragraph mode). + If an empty string is provided, the flag is used without an argument ('-0'). + autosplit_mode: Enable autosplit mode with -n or -p (splits $_ into @F). + unicode_features: Enables the listed Unicode features (e.g., 'all', 'io', 'say'). + If an empty string is provided, the flag is used without an argument ('-C'). + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). + debugger: Run program under debugger. Optionally specify debugger name (e.g., ':ptkdb'). + If an empty string is provided, the flag is used without an argument ('-d'). + debugging_flags: Set debugging flags (argument is a bit mask or alphabets). + If an empty string is provided, the flag is used without an argument ('-D'). + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. + split_pattern: split() pattern for -a switch (e.g., '/\s+/'). '//'s are optional. + If an empty string is provided, the flag is used without an argument ('-F'). + edit_in_place_extension: Edit <> files in place. Makes backup if extension supplied (e.g., '.bak'). + If an empty string is provided, the flag is used without an argument ('-i'). + include_directories: Specify @INC/#include directory. Can be specified multiple times. + line_ending_processing: Enable line ending processing. Optionally specifies line terminator (e.g., '012' for LF). + If an empty string is provided, the flag is used without an argument ('-l'). + use_module: Execute "use/no module..." before executing program. + Format: '[m|M][-]module_name'. 'm' for 'use', 'M' for 'use strict', '-' for 'no'. + Can be specified multiple times. + loop_around_program: Assume "while (<>) { ... }" loop around program. + loop_and_print: Assume loop like -n but print line also, like sed. + rudimentary_parsing_switches: Enable rudimentary parsing for switches after programfile. + look_for_programfile_in_path: Look for programfile using PATH environment variable. + tainting_warnings: Enable tainting warnings. + tainting_checks: Enable tainting checks. + dump_core: Dump core after parsing program. + allow_unsafe_operations: Allow unsafe operations. + print_version: Print version, patchlevel and license. + print_config_summary: Print configuration summary. Optionally specify a single Config.pm variable. + If an empty string is provided, the flag is used without an argument ('-V'). + enable_warnings: Enable many useful warnings. + enable_all_warnings: Enable all warnings. + ignore_text_before_perl_line: Ignore text before #!perl line. Optionally cd to directory. + If Path('.') is provided, the flag is used without a specific directory ('-x'). + disable_all_warnings: Disable all warnings. + """ + command = ["perl"] + output_files: List[Path] = [] + + # Input validation for program_file + if program_file: + if not program_file.is_file(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Program file '{program_file}' does not exist.", + "output_files": [], + } + + # Add switches + if record_separator_octal is not None: + command.append(f"-0{record_separator_octal}") + if autosplit_mode: + command.append("-a") + if unicode_features is not None: + command.append(f"-C{unicode_features}") + if check_syntax_only: + command.append("-c") + if debugger is not None: + command.append(f"-d{debugger}") + if debugging_flags is not None: + command.append(f"-D{debugging_flags}") + if program_string: + for p_str in program_string: + command.extend(["-e", p_str]) + if program_string_extended: + for p_str_ext in program_string_extended: + command.extend(["-E", p_str_ext]) + if no_sitecustomize: + command.append("-f") + if split_pattern is not None: + command.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + command.append(f"-i{edit_in_place_extension}") + if include_directories: + for inc_dir in include_directories: + if not inc_dir.is_dir(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Include directory '{inc_dir}' does not exist or is not a directory.", + "output_files": [], + } + command.extend(["-I", str(inc_dir)]) + if line_ending_processing is not None: + command.append(f"-l{line_ending_processing}") + if use_module: + for module_spec in use_module: + # Basic validation for module_spec format + if not (module_spec.startswith('m') or module_spec.startswith('M') or module_spec.startswith('-')): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Invalid module specification '{module_spec}'. Must start with 'm', 'M', or '-'.", + "output_files": [], + } + command.append(f"-{module_spec}") + if loop_around_program: + command.append("-n") + if loop_and_print: + command.append("-p") + if rudimentary_parsing_switches: + command.append("-s") + if look_for_programfile_in_path: + command.append("-S") + if tainting_warnings: + command.append("-t") + if tainting_checks: + command.append("-T") + if dump_core: + command.append("-u") + if allow_unsafe_operations: + command.append("-U") + if print_version: + command.append("-v") + if print_config_summary is not None: + command.append(f"-V:{print_config_summary}") + if enable_warnings: + command.append("-w") + if enable_all_warnings: + command.append("-W") + if ignore_text_before_perl_line is not None: + # If Path('.') is passed, it means -x without a specific directory argument. + # Otherwise, validate the directory. + if str(ignore_text_before_perl_line) != ".": + if not ignore_text_before_perl_line.is_dir(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Directory for -x '{ignore_text_before_perl_line}' does not exist or is not a directory.", + "output_files": [], + } + command.append(f"-x{ignore_text_before_perl_line}") + if disable_all_warnings: + command.append("-X") + + # Add program file and arguments + if program_file: + command.append(str(program_file)) + if program_arguments: + command.extend(program_arguments) + + # If no program file or string is provided, and no version/config info is requested, + # Perl will just wait for input or exit. This might not be the intended use. + # This check ensures that at least some action is specified for the Perl interpreter. + if len(command) == 1 and not (print_version or print_config_summary is not None or check_syntax_only): + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: No Perl program file, program string, or informational flag (-v, -V, -c) provided. " + "The 'perl' command would run without arguments, potentially waiting for STDIN.", + "output_files": [], + } + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding="utf-8" + ) + stdout = process.stdout + stderr = process.stderr + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "output_files": [], + } + except Exception as e: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": f"An unexpected error occurred: {str(e)}", + "output_files": [], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/app/perl-ole-storage_lite_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/app/perl-ole-storage_lite_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b5708c17ddbc17c222a869157881b6ac82b769a7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/app/perl-ole-storage_lite_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/app/perl-ole-storage_lite_server.py') +SERVER_NAME = 'biosci_perl_ole_storage_lite' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..aedb207f7bc7a93da7b717ea41778d9fd3b49f79 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-ole-storage_lite: + build: . + image: mcp-perl-ole-storage_lite:latest + container_name: mcp-perl-ole-storage_lite + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-ole-storage_lite + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8bd5d5a0e7ea9b8cd5f819aa5d89d9c6f067bd77 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-ole-storage_lite + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-ole-storage_lite/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3af430154bf05a30b6074467f39f82a6574f3da4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-package-deprecationmanager via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-package-deprecationmanager -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-package-deprecationmanager_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-package-deprecationmanager_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-package-deprecationmanager_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/app/perl-package-deprecationmanager_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/app/perl-package-deprecationmanager_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5fb77f9dcc29ace8974ed8c1a7223174887063bc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/app/perl-package-deprecationmanager_server.py @@ -0,0 +1,32 @@ +import subprocess +from typing import Dict + +# @mcp.tool() +def package_deprecationmanager_info() -> Dict[str, str]: + """ + Provides information about the perl-package-deprecationmanager library. + + This package is a Perl library and not a command-line tool. It is intended + to be used by developers within their Perl code to manage deprecation + warnings for their distributions. As it has no executable or command-line + interface, this function returns informational text instead of executing a + command. + """ + + # This is a library, so there is no command to execute. + # The return structure is provided for consistency with the MCP framework. + command_executed = "N/A (This is a Perl library, not an executable)" + + stdout_message = ( + "Tool 'perl-package-deprecationmanager' is a Perl library for managing " + "deprecation warnings within Perl code. It does not have a command-line " + "interface and cannot be executed directly. To use it, you must 'use' " + "it in your own Perl scripts." + ) + + return { + "command_executed": command_executed, + "stdout": stdout_message, + "stderr": "", + "output_files": [] + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/app/perl-package-deprecationmanager_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/app/perl-package-deprecationmanager_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8fcf7e41bcb48949c83360d770c6666f1ac18cf4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/app/perl-package-deprecationmanager_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/app/perl-package-deprecationmanager_server.py') +SERVER_NAME = 'biosci_perl_package_deprecationmanager' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5616a754b3976e3ef2db624966a6da968a7e9483 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-package-deprecationmanager: + build: . + image: mcp-perl-package-deprecationmanager:latest + container_name: mcp-perl-package-deprecationmanager + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-package-deprecationmanager + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..869a174516e040f5a6c0d0ce1f52b79dfbe21736 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-package-deprecationmanager + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-deprecationmanager/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..85a2acc966d94d28fcb5484238c0b57e3021d170 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-package-stash-xs via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-package-stash-xs -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-package-stash-xs_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-package-stash-xs_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-package-stash-xs_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/app/perl-package-stash-xs_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/app/perl-package-stash-xs_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b3b5ba2b9850360bf137444a77ecd640f585afec --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/app/perl-package-stash-xs_server.py @@ -0,0 +1,313 @@ +import subprocess +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def package_stash_get_info( + perl5lib: Optional[str] = None +) -> Dict[str, Any]: + """ + Returns information about the Package::Stash environment, confirming if the + XS (accelerated) version is active and which version is installed. + + Args: + perl5lib: Optional path to add to PERL5LIB for finding modules. + """ + env = os.environ.copy() + if perl5lib: + path_obj = Path(perl5lib) + if path_obj.exists(): + env["PERL5LIB"] = str(path_obj.absolute()) + (os.pathsep + env.get("PERL5LIB", "") if env.get("PERL5LIB") else "") + + perl_code = ( + "use Package::Stash; " + "print \"Implementation: $Package::Stash::IMPLEMENTATION\\n\"; " + "eval { require Package::Stash::XS; print \"XS_Version: $Package::Stash::XS::VERSION\\n\"; }; " + "print \"Stash_Version: $Package::Stash::VERSION\\n\";" + ) + + cmd = ["perl", "-e", perl_code] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True, env=env) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "error": f"Failed to retrieve Package::Stash info: {e.stderr}", + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def package_stash_list_symbols( + package_name: str, + perl5lib: Optional[str] = None +) -> Dict[str, Any]: + """ + Lists all symbols defined in a specific Perl package namespace. + Useful for inspecting the contents of bioinformatics modules (e.g., Bio::Seq). + + Args: + package_name: The name of the Perl package to inspect (e.g., 'Package::Stash'). + perl5lib: Optional path to add to PERL5LIB for finding modules. + """ + if not package_name: + raise ValueError("package_name is required") + + env = os.environ.copy() + if perl5lib: + path_obj = Path(perl5lib) + if path_obj.exists(): + env["PERL5LIB"] = str(path_obj.absolute()) + (os.pathsep + env.get("PERL5LIB", "") if env.get("PERL5LIB") else "") + + # Perl script to load the package and list symbols + perl_code = ( + "use Package::Stash; " + "my $pkg = $ARGV[0]; " + "eval \"require $pkg\" or die \"Could not load package $pkg: $@\"; " + "my $s = Package::Stash->new($pkg); " + "print \"$_\n\" for sort $s->list_all_symbols;" + ) + + cmd = ["perl", "-e", perl_code, "--", package_name] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True, env=env) + symbols = result.stdout.strip().split("\n") if result.stdout.strip() else [] + return { + "command_executed": " ".join(cmd), + "package": package_name, + "symbols": symbols, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "error": f"Failed to list symbols for {package_name}: {e.stderr}", + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def package_stash_has_symbol( + package_name: str, + symbol_name: str, + perl5lib: Optional[str] = None +) -> Dict[str, Any]: + """ + Checks if a specific symbol exists in a Perl package's namespace. + + Args: + package_name: The name of the Perl package. + symbol_name: The name of the symbol to check (e.g., 'new' or '$VERSION'). + perl5lib: Optional path to add to PERL5LIB. + """ + if not package_name or not symbol_name: + raise ValueError("Both package_name and symbol_name are required") + + env = os.environ.copy() + if perl5lib: + path_obj = Path(perl5lib) + if path_obj.exists(): + env["PERL5LIB"] = str(path_obj.absolute()) + (os.pathsep + env.get("PERL5LIB", "") if env.get("PERL5LIB") else "") + + perl_code = ( + "use Package::Stash; " + "my ($pkg, $sym) = @ARGV; " + "eval \"require $pkg\"; " + "my $s = Package::Stash->new($pkg); " + "if ($s->has_symbol($sym)) { print \"EXISTS\"; exit 0; } " + "else { print \"NOT_FOUND\"; exit 1; }" + ) + + cmd = ["perl", "-e", perl_code, "--", package_name, symbol_name] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, env=env) + exists = result.stdout.strip() == "EXISTS" + return { + "command_executed": " ".join(cmd), + "package": package_name, + "symbol": symbol_name, + "exists": exists, + "stdout": result.stdout, + "stderr": result.stderr + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def package_stash_get_symbols_by_type( + package_name: str, + symbol_type: str = "code", + perl5lib: Optional[str] = None +) -> Dict[str, Any]: + """ + Returns all symbols of a specific type from a Perl package. + + Args: + package_name: The name of the Perl package. + symbol_type: The type of symbols to list. Must be one of: 'scalar', 'array', 'hash', 'code', 'io'. + perl5lib: Optional path to add to PERL5LIB. + """ + valid_types = ["scalar", "array", "hash", "code", "io"] + if symbol_type not in valid_types: + raise ValueError(f"symbol_type must be one of {valid_types}") + + env = os.environ.copy() + if perl5lib: + path_obj = Path(perl5lib) + if path_obj.exists(): + env["PERL5LIB"] = str(path_obj.absolute()) + (os.pathsep + env.get("PERL5LIB", "") if env.get("PERL5LIB") else "") + + perl_code = ( + "use Package::Stash; " + "my ($pkg, $type) = @ARGV; " + "eval \"require $pkg\"; " + "my $s = Package::Stash->new($pkg); " + "my $syms = $s->get_all_symbols($type); " + "print \"$_\n\" for sort keys %$syms;" + ) + + cmd = ["perl", "-e", perl_code, "--", package_name, symbol_type] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True, env=env) + symbols = result.stdout.strip().split("\n") if result.stdout.strip() else [] + return { + "command_executed": " ".join(cmd), + "package": package_name, + "type": symbol_type, + "symbols": symbols, + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": f"Failed to get symbols by type: {e.stderr}", + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def package_stash_remove_symbol( + package_name: str, + symbol_name: str, + perl5lib: Optional[str] = None +) -> Dict[str, Any]: + """ + Removes a symbol from a Perl package's symbol table. + Warning: This modifies the Perl environment for the duration of the execution. + + Args: + package_name: The name of the Perl package. + symbol_name: The name of the symbol to remove. + perl5lib: Optional path to add to PERL5LIB. + """ + if not package_name or not symbol_name: + raise ValueError("Both package_name and symbol_name are required") + + env = os.environ.copy() + if perl5lib: + path_obj = Path(perl5lib) + if path_obj.exists(): + env["PERL5LIB"] = str(path_obj.absolute()) + (os.pathsep + env.get("PERL5LIB", "") if env.get("PERL5LIB") else "") + + perl_code = ( + "use Package::Stash; " + "my ($pkg, $sym) = @ARGV; " + "eval \"require $pkg\"; " + "my $s = Package::Stash->new($pkg); " + "if ($s->has_symbol($sym)) { " + " $s->remove_symbol($sym); " + " print \"REMOVED\"; " + "} else { " + " print \"NOT_FOUND\"; " + "}" + ) + + cmd = ["perl", "-e", perl_code, "--", package_name, symbol_name] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True, env=env) + return { + "command_executed": " ".join(cmd), + "package": package_name, + "symbol": symbol_name, + "status": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": f"Failed to remove symbol: {e.stderr}", + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def package_stash_add_scalar_symbol( + package_name: str, + symbol_name: str, + value: str, + perl5lib: Optional[str] = None +) -> Dict[str, Any]: + """ + Adds a scalar symbol with a specific string value to a Perl package. + + Args: + package_name: The name of the Perl package. + symbol_name: The name of the symbol (without the $ prefix). + value: The string value to assign to the scalar. + perl5lib: Optional path to add to PERL5LIB. + """ + if not package_name or not symbol_name: + raise ValueError("Both package_name and symbol_name are required") + + env = os.environ.copy() + if perl5lib: + path_obj = Path(perl5lib) + if path_obj.exists(): + env["PERL5LIB"] = str(path_obj.absolute()) + (os.pathsep + env.get("PERL5LIB", "") if env.get("PERL5LIB") else "") + + perl_code = ( + "use Package::Stash; " + "my ($pkg, $sym, $val) = @ARGV; " + "eval \"require $pkg\"; " + "my $s = Package::Stash->new($pkg); " + "my $val_ref = \\$val; " + "$s->add_symbol('$' . $sym, $val_ref); " + "print \"ADDED\";" + ) + + cmd = ["perl", "-e", perl_code, "--", package_name, symbol_name, value] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True, env=env) + return { + "command_executed": " ".join(cmd), + "package": package_name, + "symbol": f"${symbol_name}", + "value": value, + "status": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": f"Failed to add symbol: {e.stderr}", + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/app/perl-package-stash-xs_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/app/perl-package-stash-xs_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c2f2ef3e30ed8ff1722666147afe33d9b3e9bc94 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/app/perl-package-stash-xs_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/app/perl-package-stash-xs_server.py') +SERVER_NAME = 'biosci_perl_package_stash_xs' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..21642a14637eb07d1c47c856e203a8ae3e0fc3b1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-package-stash-xs: + build: . + image: mcp-perl-package-stash-xs:latest + container_name: mcp-perl-package-stash-xs + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-package-stash-xs + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6b84cf6c15be775363ebf5bab1746f8846367866 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-package-stash-xs + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash-xs/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..264d141116a7b7056eeff9484d8e3f4a11c542f9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-package-stash via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-package-stash -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-package-stash_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-package-stash_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-package-stash_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/app/perl-package-stash_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/app/perl-package-stash_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b1bec45f700403aee67e5a7ddc9076a8e2bc99fd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/app/perl-package-stash_server.py @@ -0,0 +1,368 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +# Helper function to build command arguments for perl_execute_script +def _build_perl_run_command( + program_file: Optional[Path], + program_one_liner: Optional[List[str]], + program_one_liner_extended: Optional[List[str]], + script_arguments: Optional[List[str]], + record_separator_octal: Optional[str], + autosplit: bool, + unicode_features: Optional[str], + check_syntax_only: bool, + debugger: Optional[str], + debug_flags: Optional[str], + no_sitecustomize: bool, + split_pattern: Optional[str], + in_place_edit_extension: Optional[str], + include_directories: Optional[List[Path]], + line_terminator_octal: Optional[str], + use_modules: Optional[List[str]], + no_modules: Optional[List[str]], + loop_input: bool, + loop_input_and_print: bool, + parse_switches_after_program: bool, + search_path_for_program: bool, + taint_warnings: bool, + taint_checks: bool, + dump_core: bool, + allow_unsafe: bool, + enable_warnings: bool, + enable_all_warnings: bool, + ignore_shebang_text: bool, + change_directory_for_shebang: Optional[Path], + disable_all_warnings: bool, +) -> List[str]: + """ + Constructs the command list for executing a Perl script or one-liner. + Performs basic validation for file/directory existence. + """ + cmd = ["perl"] + + if record_separator_octal is not None: + cmd.append(f"-0{record_separator_octal}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if debugger is not None: + cmd.append(f"-d:{debugger}") + if debug_flags is not None: + cmd.append(f"-D{debug_flags}") + if program_one_liner: + for p in program_one_liner: + cmd.extend(["-e", p]) + if program_one_liner_extended: + for p in program_one_liner_extended: + cmd.extend(["-E", p]) + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if in_place_edit_extension is not None: + cmd.append(f"-i{in_place_edit_extension}") + if include_directories: + for d in include_directories: + if not d.is_dir(): + raise ValueError(f"Include directory '{d}' does not exist or is not a directory.") + cmd.extend(["-I", str(d)]) + if line_terminator_octal is not None: + cmd.append(f"-l{line_terminator_octal}") + if use_modules: + for m in use_modules: + cmd.extend(["-M", m]) # Using -M as it's more general for 'use module' + if no_modules: + for m in no_modules: + cmd.extend(["-M-", m]) # Using -M- for 'no module' + if loop_input: + cmd.append("-n") + if loop_input_and_print: + cmd.append("-p") + if parse_switches_after_program: + cmd.append("-s") + if search_path_for_program: + cmd.append("-S") + if taint_warnings: + cmd.append("-t") + if taint_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if allow_unsafe: + cmd.append("-U") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if disable_all_warnings: + cmd.append("-X") + if ignore_shebang_text: + if change_directory_for_shebang: + if not change_directory_for_shebang.is_dir(): + raise ValueError(f"Directory for -x '{change_directory_for_shebang}' does not exist or is not a directory.") + cmd.append(f"-x{change_directory_for_shebang}") + else: + cmd.append("-x") + + if program_file: + if not program_file.is_file(): + raise FileNotFoundError(f"Program file '{program_file}' not found.") + cmd.append(str(program_file)) + + if script_arguments: + cmd.extend(script_arguments) + + return cmd + + +@mcp.tool() +def perl_execute_script( + program_file: Optional[Path] = None, + program_one_liner: Optional[List[str]] = None, + program_one_liner_extended: Optional[List[str]] = None, + script_arguments: Optional[List[str]] = None, + record_separator_octal: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debug_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + in_place_edit_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_terminator_octal: Optional[str] = None, + use_modules: Optional[List[str]] = None, + no_modules: Optional[List[str]] = None, + loop_input: bool = False, + loop_input_and_print: bool = False, + parse_switches_after_program: bool = False, + search_path_for_program: bool = False, + taint_warnings: bool = False, + taint_checks: bool = False, + dump_core: bool = False, + allow_unsafe: bool = False, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_shebang_text: bool = False, + change_directory_for_shebang: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> Dict[str, Any]: + """ + Executes a Perl script or one-liner with various Perl interpreter options. + + This function wraps the 'perl' interpreter, allowing users to run Perl scripts + or execute one-liners with fine-grained control over Perl's execution environment. + It supports all switches available via 'perl -h'. + + Args: + program_file: Path to the Perl script to execute. Required if no one-liner is provided. + program_one_liner: One or more Perl code lines to execute via '-e'. Can be used multiple times. + program_one_liner_extended: One or more Perl code lines to execute via '-E', enabling all optional features. + Can be used multiple times. + script_arguments: Arguments to pass to the Perl script. + record_separator_octal: Specify the input record separator (e.g., '0' for NUL, or an octal value). + If empty string, defaults to '\0'. + autosplit: Enable autosplit mode with -n or -p (splits $_ into @F). + unicode_features: Enables the listed Unicode features (e.g., 'a' for all, 'S' for script_run). + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks), does not execute the main program. + debugger: Run program under the specified debugger (e.g., 'ptkdb'). + debug_flags: Set debugging flags (argument is a bit mask or alphabets). + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. + split_pattern: Pattern for split() when using -a switch (e.g., '/\s+/'). + in_place_edit_extension: Edit <> files in place. If an extension is supplied (e.g., '.bak'), + makes a backup of the original file. If empty string, no backup. + include_directories: Specify directories to add to @INC for module searching. + line_terminator_octal: Enable line ending processing, specifies line terminator (e.g., '0' for NUL). + If empty string, uses system default. + use_modules: List of modules to 'use' before executing the program (e.g., 'strict', 'warnings'). + Corresponds to '-Mmodule'. + no_modules: List of modules to 'no' before executing the program (e.g., 'strict'). + Corresponds to '-M-module'. + loop_input: Assume "while (<>) { ... }" loop around program. + loop_input_and_print: Assume loop like -n but print line also, like sed. + parse_switches_after_program: Enable rudimentary parsing for switches after programfile. + search_path_for_program: Look for program_file using PATH environment variable. + taint_warnings: Enable tainting warnings. + taint_checks: Enable tainting checks. + dump_core: Dump core after parsing program. + allow_unsafe: Allow unsafe operations. + enable_warnings: Enable many useful warnings (-w). + enable_all_warnings: Enable all warnings (-W). + ignore_shebang_text: Ignore text before #!perl line. + change_directory_for_shebang: Optionally change to this directory before processing -x. + disable_all_warnings: Disable all warnings (-X). + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + # Input validation + if not program_file and not (program_one_liner or program_one_liner_extended): + raise ValueError("Either 'program_file' or at least one of 'program_one_liner' or 'program_one_liner_extended' must be provided.") + + if loop_input and loop_input_and_print: + raise ValueError("Options 'loop_input' (-n) and 'loop_input_and_print' (-p) are mutually exclusive.") + + warning_options_count = sum([enable_warnings, enable_all_warnings, disable_all_warnings]) + if warning_options_count > 1: + raise ValueError("Only one of 'enable_warnings' (-w), 'enable_all_warnings' (-W), or 'disable_all_warnings' (-X) can be true.") + + if split_pattern is not None and not autosplit: + raise ValueError("If 'split_pattern' (-F) is specified, 'autosplit' (-a) must be enabled.") + + if change_directory_for_shebang and not ignore_shebang_text: + raise ValueError("If 'change_directory_for_shebang' (-x directory) is specified, 'ignore_shebang_text' (-x) must be enabled.") + + command = _build_perl_run_command( + program_file=program_file, + program_one_liner=program_one_liner, + program_one_liner_extended=program_one_liner_extended, + script_arguments=script_arguments, + record_separator_octal=record_separator_octal, + autosplit=autosplit, + unicode_features=unicode_features, + check_syntax_only=check_syntax_only, + debugger=debugger, + debug_flags=debug_flags, + no_sitecustomize=no_sitecustomize, + split_pattern=split_pattern, + in_place_edit_extension=in_place_edit_extension, + include_directories=include_directories, + line_terminator_octal=line_terminator_octal, + use_modules=use_modules, + no_modules=no_modules, + loop_input=loop_input, + loop_input_and_print=loop_input_and_print, + parse_switches_after_program=parse_switches_after_program, + search_path_for_program=search_path_for_program, + taint_warnings=taint_warnings, + taint_checks=taint_checks, + dump_core=dump_core, + allow_unsafe=allow_unsafe, + enable_warnings=enable_warnings, + enable_all_warnings=enable_all_warnings, + ignore_shebang_text=ignore_shebang_text, + change_directory_for_shebang=change_directory_for_shebang, + disable_all_warnings=disable_all_warnings, + ) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [], # Perl scripts can produce arbitrary output files, not easily captured generically. + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + + +@mcp.tool() +def perl_get_version() -> Dict[str, Any]: + """ + Prints the Perl version, patchlevel, and license information. + Corresponds to 'perl -v'. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + command = ["perl", "-v"] + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + + +@mcp.tool() +def perl_get_config( + variable: Optional[str] = None, +) -> Dict[str, Any]: + """ + Prints a summary of Perl's configuration or a single Config.pm variable. + Corresponds to 'perl -V[:variable]'. + + Args: + variable: Optional. The name of a Config.pm variable to print (e.g., 'archname', 'version'). + If not provided, prints a full configuration summary. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + command = ["perl"] + if variable: + command.append(f"-V:{variable}") + else: + command.append("-V") + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/app/perl-package-stash_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/app/perl-package-stash_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3b57054bd62d8a1188b1c5ec4595f3dff49a076c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/app/perl-package-stash_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/app/perl-package-stash_server.py') +SERVER_NAME = 'biosci_perl_package_stash' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7f605a30c1e6ea9440e97667f4e9b3b227870d37 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-package-stash: + build: . + image: mcp-perl-package-stash:latest + container_name: mcp-perl-package-stash + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-package-stash + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..58d3d17b26722288c2caf665aa54a2e6d743ccc1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-package-stash + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-package-stash/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7654038728e5f0be492ce345181d63b954bf2e77 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-parallel-forkmanager via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-parallel-forkmanager -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-parallel-forkmanager_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-parallel-forkmanager_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-parallel-forkmanager_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/app/perl-parallel-forkmanager_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/app/perl-parallel-forkmanager_server.py new file mode 100644 index 0000000000000000000000000000000000000000..03da96a68d92fc3b17ab482d8f9d7610c92f3e45 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/app/perl-parallel-forkmanager_server.py @@ -0,0 +1,141 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + + +@mcp.tool() +def run_perl_script( + program_file: Optional[Path] = None, + program_string: Optional[str] = None, + arguments: Optional[List[str]] = None, + use_modern_features_for_string: bool = False, + search_path_for_script: bool = False, + check_syntax_only: bool = False, + include_directories: Optional[List[Path]] = None, + use_modules: Optional[List[str]] = None, + no_modules: Optional[List[str]] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + enable_tainting_checks: bool = False, +) -> dict: + """ + Executes a Perl script, designed for use with modules like Parallel::ForkManager. + + This tool is a wrapper around the Perl interpreter (`perl`). It allows you to run + a Perl script from a file (`program_file`) or a string (`program_string`), and pass + various command-line options to the interpreter. It is created in the context of the + `perl-parallel-forkmanager` package, assuming that scripts may leverage this module + for parallel processing. + + Args: + program_file: Path to the Perl script to execute. + program_string: A string containing a Perl program to execute (one-liner). + arguments: A list of arguments to pass to the Perl script. + use_modern_features_for_string: If true, uses '-E' to enable all optional features + for the `program_string`. Defaults to False, using '-e'. + search_path_for_script: If true, uses '-S' to search for the `program_file` in the system's PATH. + check_syntax_only: If true, uses '-c' to check the script's syntax without running it. + include_directories: A list of directories to add to Perl's module search path (@INC). Corresponds to the '-I' flag. + use_modules: A list of modules to load before executing the script. Corresponds to the '-M' flag. + no_modules: A list of modules to disable before executing the script. Corresponds to the '-m' flag. + enable_warnings: If true, enables many useful warnings ('-w'). + enable_all_warnings: If true, enables all warnings ('-W'). + disable_all_warnings: If true, disables all warnings ('-X'). + enable_tainting_checks: If true, enables taint checking ('-T'). + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # 1. Input Validation + if not (program_file or program_string): + raise ValueError("Either 'program_file' or 'program_string' must be provided.") + if program_file and program_string: + raise ValueError("Cannot provide both 'program_file' and 'program_string'.") + + if program_file and not search_path_for_script: + if not program_file.is_file(): + raise FileNotFoundError(f"Program file not found: {program_file}") + + if include_directories: + for directory in include_directories: + if not directory.is_dir(): + raise NotADirectoryError(f"Include directory not found: {directory}") + + # 2. Command Construction + cmd = ["perl"] + + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if disable_all_warnings: + cmd.append("-X") + if check_syntax_only: + cmd.append("-c") + if enable_tainting_checks: + cmd.append("-T") + if search_path_for_script: + cmd.append("-S") + + if include_directories: + for directory in include_directories: + cmd.extend(["-I", str(directory)]) + if use_modules: + for module in use_modules: + cmd.extend(["-M", module]) + if no_modules: + for module in no_modules: + cmd.extend(["-m", module]) + + # 3. Handle script source + if program_string: + if use_modern_features_for_string: + cmd.append("-E") + else: + cmd.append("-e") + cmd.append(program_string) + elif program_file: + cmd.append(str(program_file)) + + # 4. Add script arguments + if arguments: + cmd.extend(arguments) + + command_str = " ".join(map(str, cmd)) # Ensure all parts are strings for join + + # 5. Execute command + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + # This error is raised if 'perl' is not found in the system's PATH + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: 'perl' executable not found. Is Perl installed and in your PATH?", + "output_files": [] + } + except subprocess.CalledProcessError as e: + # This handles cases where the perl script exits with a non-zero status + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # 6. Return structured output + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": [] # The wrapper itself doesn't know about output files; the user's script creates them. + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/app/perl-parallel-forkmanager_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/app/perl-parallel-forkmanager_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c57e02908de356da024e338f0ee5ff3035e7d71a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/app/perl-parallel-forkmanager_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/app/perl-parallel-forkmanager_server.py') +SERVER_NAME = 'biosci_perl_parallel_forkmanager' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c09f26c8d5084fcdd306e2c24bf9b0c507c103bc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-parallel-forkmanager: + build: . + image: mcp-perl-parallel-forkmanager:latest + container_name: mcp-perl-parallel-forkmanager + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-parallel-forkmanager + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..01bf6a8e0712f60b08e43de40ea2416d58a7c051 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-parallel-forkmanager + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parallel-forkmanager/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..10a6cb4c0f30f2e1692b275a7c1c948ef9054973 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-params-check via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-params-check -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-params-check_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-params-check_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-params-check_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/app/perl-params-check_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/app/perl-params-check_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f60d7165d1bc7181ebe5abca2ec4ee522c01a1e4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/app/perl-params-check_server.py @@ -0,0 +1,206 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# This is a mock decorator. In a real MCP environment, this would be provided by the MCP framework. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +@mcp.tool() +def run_perl( + programfile: Optional[Path] = None, + execute_program: Optional[List[str]] = None, + execute_program_extended: Optional[List[str]] = None, + arguments: Optional[List[str]] = None, + check_syntax_only: bool = False, + run_under_debugger: Optional[str] = None, + dump_core: bool = False, + allow_unsafe: bool = False, + no_sitecustomize: bool = False, + search_path: bool = False, + ignore_pre_hashbang_text: Optional[Path] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + split_pattern: Optional[str] = None, + line_ending_processing: Optional[str] = None, + in_place_edit: Optional[str] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + include_directory: Optional[List[Path]] = None, + use_module: Optional[List[str]] = None, + use_module_no_import: Optional[List[str]] = None, + no_module: Optional[List[str]] = None, + no_module_no_import: Optional[List[str]] = None, + print_version: bool = False, + print_config: Optional[str] = None, + unicode_features: Optional[str] = None, + debugging_flags: Optional[str] = None, + parse_switches: bool = False, +) -> dict: + """ + Executes a Perl script or one-liner using the Perl interpreter. + + This tool provides a comprehensive wrapper around the `perl` command-line + interface, allowing for script execution, syntax checking, module loading, + and control over various runtime behaviors like warnings and data handling. + + Args: + programfile: Path to the Perl program file to execute. + execute_program: One or more lines of a program to execute via `-e`. + execute_program_extended: Like `execute_program`, but enables all optional features (`-E`). + arguments: A list of arguments to be passed to the program. + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). Corresponds to `-c`. + run_under_debugger: Run the program under the specified debugger. Corresponds to `-d[:debugger]`. + dump_core: Dump core after parsing the program. Corresponds to `-u`. + allow_unsafe: Allow unsafe operations. Corresponds to `-U`. + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. Corresponds to `-f`. + search_path: Look for programfile using the PATH environment variable. Corresponds to `-S`. + ignore_pre_hashbang_text: Ignore text before #!perl line, optionally cd to the directory. Corresponds to `-x[directory]`. + record_separator: Specify record separator (`\\0` if no argument). Corresponds to `-0[octal]`. + autosplit: Enable autosplit mode with `-n` or `-p` (splits $_ into @F). Corresponds to `-a`. + split_pattern: Specify the split() pattern for the `-a` switch. Corresponds to `-F/pattern/`. + line_ending_processing: Enable line ending processing and specify the line terminator. Corresponds to `-l[octal]`. + in_place_edit: Edit <> files in place, making a backup if an extension is supplied. Corresponds to `-i[extension]`. + loop_around_program: Assume "while (<>) { ... }" loop around the program. Corresponds to `-n`. + loop_and_print: Assume a loop like `-n` but also print the line. Corresponds to `-p`. + enable_warnings: Enable many useful warnings. Corresponds to `-w`. + enable_all_warnings: Enable all warnings. Corresponds to `-W`. + disable_all_warnings: Disable all warnings. Corresponds to `-X`. + tainting_warnings: Enable tainting warnings. Corresponds to `-t`. + tainting_checks: Enable tainting checks. Corresponds to `-T`. + include_directory: Specify @INC/#include directories. Corresponds to `-I`. + use_module: Execute "use module..." before the program. Corresponds to `-Mmodule`. + use_module_no_import: Execute "use module ()" before the program. Corresponds to `-mmodule`. + no_module: Execute "no module..." before the program. Corresponds to `-M-module`. + no_module_no_import: Corresponds to `-m-module`. + print_version: Print version, patchlevel, and license. Corresponds to `-v`. + print_config: Print configuration summary or a single Config.pm variable. Corresponds to `-V[:variable]`. + unicode_features: Enable the listed Unicode features. Corresponds to `-C[number/list]`. + debugging_flags: Set debugging flags. Corresponds to `-D[number/list]`. + parse_switches: Enable rudimentary parsing for switches after programfile. Corresponds to `-s`. + + Returns: + A dictionary containing the executed command, stdout, stderr, and output file paths. + """ + # --- Input Validation --- + program_sources = sum(p is not None for p in [programfile, execute_program, execute_program_extended]) + is_info_only = print_version or (print_config is not None) + + if not is_info_only and program_sources == 0: + raise ValueError("A program must be specified via 'programfile', 'execute_program', or 'execute_program_extended'.") + if program_sources > 1: + raise ValueError("Only one of 'programfile', 'execute_program', or 'execute_program_extended' can be specified.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"Program file not found: {programfile}") + if include_directory: + for d in include_directory: + if not d.is_dir(): + raise NotADirectoryError(f"Include directory not found: {d}") + if ignore_pre_hashbang_text and not ignore_pre_hashbang_text.is_dir(): + raise NotADirectoryError(f"Directory for -x option not found: {ignore_pre_hashbang_text}") + + # --- Command Construction --- + cmd = ["perl"] + + # Boolean flags + if autosplit: cmd.append("-a") + if check_syntax_only: cmd.append("-c") + if no_sitecustomize: cmd.append("-f") + if loop_around_program: cmd.append("-n") + if loop_and_print: cmd.append("-p") + if parse_switches: cmd.append("-s") + if search_path: cmd.append("-S") + if tainting_warnings: cmd.append("-t") + if tainting_checks: cmd.append("-T") + if dump_core: cmd.append("-u") + if allow_unsafe: cmd.append("-U") + if print_version: cmd.append("-v") + if enable_warnings: cmd.append("-w") + if enable_all_warnings: cmd.append("-W") + if disable_all_warnings: cmd.append("-X") + + # Flags with optional or required values + if record_separator is not None: cmd.append(f"-0{record_separator}") + if unicode_features is not None: cmd.append(f"-C{unicode_features}") + if run_under_debugger is not None: cmd.append(f"-d:{run_under_debugger}" if run_under_debugger else "-d") + if debugging_flags is not None: cmd.append(f"-D{debugging_flags}") + if split_pattern is not None: cmd.append(f"-F{split_pattern}") + if in_place_edit is not None: cmd.append(f"-i{in_place_edit}") + if line_ending_processing is not None: cmd.append(f"-l{line_ending_processing}") + if print_config is not None: cmd.append(f"-V:{print_config}" if print_config else "-V") + if ignore_pre_hashbang_text is not None: cmd.append(f"-x{ignore_pre_hashbang_text}") + elif ignore_pre_hashbang_text == Path('.'): # Special case for -x without directory + cmd.append("-x") + + # List-based flags + if include_directory: + for d in include_directory: + cmd.append(f"-I{d}") + if use_module: + for m in use_module: + cmd.append(f"-M{m}") + if use_module_no_import: + for m in use_module_no_import: + cmd.append(f"-m{m}") + if no_module: + for m in no_module: + cmd.append(f"-M-{m}") + if no_module_no_import: + for m in no_module_no_import: + cmd.append(f"-m-{m}") + if execute_program: + for p in execute_program: + cmd.extend(["-e", p]) + if execute_program_extended: + for p in execute_program_extended: + cmd.extend(["-E", p]) + + # Positional arguments + if programfile: + cmd.append(str(programfile)) + if arguments: + cmd.append("--") + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] # Perl interpreter itself doesn't guarantee output files; scripts do. + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed with return code {e.returncode}", + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "error": "Command not found", + "output_files": [] + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/app/perl-params-check_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/app/perl-params-check_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e90a3d20ce8b48ec644af9378e3da837a149dbd4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/app/perl-params-check_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/app/perl-params-check_server.py') +SERVER_NAME = 'biosci_perl_params_check' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c3c99b2a6953e5e2cfd46dfe5bcedeb1a038f472 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-params-check: + build: . + image: mcp-perl-params-check:latest + container_name: mcp-perl-params-check + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-params-check + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3b3cba7112b3aebe734782ac7771cf639f8e4c05 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-params-check + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..38698618f3c5bdb5d9fa879f2b25083281817959 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-params-util via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-params-util -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-params-util_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-params-util_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-params-util_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/app/perl-params-util_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/app/perl-params-util_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2dc136ad7bdd31824a73445e7d1a04a3888210f1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/app/perl-params-util_server.py @@ -0,0 +1,744 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Union, Any + +# Helper function to run Perl commands +def _run_perl_util_command( + perl_path: Path, + function_name: str, # The specific Params::Util function to import + perl_code: str, # The Perl code snippet to execute + additional_imports: Optional[List[str]] = None, # Other modules to import +) -> Dict[str, Any]: + """ + Executes a Perl one-liner using Params::Util and captures output. + """ + if not perl_path.is_file(): + raise FileNotFoundError(f"Perl executable not found at {perl_path}") + + # Construct the Perl module import string + # We always import the specific function_name, and optionally others + imports = [function_name] + if additional_imports: + imports.extend(additional_imports) + + # Ensure unique imports + imports = list(set(imports)) + + # The -M flag expects a comma-separated list of functions for Params::Util=qw(...) + # and a space-separated list for other modules. + # For simplicity, we'll assume Params::Util functions are passed as qw(...) + # and other modules are just 'use Module;' + + module_import_parts = [f"-MParams::Util=qw({' '.join(imports)})"] + if additional_imports: + # Add other modules as separate -M flags or within the -e block + # For simplicity, we'll add them to the -e block for now. + # If they were to be added via -M, it would be like -MScalar::Util + pass # Handled by including 'use Scalar::Util;' in perl_code if needed + + command = [ + str(perl_path), + *module_import_parts, + "-e", + perl_code, + ] + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + stdout = process.stdout.strip() + stderr = process.stderr.strip() + + # Params::Util functions return undef on failure, which we print as 'undef' + # Map 'undef' string output to Python None + result_value = None if stdout == "undef" else stdout + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "result": result_value, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "error": f"Perl command failed with exit code {e.returncode}", + "result": None, + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": f"Error: Perl executable not found at {perl_path}", + "error": f"Perl executable not found at {perl_path}", + "result": None, + "output_files": [], + } + +@mcp.tool() +def _string( + value: str, + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests if a value is a normal non-false string of non-zero length using Params::Util::_STRING. + Returns the string if valid, or None otherwise. + """ + if not isinstance(value, str): + raise TypeError("Value must be a string.") + if not value: + # _STRING specifically checks for non-zero length + return { + "command_executed": "", + "stdout": "", + "stderr": "Input value is an empty string, which _STRING will treat as invalid.", + "result": None, + "output_files": [], + } + + perl_code = f"my $result = _STRING('{value}'); print defined $result ? $result : 'undef';" + return _run_perl_util_command(perl_path, "_STRING", perl_code) + +@mcp.tool() +def _identifier( + value: str, + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests if a value is a string that is a valid Perl identifier using Params::Util::_IDENTIFIER. + Returns the string if valid, or None otherwise. + """ + if not isinstance(value, str): + raise TypeError("Value must be a string.") + + perl_code = f"my $result = _IDENTIFIER('{value}'); print defined $result ? $result : 'undef';" + return _run_perl_util_command(perl_path, "_IDENTIFIER", perl_code) + +@mcp.tool() +def _class( + value: str, + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests if a value is a string that is a valid Perl class name using Params::Util::_CLASS. + Checks format only, not if the class is loaded. Assumes "normalized" form. + Returns the string if valid, or None otherwise. + """ + if not isinstance(value, str): + raise TypeError("Value must be a string.") + + perl_code = f"my $result = _CLASS('{value}'); print defined $result ? $result : 'undef';" + return _run_perl_util_command(perl_path, "_CLASS", perl_code) + +@mcp.tool() +def _classisa( + value: str, + class_name: str, + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests if a value is a string that is a particular class, or a subclass of it, + using Params::Util::_CLASSISA. Calls the ->isa method on the class name. + Returns the string if valid, or None otherwise. + """ + if not isinstance(value, str) or not isinstance(class_name, str): + raise TypeError("Value and class_name must be strings.") + + perl_code = f"my $result = _CLASSISA('{value}', '{class_name}'); print defined $result ? $result : 'undef';" + return _run_perl_util_command(perl_path, "_CLASSISA", perl_code) + +@mcp.tool() +def _classdoes( + value: str, + role_name: str, + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests if a value is a string that is a particular class, or a class that DOES a role, + using Params::Util::_CLASSDOES. Calls the ->DOES method on the class name. + Recommended for Perl 5.10 or later. + Returns the string if valid, or None otherwise. + """ + if not isinstance(value, str) or not isinstance(role_name, str): + raise TypeError("Value and role_name must be strings.") + + perl_code = f"my $result = _CLASSDOES('{value}', '{role_name}'); print defined $result ? $result : 'undef';" + return _run_perl_util_command(perl_path, "_CLASSDOES", perl_code) + +@mcp.tool() +def _subclass( + value: str, + class_name: str, + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests if a value is a string that is a subclass of a specified class, + using Params::Util::_SUBCLASS. Calls the ->isa method on the class name. + Returns the string if valid, or None otherwise. + """ + if not isinstance(value, str) or not isinstance(class_name, str): + raise TypeError("Value and class_name must be strings.") + + perl_code = f"my $result = _SUBCLASS('{value}', '{class_name}'); print defined $result ? $result : 'undef';" + return _run_perl_util_command(perl_path, "_SUBCLASS", perl_code) + +@mcp.tool() +def _number( + value: Union[str, int, float], + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests if a value is a number (defined and Perl thinks it's a number) + using Params::Util::_NUMBER. + Returns the value if valid, or None otherwise. + """ + # Perl's looks_like_number is quite flexible, so we pass the string representation + perl_value = str(value) + perl_code = f"use Scalar::Util qw(looks_like_number); my $result = _NUMBER('{perl_value}'); print defined $result ? $result : 'undef';" + return _run_perl_util_command(perl_path, "_NUMBER", perl_code, additional_imports=["Scalar::Util"]) + +@mcp.tool() +def _posint( + value: Union[str, int], + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests if a value is a positive integer using Params::Util::_POSINT. + Returns the value if valid, or None otherwise. + """ + perl_value = str(value) + perl_code = f"my $result = _POSINT('{perl_value}'); print defined $result ? $result : 'undef';" + return _run_perl_util_command(perl_path, "_POSINT", perl_code) + +@mcp.tool() +def _nonnegint( + value: Union[str, int], + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests if a value is a non-negative integer (positive integer or zero) + using Params::Util::_NONNEGINT. + Returns the value if valid, or None otherwise. + """ + perl_value = str(value) + perl_code = f"my $result = _NONNEGINT('{perl_value}'); print defined $result ? $result : 'undef';" + return _run_perl_util_command(perl_path, "_NONNEGINT", perl_code) + +@mcp.tool() +def _scalar( + value_content: str, + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests for a raw and unblessed SCALAR reference with non-zero length content + using Params::Util::_SCALAR. + The Python 'value_content' is used to create a scalar reference in Perl. + Returns the dereferenced scalar content if valid, or None otherwise. + """ + # Perl code creates a scalar variable, takes a reference to it, and passes the reference. + # Then it prints the dereferenced value if valid. + perl_code = f""" + my $val = '{value_content}'; + my $ref = \\$val; + my $result = _SCALAR($ref); + print defined $result ? $$result : 'undef'; + """ + return _run_perl_util_command(perl_path, "_SCALAR", perl_code) + +@mcp.tool() +def _scalar0( + value_content: str, + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests for a raw and unblessed SCALAR reference, allowing zero-length content, + using Params::Util::_SCALAR0. + The Python 'value_content' is used to create a scalar reference in Perl. + Returns the dereferenced scalar content if valid, or None otherwise. + """ + perl_code = f""" + my $val = '{value_content}'; + my $ref = \\$val; + my $result = _SCALAR0($ref); + print defined $result ? $$result : 'undef'; + """ + return _run_perl_util_command(perl_path, "_SCALAR0", perl_code) + +@mcp.tool() +def _array( + values: List[str], + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests for a raw and unblessed ARRAY reference containing at least one element + using Params::Util::_ARRAY. + The Python 'values' list is used to create an array reference in Perl. + Returns a comma-separated string of dereferenced array elements if valid, or None otherwise. + """ + if not isinstance(values, list): + raise TypeError("Values must be a list of strings.") + if not values: + # _ARRAY specifically checks for at least one element + return { + "command_executed": "", + "stdout": "", + "stderr": "Input values list is empty, which _ARRAY will treat as invalid.", + "result": None, + "output_files": [], + } + + perl_array_elements = ', '.join(f"'{v}'" for v in values) + perl_code = f""" + my @arr = ({perl_array_elements}); + my $ref = \\@arr; + my $result = _ARRAY($ref); + print defined $result ? join(',', @$result) : 'undef'; + """ + return _run_perl_util_command(perl_path, "_ARRAY", perl_code) + +@mcp.tool() +def _array0( + values: List[str], + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests for a raw and unblessed ARRAY reference, allowing zero-length content, + using Params::Util::_ARRAY0. + The Python 'values' list is used to create an array reference in Perl. + Returns a comma-separated string of dereferenced array elements if valid, or None otherwise. + """ + if not isinstance(values, list): + raise TypeError("Values must be a list of strings.") + + perl_array_elements = ', '.join(f"'{v}'" for v in values) + perl_code = f""" + my @arr = ({perl_array_elements}); + my $ref = \\@arr; + my $result = _ARRAY0($ref); + print defined $result ? join(',', @$result) : 'undef'; + """ + return _run_perl_util_command(perl_path, "_ARRAY0", perl_code) + +@mcp.tool() +def _arraylike( + value: str, + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests whether a given scalar value can respond to array dereferencing + using Params::Util::_ARRAYLIKE. + Note: This function is difficult to test generically via `perl -e` with simple strings, + as it typically expects an actual Perl reference or an object that overloads array dereferencing. + Passing a simple string will likely result in 'undef'. + Returns the value if it's array-like, or None otherwise. + """ + if not isinstance(value, str): + raise TypeError("Value must be a string.") + + perl_code = f""" + my $val = '{value}'; + my $result = _ARRAYLIKE($val); + print defined $result ? $result : 'undef'; + """ + return _run_perl_util_command(perl_path, "_ARRAYLIKE", perl_code) + +@mcp.tool() +def _hash( + values: Dict[str, str], + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests for a raw and unblessed HASH reference with at least one entry + using Params::Util::_HASH. + The Python 'values' dictionary is used to create a hash reference in Perl. + Returns a comma-separated string of key-value pairs (key=>value) if valid, or None otherwise. + """ + if not isinstance(values, dict): + raise TypeError("Values must be a dictionary of strings.") + if not values: + # _HASH specifically checks for at least one entry + return { + "command_executed": "", + "stdout": "", + "stderr": "Input values dictionary is empty, which _HASH will treat as invalid.", + "result": None, + "output_files": [], + } + + perl_hash_elements = ', '.join(f"'{k}' => '{v}'" for k, v in values.items()) + perl_code = f""" + my %hash = ({perl_hash_elements}); + my $ref = \\%hash; + my $result = _HASH($ref); + print defined $result ? join(',', map {{ "$_=>$hash{{$_}}" }} sort keys %$result) : 'undef'; + """ + return _run_perl_util_command(perl_path, "_HASH", perl_code) + +@mcp.tool() +def _hash0( + values: Dict[str, str], + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests for a raw and unblessed HASH reference, regardless of content, + using Params::Util::_HASH0. + The Python 'values' dictionary is used to create a hash reference in Perl. + Returns a comma-separated string of key-value pairs (key=>value) if valid, or None otherwise. + """ + if not isinstance(values, dict): + raise TypeError("Values must be a dictionary of strings.") + + perl_hash_elements = ', '.join(f"'{k}' => '{v}'" for k, v in values.items()) + perl_code = f""" + my %hash = ({perl_hash_elements}); + my $ref = \\%hash; + my $result = _HASH0($ref); + print defined $result ? join(',', map {{ "$_=>$hash{{$_}}" }} sort keys %$result) : 'undef'; + """ + return _run_perl_util_command(perl_path, "_HASH0", perl_code) + +@mcp.tool() +def _hashlike( + value: str, + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests whether a given scalar value can respond to hash dereferencing + using Params::Util::_HASHLIKE. + Note: This function is difficult to test generically via `perl -e` with simple strings, + as it typically expects an actual Perl reference or an object that overloads hash dereferencing. + Passing a simple string will likely result in 'undef'. + Returns the value if it's hash-like, or None otherwise. + """ + if not isinstance(value, str): + raise TypeError("Value must be a string.") + + perl_code = f""" + my $val = '{value}'; + my $result = _HASHLIKE($val); + print defined $result ? $result : 'undef'; + """ + return _run_perl_util_command(perl_path, "_HASHLIKE", perl_code) + +@mcp.tool() +def _code( + code_string: str, + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests for a raw and unblessed CODE reference using Params::Util::_CODE. + The 'code_string' is evaluated in Perl to create a code reference. + WARNING: Evaluating arbitrary code from user input can be a security risk. + Returns 'CODE_REF' if a valid code reference is created and validated, or None otherwise. + """ + if not isinstance(code_string, str): + raise TypeError("Code string must be a string.") + + perl_code = f""" + my $code_ref; + eval '$code_ref = sub {{ {code_string} }};'; + if ($@) {{ + print STDERR "Perl eval error: $@"; + print "undef"; + }} else {{ + my $result = _CODE($code_ref); + print defined $result ? 'CODE_REF' : 'undef'; + }} + """ + return _run_perl_util_command(perl_path, "_CODE", perl_code) + +@mcp.tool() +def _codelike( + code_string: str, + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests whether a given scalar value can respond to code dereferencing (like _CODE, + but also includes objects overloading '&{}') using Params::Util::_CODELIKE. + The 'code_string' is evaluated in Perl to create a code reference. + WARNING: Evaluating arbitrary code from user input can be a security risk. + Returns 'CODE_REF' if a valid callable is created and validated, or None otherwise. + """ + if not isinstance(code_string, str): + raise TypeError("Code string must be a string.") + + perl_code = f""" + my $code_ref; + eval '$code_ref = sub {{ {code_string} }};'; + if ($@) {{ + print STDERR "Perl eval error: $@"; + print "undef"; + }} else {{ + my $result = _CODELIKE($code_ref); + print defined $result ? 'CODE_REF' : 'undef'; + }} + """ + return _run_perl_util_command(perl_path, "_CODELIKE", perl_code) + +@mcp.tool() +def _invocant( + value: str, + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests whether the given value is a valid method invocant (object instance or class name) + using Params::Util::_INVOCANT. + Returns the value if it's a valid invocant, or None otherwise. + """ + if not isinstance(value, str): + raise TypeError("Value must be a string.") + + perl_code = f"my $result = _INVOCANT('{value}'); print defined $result ? $result : 'undef';" + return _run_perl_util_command(perl_path, "_INVOCANT", perl_code) + +@mcp.tool() +def _instance( + object_class_name: str, + expected_class: str, + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests for an object of a particular class in a strictly correct manner + using Params::Util::_INSTANCE. + The 'object_class_name' is used to attempt to instantiate an object in Perl. + Returns the class name of the object if valid, or None otherwise. + Note: This requires the 'object_class_name' to be a loadable Perl module with a 'new' constructor that takes no arguments. + """ + if not isinstance(object_class_name, str) or not isinstance(expected_class, str): + raise TypeError("Object class name and expected class must be strings.") + + # Attempt to instantiate the object in Perl + perl_code = f""" + my $obj; + eval "use {object_class_name};"; + if ($@) {{ + print STDERR "Perl module load error for {object_class_name}: $@"; + print "undef"; + }} else {{ + eval '$obj = {object_class_name}->new();'; + if ($@) {{ + print STDERR "Perl object instantiation error for {object_class_name}: $@"; + print "undef"; + }} else {{ + my $result = _INSTANCE($obj, '{expected_class}'); + print defined $result ? ref($result) : 'undef'; + }} + }} + """ + return _run_perl_util_command(perl_path, "_INSTANCE", perl_code) + +@mcp.tool() +def _instancedoes( + object_class_name: str, + role_name: str, + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests for an object that DOES a particular role, similar to _INSTANCE, + using Params::Util::_INSTANCEDOES. + The 'object_class_name' is used to attempt to instantiate an object in Perl. + Returns the class name of the object if valid, or None otherwise. + Note: This requires the 'object_class_name' to be a loadable Perl module with a 'new' constructor that takes no arguments. + Recommended for Perl 5.10 or later. + """ + if not isinstance(object_class_name, str) or not isinstance(role_name, str): + raise TypeError("Object class name and role name must be strings.") + + perl_code = f""" + my $obj; + eval "use {object_class_name};"; + if ($@) {{ + print STDERR "Perl module load error for {object_class_name}: $@"; + print "undef"; + }} else {{ + eval '$obj = {object_class_name}->new();'; + if ($@) {{ + print STDERR "Perl object instantiation error for {object_class_name}: $@"; + print "undef"; + }} else {{ + my $result = _INSTANCEDOES($obj, '{role_name}'); + print defined $result ? ref($result) : 'undef'; + }} + }} + """ + return _run_perl_util_command(perl_path, "_INSTANCEDOES", perl_code) + +@mcp.tool() +def _regex( + pattern: str, + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests for a regular expression using Params::Util::_REGEX. + The 'pattern' string is converted to a Perl regex object (qr{}) for testing. + Returns the pattern string if it's a valid regex, or None otherwise. + """ + if not isinstance(pattern, str): + raise TypeError("Pattern must be a string.") + + # Perl code creates a regex object from the pattern string + perl_code = f""" + my $regex_obj; + eval '$regex_obj = qr{{{pattern}}};'; + if ($@) {{ + print STDERR "Perl regex compilation error: $@"; + print "undef"; + }} else {{ + my $result = _REGEX($regex_obj); + print defined $result ? '{pattern}' : 'undef'; # Return the original pattern if valid + }} + """ + return _run_perl_util_command(perl_path, "_REGEX", perl_code) + +@mcp.tool() +def _set( + num_objects: int, + class_name: str, + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests for a set of at least one object of a particular class using Params::Util::_SET. + 'num_objects' specifies how many objects of 'class_name' to instantiate in Perl. + Returns a comma-separated string of dereferenced object class names if valid, or None otherwise. + Note: This requires 'class_name' to be a loadable Perl module with a 'new' constructor that takes no arguments. + """ + if not isinstance(num_objects, int) or num_objects < 0: + raise ValueError("num_objects must be a non-negative integer.") + if not isinstance(class_name, str): + raise TypeError("class_name must be a string.") + if num_objects == 0: + # _SET specifically checks for at least one object + return { + "command_executed": "", + "stdout": "", + "stderr": "num_objects is 0, which _SET will treat as invalid (requires at least one object).", + "result": None, + "output_files": [], + } + + # Construct Perl code to instantiate objects and create an array reference + perl_object_instantiation = [] + for i in range(num_objects): + perl_object_instantiation.append(f"eval '$obj_{i} = {class_name}->new();' or die $@;") + perl_object_instantiation.append(f"push @arr, $obj_{i};") + + perl_code = f""" + my @arr; + eval "use {class_name};"; + if ($@) {{ + print STDERR "Perl module load error for {class_name}: $@"; + print "undef"; + }} else {{ + {' '.join(perl_object_instantiation)} + my $ref = \\@arr; + my $result = _SET($ref, '{class_name}'); + print defined $result ? join(',', map {{ ref($_) }} @$result) : 'undef'; + }} + """ + return _run_perl_util_command(perl_path, "_SET", perl_code) + +@mcp.tool() +def _set0( + num_objects: int, + class_name: str, + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests for a set of objects of a particular class, allowing zero objects, + using Params::Util::_SET0. + 'num_objects' specifies how many objects of 'class_name' to instantiate in Perl. + Returns a comma-separated string of dereferenced object class names if valid, or None otherwise. + Note: This requires 'class_name' to be a loadable Perl module with a 'new' constructor that takes no arguments. + """ + if not isinstance(num_objects, int) or num_objects < 0: + raise ValueError("num_objects must be a non-negative integer.") + if not isinstance(class_name, str): + raise TypeError("class_name must be a string.") + + # Construct Perl code to instantiate objects and create an array reference + perl_object_instantiation = [] + for i in range(num_objects): + perl_object_instantiation.append(f"eval '$obj_{i} = {class_name}->new();' or die $@;") + perl_object_instantiation.append(f"push @arr, $obj_{i};") + + perl_code = f""" + my @arr; + eval "use {class_name};"; + if ($@) {{ + print STDERR "Perl module load error for {class_name}: $@"; + print "undef"; + }} else {{ + {' '.join(perl_object_instantiation)} + my $ref = \\@arr; + my $result = _SET0($ref, '{class_name}'); + print defined $result ? join(',', map {{ ref($_) }} @$result) : 'undef'; + }} + """ + return _run_perl_util_command(perl_path, "_SET0", perl_code) + +@mcp.tool() +def _handle( + file_path: Optional[Path] = None, + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Tests whether a single scalar value is a file handle using Params::Util::_HANDLE. + If 'file_path' is provided, Perl attempts to open it and checks the resulting handle. + If 'file_path' is None, it checks STDIN. + Returns 'HANDLE_OK' if a valid file handle is detected, or None otherwise. + """ + if file_path is not None and not isinstance(file_path, Path): + raise TypeError("file_path must be a Path object or None.") + + if file_path: + # Ensure the file exists if provided + if not file_path.is_file(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Input file not found at {file_path}", + "result": None, + "output_files": [], + } + perl_code = f""" + open my $fh, '<', '{file_path}' or die "Could not open file {file_path}: $!"; + my $result = _HANDLE($fh); + close $fh; + print defined $result ? 'HANDLE_OK' : 'undef'; + """ + else: + # Check STDIN if no file path is provided + perl_code = """ + my $result = _HANDLE(*STDIN{IO}); + print defined $result ? 'HANDLE_OK' : 'undef'; + """ + return _run_perl_util_command(perl_path, "_HANDLE", perl_code) + +@mcp.tool() +def _driver( + class_name: str, + base_driver_class: str, + perl_path: Path = Path("perl"), +) -> Dict[str, Any]: + """ + Loads and validates a driver class using Params::Util::_DRIVER. + Checks that 'class_name' is a valid class, loads it, and ensures it returns true + for the 'isa' method on 'base_driver_class'. + Returns the class name if valid, or None otherwise. + """ + if not isinstance(class_name, str) or not isinstance(base_driver_class, str): + raise TypeError("Class name and base driver class must be strings.") + + perl_code = f""" + my $result = _DRIVER('{class_name}', '{base_driver_class}'); + print defined $result ? $result : 'undef'; + """ + return _run_perl_util_command(perl_path, "_DRIVER", perl_code) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/app/perl-params-util_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/app/perl-params-util_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1d26f5e82499f168c45bebb653244e53d2b9f69a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/app/perl-params-util_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/app/perl-params-util_server.py') +SERVER_NAME = 'biosci_perl_params_util' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..9bbed5b605328a259b48223495990a2c85112ac8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-params-util: + build: . + image: mcp-perl-params-util:latest + container_name: mcp-perl-params-util + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-params-util + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e3c65947edd91d4c4f1bb24a35720f1218527dbf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-params-util + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-util/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ae63329f61cc4dcb40fb646433f52e223e028287 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-params-validate via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-params-validate -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-params-validate_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-params-validate_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-params-validate_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/app/perl-params-validate_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/app/perl-params-validate_server.py new file mode 100644 index 0000000000000000000000000000000000000000..80faaab0472733813d2208e6254613e43a93647b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/app/perl-params-validate_server.py @@ -0,0 +1,228 @@ +import subprocess +import shlex +from pathlib import Path +from typing import Optional, List, Dict + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be imported. +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def perl_run( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + execute_program: Optional[List[str]] = None, + execute_program_extended: Optional[List[str]] = None, + check_syntax_only: bool = False, + print_version: bool = False, + print_config: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + tainting_checks: bool = False, + tainting_warnings: bool = False, + include_directories: Optional[List[Path]] = None, + use_modules: Optional[List[str]] = None, + no_modules: Optional[List[str]] = None, + use_modules_m: Optional[List[str]] = None, + no_modules_m: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + autosplit: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + line_ending_processing: Optional[str] = None, + record_separator: Optional[str] = None, + run_under_debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + unicode_features: Optional[str] = None, + no_sitecustomize: bool = False, + enable_switch_parsing: bool = False, + search_path: bool = False, + dump_core: bool = False, + allow_unsafe: bool = False, + ignore_text_before_shebang: bool = False, + shebang_directory: Optional[Path] = None, +) -> Dict: + """ + Executes a Perl program using the standard Perl interpreter. + + Note: 'perl-params-validate' is a Perl module, not a standalone executable. + This tool wraps the 'perl' interpreter, which is used to run scripts that + may utilize the Params::Validate module. + + Args: + programfile: Path to the Perl program file to execute. + arguments: A list of arguments to pass to the program file. + execute_program: One or more lines of a program to execute (-e). Omit programfile. + execute_program_extended: Like -e, but enables all optional features (-E). + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks) (-c). + print_version: Print version, patchlevel, and license (-v). + print_config: Print configuration summary or a single variable (-V[:variable]). + enable_warnings: Enable many useful warnings (-w). + enable_all_warnings: Enable all warnings (-W). + disable_all_warnings: Disable all warnings (-X). + tainting_checks: Enable tainting checks (-T). + tainting_warnings: Enable tainting warnings (-t). + include_directories: Specify @INC/#include directories (-I). + use_modules: Execute "use module..." before the program (-Mmodule). + no_modules: Execute "no module..." before the program (-M-module). + use_modules_m: A variant of -M for executing "use module..." (-mmodule). + no_modules_m: A variant of -M for executing "no module..." (-m-module). + loop_around_program: Assume "while (<>) { ... }" loop around the program (-n). + loop_and_print: Assume loop like -n but also print line, like sed (-p). + autosplit: Enable autosplit mode with -n or -p (splits $_ into @F) (-a). + split_pattern: Specify the split() pattern for the -a switch (-F/pattern/). + edit_in_place_extension: Edit <> files in place, with an optional backup extension (-i[extension]). + line_ending_processing: Enable line ending processing, specifies line terminator (-l[octal]). + record_separator: Specify the record separator (\\0, if no argument) (-0[octal]). + run_under_debugger: Run the program under a debugger (-d[:debugger]). + debugging_flags: Set debugging flags (-D[number/list]). + unicode_features: Enable the listed Unicode features (-C[number/list]). + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup (-f). + enable_switch_parsing: Enable rudimentary parsing for switches after programfile (-s). + search_path: Look for programfile using the PATH environment variable (-S). + dump_core: Dump core after parsing the program (-u). + allow_unsafe: Allow unsafe operations (-U). + ignore_text_before_shebang: Ignore text before #!perl line (-x). + shebang_directory: Change directory to the specified one before running script with -x. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + has_programfile = programfile is not None + has_e_prog = execute_program is not None + has_E_prog = execute_program_extended is not None + + if not any([has_programfile, has_e_prog, has_E_prog, print_version, print_config is not None]): + raise ValueError("A program source must be provided via 'programfile', 'execute_program', 'execute_program_extended', 'print_version', or 'print_config'.") + + if has_programfile and (has_e_prog or has_E_prog): + raise ValueError("'programfile' cannot be used with 'execute_program' or 'execute_program_extended'.") + + if loop_around_program and loop_and_print: + raise ValueError("'loop_around_program' (-n) and 'loop_and_print' (-p) are mutually exclusive.") + + if tainting_warnings and tainting_checks: + raise ValueError("'tainting_warnings' (-t) and 'tainting_checks' (-T) are mutually exclusive.") + + if shebang_directory and not ignore_text_before_shebang: + raise ValueError("'shebang_directory' can only be used when 'ignore_text_before_shebang' is True.") + + if has_programfile and not programfile.is_file(): + raise FileNotFoundError(f"Program file not found: {programfile}") + + # --- Command Construction --- + cmd = ["perl"] + + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if run_under_debugger is not None: + cmd.append(f"-d{run_under_debugger}") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if execute_program: + for prog in execute_program: + cmd.extend(["-e", prog]) + if execute_program_extended: + for prog in execute_program_extended: + cmd.extend(["-E", prog]) + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + cmd.append(f"-i{edit_in_place_extension}") + if include_directories: + for directory in include_directories: + cmd.extend(["-I", str(directory)]) + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + if use_modules: + for module in use_modules: + cmd.append(f"-M{module}") + if no_modules: + for module in no_modules: + cmd.append(f"-M-{module}") + if use_modules_m: + for module in use_modules_m: + cmd.append(f"-m{module}") + if no_modules_m: + for module in no_modules_m: + cmd.append(f"-m-{module}") + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if enable_switch_parsing: + cmd.append("-s") + if search_path: + cmd.append("-S") + if tainting_warnings: + cmd.append("-t") + if tainting_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if allow_unsafe: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config is not None: + cmd.append(f"-V{print_config}") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if ignore_text_before_shebang: + cmd.append(f"-x{shebang_directory}" if shebang_directory else "-x") + if disable_all_warnings: + cmd.append("-X") + + if programfile: + cmd.append(str(programfile)) + + if arguments: + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = shlex.join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Is Perl installed and in the system's PATH?", + "error": "Command not found", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed with return code {e.returncode}", + "output_files": [] + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/app/perl-params-validate_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/app/perl-params-validate_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..06ae216cca15872650cb5565d5a4be6188a84713 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/app/perl-params-validate_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/app/perl-params-validate_server.py') +SERVER_NAME = 'biosci_perl_params_validate' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..36bc3e6873e579908a1a2073f488d9129a8fcf97 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-params-validate: + build: . + image: mcp-perl-params-validate:latest + container_name: mcp-perl-params-validate + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-params-validate + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cd368fdf7d5d5bcdb1516aaba5f80ba5a6d5a2a7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-params-validate + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-validate/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..43064fcee75307587503cd4428a6bb8e4a229a78 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-parent via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-parent -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-parent_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-parent_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-parent_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/app/perl-parent_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/app/perl-parent_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8475f87cb91bc05bf3a568c88f38e8d532c0d8fe --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/app/perl-parent_server.py @@ -0,0 +1,346 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def samtools_view( + input_file: str, + output_file: Optional[str] = None, + is_bam: bool = False, + is_cram: bool = False, + uncompressed: bool = False, + fast_compression: bool = False, + count: bool = False, + header_only: bool = False, + include_header: bool = False, + threads: int = 1, + subsample_fraction: float = 0.0, + region: Optional[str] = None, + min_mq: int = 0, + require_flags: int = 0, + exclude_flags: int = 0, +): + """ + Views and converts SAM/BAM/CRAM files. + + Args: + input_file: Path to the input SAM, BAM, or CRAM file. + output_file: Path to the output file. + is_bam: Output BAM format. + is_cram: Output CRAM format. + uncompressed: Output uncompressed BAM. + fast_compression: Use fast BAM compression. + count: Instead of printing the alignments, only count them. + header_only: Output the header only. + include_header: Include the header in the output. + threads: Number of additional threads to use. + subsample_fraction: Fraction of templates/reads to subsample [0.0 to 1.0]. + region: Optional genomic region (e.g., 'chr1:100-200'). + min_mq: Skip alignments with MAPQ smaller than this value. + require_flags: Only include reads with all bits set in INT present in the FLAG field. + exclude_flags: Only include reads with none of the bits set in INT present in the FLAG field. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} does not exist."} + + cmd = ["samtools", "view"] + + if is_bam: cmd.append("-b") + if is_cram: cmd.append("-C") + if uncompressed: cmd.append("-u") + if fast_compression: cmd.append("-1") + if count: cmd.append("-c") + if header_only: cmd.append("-H") + if include_header: cmd.append("-h") + if threads > 1: cmd.extend(["-@", str(threads)]) + if subsample_fraction > 0.0: cmd.extend(["-s", str(subsample_fraction)]) + if min_mq > 0: cmd.extend(["-q", str(min_mq)]) + if require_flags > 0: cmd.extend(["-f", str(require_flags)]) + if exclude_flags > 0: cmd.extend(["-F", str(exclude_flags)]) + + if output_file: + cmd.extend(["-o", output_file]) + + cmd.append(input_file) + + if region: + cmd.append(region) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] if output_file else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def samtools_sort( + input_file: str, + output_file: str, + threads: int = 1, + memory_per_thread: str = "768M", + by_name: bool = False, + compression_level: int = -1, +): + """ + Sorts alignments by leftmost coordinates or by read name. + + Args: + input_file: Path to the input BAM/SAM/CRAM file. + output_file: Path to the output sorted file. + threads: Number of additional threads to use. + memory_per_thread: Maximum memory per thread; suffix K/M/G recognized. + by_name: Sort by read name instead of chromosomal coordinates. + compression_level: Set compression level, from 0 (uncompressed) to 9 (best). + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} does not exist."} + + cmd = ["samtools", "sort", "-o", output_file] + + if threads > 1: cmd.extend(["-@", str(threads)]) + if memory_per_thread != "768M": cmd.extend(["-m", memory_per_thread]) + if by_name: cmd.append("-n") + if compression_level >= 0: cmd.extend(["-l", str(compression_level)]) + + cmd.append(input_file) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def samtools_index( + input_file: str, + output_index: Optional[str] = None, + csi: bool = False, + min_shift: int = 0, + threads: int = 1, +): + """ + Indexes a coordinate-sorted BAM or CRAM file. + + Args: + input_file: Path to the sorted BAM/CRAM file. + output_index: Optional path for the output index file. + csi: Generate CSI-format index instead of BAI. + min_shift: Set minimum interval size for CSI indices to 2^INT. + threads: Number of additional threads to use. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} does not exist."} + + cmd = ["samtools", "index"] + + if csi: cmd.append("-c") + if min_shift > 0: cmd.extend(["-m", str(min_shift)]) + if threads > 1: cmd.extend(["-@", str(threads)]) + + cmd.append(input_file) + if output_index: + cmd.append(output_index) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_index if output_index else f"{input_file}.bai"] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def samtools_flagstat( + input_file: str, + threads: int = 1, +): + """ + Provides simple statistics from the BAM FLAG field. + + Args: + input_file: Path to the BAM/SAM/CRAM file. + threads: Number of additional threads to use. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} does not exist."} + + cmd = ["samtools", "flagstat"] + if threads > 1: cmd.extend(["-@", str(threads)]) + cmd.append(input_file) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def samtools_stats( + input_file: str, + reference: Optional[str] = None, + threads: int = 1, + remove_dups: bool = False, +): + """ + Generates comprehensive statistics from a BAM file. + + Args: + input_file: Path to the BAM/SAM/CRAM file. + reference: Optional path to the reference fasta file. + threads: Number of additional threads to use. + remove_dups: Exclude duplicate reads from statistics. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} does not exist."} + + cmd = ["samtools", "stats"] + if threads > 1: cmd.extend(["-@", str(threads)]) + if reference: cmd.extend(["--reference", reference]) + if remove_dups: cmd.append("-d") + cmd.append(input_file) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def samtools_faidx( + fasta_file: str, + region: Optional[str] = None, + output_file: Optional[str] = None, +): + """ + Indexes or extracts regions from a FASTA file. + + Args: + fasta_file: Path to the reference FASTA file. + region: Optional genomic region to extract (e.g., 'chr1:100-200'). + output_file: Optional path to save the extracted sequence. + """ + fasta_path = Path(fasta_file) + if not fasta_path.exists(): + return {"error": f"Fasta file {fasta_file} does not exist."} + + cmd = ["samtools", "faidx", fasta_file] + if region: + cmd.append(region) + + if output_file: + cmd.extend(["-o", output_file]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] if output_file else [f"{fasta_file}.fai"] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def samtools_depth( + input_file: str, + output_file: Optional[str] = None, + region: Optional[str] = None, + min_base_quality: int = 0, + min_mapping_quality: int = 0, +): + """ + Computes the depth of coverage at each genomic position. + + Args: + input_file: Path to the BAM/SAM/CRAM file. + output_file: Optional path to save the depth output. + region: Optional genomic region (e.g., 'chr1:100-200'). + min_base_quality: Minimum base quality. + min_mapping_quality: Minimum mapping quality. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} does not exist."} + + cmd = ["samtools", "depth"] + if min_base_quality > 0: cmd.extend(["-q", str(min_base_quality)]) + if min_mapping_quality > 0: cmd.extend(["-Q", str(min_mapping_quality)]) + if region: cmd.extend(["-r", region]) + + if output_file: + cmd.extend(["-o", output_file]) + + cmd.append(input_file) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] if output_file else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/app/perl-parent_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/app/perl-parent_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..104c3f13e0c802eb9fc7e57c47b2138f365a3afc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/app/perl-parent_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/app/perl-parent_server.py') +SERVER_NAME = 'biosci_perl_parent' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..efccfc3a2ad8f327f7d35bfee62fec77946b2c92 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-parent: + build: . + image: mcp-perl-parent:latest + container_name: mcp-perl-parent + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-parent + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..381fd14ffc602071d09ab2fc5694246390b75e0b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-parent + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parent/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ccae3e165318875a244a3b51936761aa0e8c73db --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-parse-recdescent via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-parse-recdescent -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-parse-recdescent_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-parse-recdescent_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-parse-recdescent_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/app/perl-parse-recdescent_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/app/perl-parse-recdescent_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7632cde397ce484501c8a1ea1d912be823d2b2fa --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/app/perl-parse-recdescent_server.py @@ -0,0 +1,229 @@ +from typing import Optional, List +import subprocess +from pathlib import Path + +@mcp.tool() +def precompile_grammar( + grammar_file: str, + parser_class: str, + output_file: str, + use_warnings: bool = True, +) -> dict: + """ + Precompiles a Parse::RecDescent grammar into a standalone Perl module. + + This is the primary way to generate a recursive-descent parser from a grammar + specification file. The resulting file is a standard Perl module (.pm). + + Args: + grammar_file: Path to the file containing the RecDescent grammar specification. + parser_class: The name of the Perl class/package to be generated (e.g., 'My::Parser'). + output_file: Path where the generated Perl module (.pm) should be saved. + use_warnings: Whether to enable Perl warnings during the generation process. + """ + grammar_path = Path(grammar_file) + output_path = Path(output_file) + + if not grammar_path.exists(): + return {"error": f"Grammar file not found: {grammar_file}"} + + # Ensure output directory exists + output_path.parent.mkdir(parents=True, exist_ok=True) + + # Construct the Perl command + # We use a one-liner to read the grammar from STDIN and call Precompile + perl_cmd = ["perl"] + if use_warnings: + perl_cmd.append("-w") + + perl_cmd.extend([ + "-MParse::RecDescent", + "-e", + "undef $/; my $grammar = ; Parse::RecDescent->Precompile($grammar, $ARGV[0]);", + "--", + parser_class + ]) + + try: + with open(grammar_path, "r") as f_in: + result = subprocess.run( + perl_cmd, + stdin=f_in, + capture_output=True, + text=True, + check=True + ) + + # Precompile prints the generated code to STDOUT + with open(output_path, "w") as f_out: + f_out.write(result.stdout) + + return { + "command_executed": " ".join(perl_cmd) + f" < {grammar_file} > {output_file}", + "stdout": "Parser generated successfully.", + "stderr": result.stderr, + "output_files": [str(output_path.absolute())] + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to precompile grammar. Check if the grammar syntax is valid." + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def verify_grammar( + grammar_file: str, +) -> dict: + """ + Validates the syntax of a Parse::RecDescent grammar file. + + This tool attempts to instantiate a parser object from the grammar. + If the grammar contains errors, Parse::RecDescent will report them to STDERR. + + Args: + grammar_file: Path to the file containing the RecDescent grammar specification. + """ + grammar_path = Path(grammar_file) + + if not grammar_path.exists(): + return {"error": f"Grammar file not found: {grammar_file}"} + + # Perl command to check grammar validity + perl_cmd = [ + "perl", + "-MParse::RecDescent", + "-e", + "undef $/; my $grammar = ; my $parser = Parse::RecDescent->new($grammar); exit($parser ? 0 : 1);" + ] + + try: + with open(grammar_path, "r") as f_in: + result = subprocess.run( + perl_cmd, + stdin=f_in, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": " ".join(perl_cmd) + f" < {grammar_file}", + "stdout": "Grammar is valid.", + "stderr": result.stderr, + "valid": True + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Grammar validation failed.", + "valid": False + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def run_parser_test( + grammar_file: str, + input_text: str, + start_rule: str = "start", +) -> dict: + """ + Tests a grammar against a specific input string without precompiling. + + Useful for rapid prototyping and debugging of grammars. + + Args: + grammar_file: Path to the grammar specification. + input_text: The text string to be parsed. + start_rule: The name of the top-level rule in the grammar to start parsing from. + """ + grammar_path = Path(grammar_file) + + if not grammar_path.exists(): + return {"error": f"Grammar file not found: {grammar_file}"} + + # Perl script to load grammar and parse input + # $ARGV[0] is the start rule, $ARGV[1] is the input text + perl_script = """ + use Parse::RecDescent; + undef $/; + my $grammar = ; + my $parser = Parse::RecDescent->new($grammar) or die "Invalid grammar"; + my $result = $parser->$ARGV[0]($ARGV[1]); + if (defined $result) { + print "Match successful.\\n"; + } else { + print "Match failed.\\n"; + exit 1; + } + """ + + perl_cmd = [ + "perl", + "-MParse::RecDescent", + "-e", + perl_script, + "--", + start_rule, + input_text + ] + + try: + with open(grammar_path, "r") as f_in: + result = subprocess.run( + perl_cmd, + stdin=f_in, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": "perl -MParse::RecDescent ...", + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": "perl -MParse::RecDescent ...", + "stdout": e.stdout, + "stderr": e.stderr, + "status": "failed", + "error": "Parsing failed or grammar error." + } + +@mcp.tool() +def perl_recdescent_info() -> dict: + """ + Returns the version information for Perl and the Parse::RecDescent module. + """ + try: + perl_ver = subprocess.run(["perl", "-v"], capture_output=True, text=True, check=True) + mod_ver = subprocess.run( + ["perl", "-MParse::RecDescent", "-e", "print $Parse::RecDescent::VERSION"], + capture_output=True, + text=True, + check=True + ) + + return { + "perl_version": perl_ver.stdout.splitlines()[1] if len(perl_ver.stdout.splitlines()) > 1 else "Unknown", + "parse_recdescent_version": mod_ver.stdout, + "status": "installed" + } + except Exception as e: + return { + "status": "error", + "error": str(e), + "message": "Ensure perl and perl-parse-recdescent are installed in the environment." + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/app/perl-parse-recdescent_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/app/perl-parse-recdescent_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..52c27b5bdfd8f5d31a1be764904c9a4170e5d863 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/app/perl-parse-recdescent_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/app/perl-parse-recdescent_server.py') +SERVER_NAME = 'biosci_perl_parse_recdescent' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c041a9b282f3d9cafa7e8a8d3604efc2a5d3d857 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-parse-recdescent: + build: . + image: mcp-perl-parse-recdescent:latest + container_name: mcp-perl-parse-recdescent + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-parse-recdescent + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ce3a1c9fdb30ca3c049958bb407c047688974ce1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-parse-recdescent + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-parse-recdescent/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..11b00d60d6b654e70ecebe9d907844c4043df0e7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-path-tiny via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-path-tiny -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-path-tiny_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-path-tiny_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-path-tiny_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/app/perl-path-tiny_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/app/perl-path-tiny_server.py new file mode 100644 index 0000000000000000000000000000000000000000..32d55a2b913a12a7bf66b18fc94a269d82d32a27 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/app/perl-path-tiny_server.py @@ -0,0 +1,249 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +@mcp.tool() +def run_perl_script( + program_file: Optional[Path] = None, + program_string: Optional[List[str]] = None, + program_string_extended: Optional[List[str]] = None, + script_arguments: Optional[List[str]] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debug_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_terminator: Optional[str] = None, + use_modules_M: Optional[List[str]] = None, + use_modules_m: Optional[List[str]] = None, + no_modules_M: Optional[List[str]] = None, + no_modules_m: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + enable_rudimentary_parsing: bool = False, + look_for_programfile_in_path: bool = False, + enable_tainting_warnings: bool = False, + enable_tainting_checks: bool = False, + dump_core_after_parsing: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + shebang_directory: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> dict: + """ + Executes a Perl script or program string with specified Perl interpreter switches. + + This tool wraps the 'perl' interpreter, allowing users to run Perl scripts + and leverage various command-line options. While the tool name is + 'perl-path-tiny', Path::Tiny is a Perl module used *within* Perl scripts, + and does not have its own direct command-line interface. This function + provides the means to execute Perl code that might utilize Path::Tiny. + + Args: + program_file: Path to the Perl program file to execute. + program_string: One or more lines of Perl program code to execute. + Can be specified multiple times via a list. + program_string_extended: Like `program_string`, but enables all optional + Perl features. Can be specified multiple times. + script_arguments: Arguments to pass to the Perl program file or program string. + record_separator: Specify record separator. If an empty string `""`, it defaults to `\0`. + If `None`, no `-0` switch is used. + autosplit: Enable autosplit mode with `-n` or `-p` (splits `$_` into `@F`). + unicode_features: Enables the listed Unicode features (number or list). + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). + debugger: Run program under debugger. Optionally specify debugger name (e.g., `:MyDebugger`). + debug_flags: Set debugging flags (argument is a bit mask or alphabets). + no_sitecustomize: Don't do `$sitelib/sitecustomize.pl` at startup. + split_pattern: `split()` pattern for `-a` switch (e.g., `/pattern/`). + edit_in_place_extension: Edit `<>` files in place. If an extension is supplied + (e.g., `".bak"`), makes a backup. If `""`, edits in place + without backup. If `None`, no `-i` switch is used. + include_directories: Specify `@INC/#include` directory. Can be specified multiple times. + line_terminator: Enable line ending processing. If an empty string `""`, enables + processing with default terminator. If a value (e.g., `"\n"` or octal), + specifies the line terminator. If `None`, no `-l` switch is used. + use_modules_M: Execute "use module..." before executing program, using the `-M` switch. + Can be specified multiple times. + use_modules_m: Execute "use module..." before executing program, using the `-m` switch. + Can be specified multiple times. + no_modules_M: Execute "no module..." before executing program, using the `-M-` switch. + Can be specified multiple times. + no_modules_m: Execute "no module..." before executing program, using the `-m-` switch. + Can be specified multiple times. + loop_around_program: Assume "while (<>) { ... }" loop around program. + loop_and_print: Assume loop like `-n` but print line also, like sed. + enable_rudimentary_parsing: Enable rudimentary parsing for switches after programfile. + look_for_programfile_in_path: Look for programfile using PATH environment variable. + enable_tainting_warnings: Enable tainting warnings. + enable_tainting_checks: Enable tainting checks. + dump_core_after_parsing: Dump core after parsing program. + allow_unsafe_operations: Allow unsafe operations. + print_version: Print Perl version, patchlevel, and license. + print_config_summary: Print configuration summary. Optionally specify a single `Config.pm` variable. + enable_warnings: Enable many useful warnings. + enable_all_warnings: Enable all warnings. + shebang_directory: Ignore text before `#!perl` line. Optionally `cd` to the specified directory. + If `Path(".")` or `Path("")`, ignores text without changing directory. + If `None`, no `-x` switch is used. + disable_all_warnings: Disable all warnings. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + command = ["perl"] + output_files = [] + + # Input validation + if sum([program_file is not None, program_string is not None, program_string_extended is not None]) > 1: + return { + "command_executed": "", + "stdout": "", + "stderr": "Error: Only one of 'program_file', 'program_string', or 'program_string_extended' can be specified.", + "output_files": [], + } + + if program_file and not program_file.is_file(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Program file '{program_file}' does not exist or is not a file.", + "output_files": [], + } + + # Build command based on parameters + if record_separator is not None: + command.append(f"-0{record_separator}") + if autosplit: + command.append("-a") + if unicode_features: + command.append(f"-C{unicode_features}") + if check_syntax_only: + command.append("-c") + if debugger is not None: + command.append(f"-d{debugger}") + if debug_flags: + command.append(f"-D{debug_flags}") + if program_string: + for p_str in program_string: + command.append("-e") + command.append(p_str) + if program_string_extended: + for p_str_ext in program_string_extended: + command.append("-E") + command.append(p_str_ext) + if no_sitecustomize: + command.append("-f") + if split_pattern: + command.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + command.append(f"-i{edit_in_place_extension}") + if include_directories: + for inc_dir in include_directories: + if not inc_dir.is_dir(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Include directory '{inc_dir}' does not exist or is not a directory.", + "output_files": [], + } + command.append(f"-I{inc_dir}") + if line_terminator is not None: + command.append(f"-l{line_terminator}") + + # Module options + if use_modules_M: + for module in use_modules_M: + command.append(f"-M{module}") + if use_modules_m: + for module in use_modules_m: + command.append(f"-m{module}") + if no_modules_M: + for module in no_modules_M: + command.append(f"-M-{module}") + if no_modules_m: + for module in no_modules_m: + command.append(f"-m-{module}") + + if loop_around_program: + command.append("-n") + if loop_and_print: + command.append("-p") + if enable_rudimentary_parsing: + command.append("-s") + if look_for_programfile_in_path: + command.append("-S") + if enable_tainting_warnings: + command.append("-t") + if enable_tainting_checks: + command.append("-T") + if dump_core_after_parsing: + command.append("-u") + if allow_unsafe_operations: + command.append("-U") + if print_version: + command.append("-v") + if print_config_summary is not None: + command.append(f"-V{print_config_summary}") + if enable_warnings: + command.append("-w") + if enable_all_warnings: + command.append("-W") + if shebang_directory is not None: + # If shebang_directory is an empty Path or Path(""), it means -x without argument. + # Otherwise, it's -x . + if str(shebang_directory) != "" and not shebang_directory.is_dir(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Shebang directory '{shebang_directory}' does not exist or is not a directory.", + "output_files": [], + } + command.append(f"-x{shebang_directory}") + if disable_all_warnings: + command.append("-X") + + # Add program file and its arguments + if program_file: + command.append(str(program_file)) + if script_arguments: + command.extend(script_arguments) + + try: + # Ensure all Path objects are converted to strings for subprocess.run + command_str_list = [str(arg) for arg in command] + process = subprocess.run( + command_str_list, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(command_str_list), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command_str_list), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": str(e), + } + except FileNotFoundError: + return { + "command_executed": " ".join(command_str_list), + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "output_files": [], + "error": "Perl executable not found.", + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/app/perl-path-tiny_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/app/perl-path-tiny_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..189c50aa5899453a9bcdcb28003d0f28c558d9ec --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/app/perl-path-tiny_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/app/perl-path-tiny_server.py') +SERVER_NAME = 'biosci_perl_path_tiny' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..824e8243db3777e770dc19a488a5bea3e4943593 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-path-tiny: + build: . + image: mcp-perl-path-tiny:latest + container_name: mcp-perl-path-tiny + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-path-tiny + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7e453f72cf7e4ab0ca83406554ae85a3bac392fd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-path-tiny + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-path-tiny/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8a248b85f423abad7b4be76017571a372d9c653e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-pathtools via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-pathtools -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-pathtools_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-pathtools_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-pathtools_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/app/perl-pathtools_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/app/perl-pathtools_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b24d1e619023229704255fd50cd0f867c8761ac9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/app/perl-pathtools_server.py @@ -0,0 +1,257 @@ +import subprocess +from typing import Optional, List +from pathlib import Path + +@mcp.tool() +def pathtools_canonpath(path: str): + """ + No-op cleanup of a path. Logical cleanup of a path, such as eliminating + successive path separators and directory traversals (e.g., /foo/../bar -> /bar). + """ + try: + cmd = ["perl", "-MFile::Spec", "-e", "print File::Spec->canonpath($ARGV[0])", path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "canonical_path": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def pathtools_catdir(directories: List[str]): + """ + Concatenate two or more directory names to form a complete path ending with a directory. + In Perl: File::Spec->catdir(@directories) + """ + if not directories: + return {"error": "The directories list cannot be empty."} + + try: + cmd = ["perl", "-MFile::Spec", "-e", "print File::Spec->catdir(@ARGV)"] + directories + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "directory_path": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def pathtools_catfile(directories: List[str], filename: str): + """ + Concatenate one or more directory names and a filename to form a complete path. + In Perl: File::Spec->catfile(@directories, $filename) + """ + try: + args = directories + [filename] + cmd = ["perl", "-MFile::Spec", "-e", "print File::Spec->catfile(@ARGV)"] + args + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "file_path": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def pathtools_abs2rel(path: str, base: Optional[str] = None): + """ + Takes a destination path and an optional base path and returns a relative path + from the base to the destination. + """ + try: + perl_code = "print File::Spec->abs2rel($ARGV[0], $ARGV[1])" + args = [path, base] if base else [path, ""] + + cmd = ["perl", "-MFile::Spec", "-e", perl_code] + args + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "relative_path": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def pathtools_rel2abs(path: str, base: Optional[str] = None): + """ + Converts a relative path to an absolute path. + If base is not specified, the current working directory is used. + """ + try: + perl_code = "print File::Spec->rel2abs($ARGV[0], $ARGV[1])" + args = [path, base] if base else [path, ""] + + cmd = ["perl", "-MFile::Spec", "-e", perl_code] + args + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "absolute_path": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def pathtools_splitpath(path: str, no_file: bool = False): + """ + Splits a path into volume, directory, and filename portions. + On systems with no concept of volume, returns an empty string for volume. + """ + try: + # Perl splitpath returns (volume, directory, file) + # no_file=True means the path is a directory and the file part will be empty + no_file_int = 1 if no_file else 0 + perl_code = f"my @res = File::Spec->splitpath($ARGV[0], {no_file_int}); print join('|', @res)" + + cmd = ["perl", "-MFile::Spec", "-e", perl_code, path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + parts = result.stdout.strip().split('|') + return { + "command_executed": " ".join(cmd), + "volume": parts[0] if len(parts) > 0 else "", + "directory": parts[1] if len(parts) > 1 else "", + "file": parts[2] if len(parts) > 2 else "", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def pathtools_cwd(): + """ + Gets the current working directory using the Cwd module. + """ + try: + cmd = ["perl", "-MCwd", "-e", "print Cwd::cwd()"] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "cwd": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def pathtools_abs_path(path: str): + """ + Returns the canonicalized absolute pathname. + This resolves all symbolic links, extra ``/'' characters, and references + to /./ and /../ in the input path. + """ + # Validate path exists for abs_path as it usually requires physical existence + path_obj = Path(path) + + try: + cmd = ["perl", "-MCwd", "-e", "print Cwd::abs_path($ARGV[0])", path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "absolute_path": result.stdout.strip(), + "exists": path_obj.exists(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def pathtools_file_name_is_absolute(path: str): + """ + Takes as argument a path and returns true if it is an absolute path. + """ + try: + # Perl returns 1 for true, empty string for false + cmd = ["perl", "-MFile::Spec", "-e", "print File::Spec->file_name_is_absolute($ARGV[0]) ? 'true' : 'false'", path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + is_absolute = result.stdout.strip() == "true" + + return { + "command_executed": " ".join(cmd), + "is_absolute": is_absolute, + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def pathtools_tmpdir(): + """ + Returns a string representation of the first writable directory found + which is suitable for temporary files. + """ + try: + cmd = ["perl", "-MFile::Spec", "-e", "print File::Spec->tmpdir()"] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "tmpdir": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/app/perl-pathtools_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/app/perl-pathtools_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..35522d432f314adcc08e82664d46979189ced9c1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/app/perl-pathtools_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/app/perl-pathtools_server.py') +SERVER_NAME = 'biosci_perl_pathtools' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..75ea5e6e510e975f45e2657e1c399bf8798efa1a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-pathtools: + build: . + image: mcp-perl-pathtools:latest + container_name: mcp-perl-pathtools + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-pathtools + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2189f90b16b4827b5c9325fb19f8b24200b26355 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-pathtools + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pathtools/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..08f318701990d8bfea24312f56678eb162d68e3e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-pdf-api2 via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-pdf-api2 -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-pdf-api2_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-pdf-api2_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-pdf-api2_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/app/perl-pdf-api2_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/app/perl-pdf-api2_server.py new file mode 100644 index 0000000000000000000000000000000000000000..80b243d90533dcccd59b0b9685930804343adf1a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/app/perl-pdf-api2_server.py @@ -0,0 +1,304 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any +import tempfile + +@mcp.tool() +def pdf_api2_merge_pdfs( + input_pdfs: List[str], + output_pdf: str, +) -> Dict[str, Any]: + """ + Merge multiple PDF files into a single PDF file using PDF::API2. + + Args: + input_pdfs: List of paths to the input PDF files in the order they should be merged. + output_pdf: Path where the merged PDF will be saved. + """ + # Input validation + if not input_pdfs: + return {"error": "No input PDF files provided."} + + valid_inputs = [] + for p in input_pdfs: + path = Path(p) + if not path.exists(): + return {"error": f"Input file does not exist: {p}"} + valid_inputs.append(str(path.absolute())) + + output_path = Path(output_pdf).absolute() + + # Perl script to perform the merge + perl_script = """ +use PDF::API2; +my $pdf_out = PDF::API2->new(); +foreach my $file (@ARGV) { + my $pdf_in = PDF::API2->open($file); + foreach my $n (1 .. $pdf_in->pages()) { + $pdf_out->import_page($pdf_in, $n); + } +} +$pdf_out->save($ENV{OUTPUT_FILE}); +""" + + env = {"OUTPUT_FILE": str(output_path)} + + try: + result = subprocess.run( + ["perl", "-MPDF::API2", "-e", perl_script] + valid_inputs, + capture_output=True, + text=True, + check=True, + env=env + ) + return { + "command_executed": f"perl -MPDF::API2 -e '...' {' '.join(valid_inputs)}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to merge PDFs", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +@mcp.tool() +def pdf_api2_extract_pages( + input_pdf: str, + output_pdf: str, + pages: str, +) -> Dict[str, Any]: + """ + Extract specific pages or ranges from a PDF file. + + Args: + input_pdf: Path to the source PDF file. + output_pdf: Path where the extracted pages will be saved. + pages: Comma-separated list of pages or ranges (e.g., "1,3,5-10,12"). + """ + input_path = Path(input_pdf) + if not input_path.exists(): + return {"error": f"Input file does not exist: {input_pdf}"} + + output_path = Path(output_pdf).absolute() + + # Perl script to handle page ranges and extraction + perl_script = """ +use PDF::API2; +my $input_file = shift @ARGV; +my $output_file = shift @ARGV; +my $range_str = shift @ARGV; + +my $pdf_in = PDF::API2->open($input_file); +my $pdf_out = PDF::API2->new(); + +my @parts = split(',', $range_str); +foreach my $part (@parts) { + if ($part =~ /^(\\d+)-(\\d+)$/) { + foreach my $n ($1 .. $2) { + $pdf_out->import_page($pdf_in, $n) if $n <= $pdf_in->pages(); + } + } elsif ($part =~ /^(\\d+)$/) { + $pdf_out->import_page($pdf_in, $1) if $1 <= $pdf_in->pages(); + } +} +$pdf_out->save($output_file); +""" + + try: + result = subprocess.run( + ["perl", "-MPDF::API2", "-e", perl_script, str(input_path.absolute()), str(output_path), pages], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"perl -MPDF::API2 -e '...' {input_pdf} {output_pdf} {pages}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to extract pages", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +@mcp.tool() +def pdf_api2_get_info( + input_pdf: str, +) -> Dict[str, Any]: + """ + Retrieve metadata and page count from a PDF file. + + Args: + input_pdf: Path to the PDF file to inspect. + """ + input_path = Path(input_pdf) + if not input_path.exists(): + return {"error": f"Input file does not exist: {input_pdf}"} + + perl_script = """ +use PDF::API2; +use JSON::PP; +my $pdf = PDF::API2->open($ARGV[0]); +my %info = $pdf->info(); +$info{Pages} = $pdf->pages(); +print encode_json(\\%info); +""" + + try: + result = subprocess.run( + ["perl", "-MPDF::API2", "-MJSON::PP", "-e", perl_script, str(input_path.absolute())], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"perl -MPDF::API2 -e '...' {input_pdf}", + "metadata": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to retrieve PDF info", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def pdf_api2_add_text_watermark( + input_pdf: str, + output_pdf: str, + text: str, + page_number: int = 1, + x_position: float = 100.0, + y_position: float = 100.0, + font_size: int = 20, +) -> Dict[str, Any]: + """ + Add a simple text string to a specific page of a PDF. + + Args: + input_pdf: Path to the source PDF. + output_pdf: Path to save the modified PDF. + text: The text to add. + page_number: The page number to add text to (1-indexed). + x_position: X coordinate (points) from the bottom-left. + y_position: Y coordinate (points) from the bottom-left. + font_size: Size of the font. + """ + input_path = Path(input_pdf) + if not input_path.exists(): + return {"error": f"Input file does not exist: {input_pdf}"} + + output_path = Path(output_pdf).absolute() + + perl_script = """ +use PDF::API2; +my ($in, $out, $txt, $pg, $x, $y, $size) = @ARGV; +my $pdf = PDF::API2->open($in); +my $page = $pdf->open_page($pg); +my $font = $pdf->font('Helvetica'); +my $content = $page->text(); +$content->font($font, $size); +$content->translate($x, $y); +$content->text($txt); +$pdf->save($out); +""" + + try: + result = subprocess.run( + [ + "perl", "-MPDF::API2", "-e", perl_script, + str(input_path.absolute()), + str(output_path), + text, + str(page_number), + str(x_position), + str(y_position), + str(font_size) + ], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "perl -MPDF::API2 -e '...'", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to add text to PDF", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def pdf_api2_custom_script( + script_content: str, + args: List[str] = [], +) -> Dict[str, Any]: + """ + Execute a custom Perl script using the PDF::API2 library. + The script should assume 'use PDF::API2;' is already available if requested, + but it is safer to include it in the script_content. + + Args: + script_content: The full Perl code to execute. + args: Optional list of command line arguments to pass to the script. + """ + with tempfile.NamedTemporaryFile(mode='w', suffix='.pl', delete=False) as tmp: + tmp.write(script_content) + tmp_path = tmp.name + + try: + result = subprocess.run( + ["perl", "-MPDF::API2", tmp_path] + args, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"perl {tmp_path} {' '.join(args)}", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Custom Perl script execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + finally: + if Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def pdf_api2_check_version() -> Dict[str, Any]: + """ + Check the installed version of the PDF::API2 Perl module. + """ + try: + result = subprocess.run( + ["perl", "-MPDF::API2", "-e", "print $PDF::API2::VERSION"], + capture_output=True, + text=True, + check=True + ) + return { + "pdf_api2_version": result.stdout.strip(), + "perl_version": subprocess.run(["perl", "-e", "print $^V"], capture_output=True, text=True).stdout + } + except subprocess.CalledProcessError as e: + return { + "error": "PDF::API2 is not installed or not found in @INC", + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/app/perl-pdf-api2_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/app/perl-pdf-api2_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8259f1be56256e5957bb67f0b0d9849185996ef6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/app/perl-pdf-api2_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/app/perl-pdf-api2_server.py') +SERVER_NAME = 'biosci_perl_pdf_api2' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f7f11daa62657731eebcb6694568870fa64e46ca --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-pdf-api2: + build: . + image: mcp-perl-pdf-api2:latest + container_name: mcp-perl-pdf-api2 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-pdf-api2 + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9a0ddf3c63bd07c8b4db72b0822f0913ca7ac896 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-pdf-api2 + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pdf-api2/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5e527cb3f3a8a472beaeba9d181b867d20073881 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-perlio-gzip via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-perlio-gzip -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-perlio-gzip_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-perlio-gzip_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-perlio-gzip_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/app/perl-perlio-gzip_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/app/perl-perlio-gzip_server.py new file mode 100644 index 0000000000000000000000000000000000000000..28622a061fece4ae7eb8c10046e5e2ae2d69fbf9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/app/perl-perlio-gzip_server.py @@ -0,0 +1,176 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# In a real MCP environment, this would be imported. +# This is a placeholder for the actual decorator. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +@mcp.tool() +def run_perl_script( + program_file: Optional[Path] = None, + program_string: Optional[str] = None, + program_string_extended: Optional[str] = None, + arguments: Optional[List[str]] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + autosplit_mode: bool = False, + split_pattern: Optional[str] = None, + in_place_edit_backup_ext: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + enable_line_ending_processing: bool = False, + use_modules: Optional[List[str]] = None, + no_modules: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + enable_switch_parsing: bool = False, + search_path: bool = False, + enable_tainting_warnings: bool = False, + enable_tainting_checks: bool = False, + allow_unsafe_operations: bool = False, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + print_version: bool = False, + print_config: Optional[str] = None, +) -> Dict[str, Any]: + """ + Executes a Perl script using the perl interpreter. + + This tool is a wrapper for the 'perl' command-line interpreter. The 'perl-perlio-gzip' + package is a Perl module, not a standalone executable. It provides an I/O layer for + handling gzip/gunzip compression within a Perl script (e.g., by using 'use PerlIO::gzip;'). + To use it, provide a Perl script via 'program_file' or 'program_string' that utilizes this module. + + Args: + program_file: Path to the Perl program file to execute. + program_string: A one-line Perl program to execute (passed via -e). + program_string_extended: Like 'program_string', but enables all optional features (passed via -E). + arguments: A list of arguments to pass to the Perl script. + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). Corresponds to -c. + debugger: Run the program under the specified debugger. Pass an empty string for the default debugger (-d). + debugging_flags: Set debugging flags (argument is a bit mask or alphabets). Corresponds to -D. + autosplit_mode: Enable autosplit mode with -n or -p (splits $_ into @F). Corresponds to -a. + split_pattern: The pattern to use for splitting in autosplit mode. Requires 'autosplit_mode'. Corresponds to -F. + in_place_edit_backup_ext: Edit files in place. If an extension is supplied (e.g., '.bak'), a backup is made. Corresponds to -i. + include_directories: A list of directories to add to @INC. Corresponds to -I. + enable_line_ending_processing: Enable line ending processing. Corresponds to -l. + use_modules: A list of modules to 'use' before executing the program. Corresponds to -M. + no_modules: A list of modules to 'no' before executing the program. Corresponds to -m. + loop_around_program: Assume a "while (<>) { ... }" loop around the program. Corresponds to -n. + loop_and_print: Assume a loop like -n but also print the line. Corresponds to -p. + enable_switch_parsing: Enable rudimentary parsing for switches after the program file. Corresponds to -s. + search_path: Look for the program file using the PATH environment variable. Corresponds to -S. + enable_tainting_warnings: Enable tainting warnings. Corresponds to -t. + enable_tainting_checks: Enable tainting checks. Corresponds to -T. + allow_unsafe_operations: Allow unsafe operations. Corresponds to -U. + enable_warnings: Enable many useful warnings. Corresponds to -w. + enable_all_warnings: Enable all warnings. Corresponds to -W. + disable_all_warnings: Disable all warnings. Corresponds to -X. + print_version: Print version, patchlevel, and license. Corresponds to -v. + print_config: Print configuration summary. Pass a variable name to see a single Config.pm variable, or an empty string for the full summary. Corresponds to -V. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + source_options = [program_file, program_string, program_string_extended, print_version, print_config is not None] + if sum(1 for opt in source_options if opt) > 1: + raise ValueError("Only one of 'program_file', 'program_string', 'program_string_extended', 'print_version', or 'print_config' can be specified.") + if not any(source_options): + raise ValueError("One of 'program_file', 'program_string', 'program_string_extended', 'print_version', or 'print_config' must be provided.") + + if program_file and not program_file.is_file(): + raise FileNotFoundError(f"Program file not found: {program_file}") + + if include_directories: + for directory in include_directories: + if not directory.is_dir(): + raise NotADirectoryError(f"Include directory not found: {directory}") + + if split_pattern and not autosplit_mode: + raise ValueError("'split_pattern' can only be used when 'autosplit_mode' is True.") + + if loop_around_program and loop_and_print: + raise ValueError("'loop_around_program' (-n) and 'loop_and_print' (-p) are mutually exclusive.") + + # --- Command Construction --- + cmd = ["perl"] + + if check_syntax_only: cmd.append("-c") + if debugger is not None: cmd.append(f"-d:{debugger}" if debugger else "-d") + if debugging_flags: cmd.append(f"-D{debugging_flags}") + if autosplit_mode: cmd.append("-a") + if split_pattern: cmd.extend(["-F", split_pattern]) + if in_place_edit_backup_ext is not None: cmd.append(f"-i{in_place_edit_backup_ext}") + if include_directories: + for directory in include_directories: cmd.extend(["-I", str(directory)]) + if enable_line_ending_processing: cmd.append("-l") + if use_modules: + for module in use_modules: cmd.append(f"-M{module}") + if no_modules: + for module in no_modules: cmd.append(f"-m{module}") + if loop_around_program: cmd.append("-n") + if loop_and_print: cmd.append("-p") + if enable_switch_parsing: cmd.append("-s") + if search_path: cmd.append("-S") + if enable_tainting_warnings: cmd.append("-t") + if enable_tainting_checks: cmd.append("-T") + if allow_unsafe_operations: cmd.append("-U") + if enable_warnings: cmd.append("-w") + if enable_all_warnings: cmd.append("-W") + if disable_all_warnings: cmd.append("-X") + if print_version: cmd.append("-v") + if print_config is not None: cmd.append(f"-V:{print_config}" if print_config else "-V") + + if program_string: cmd.extend(["-e", program_string]) + elif program_string_extended: cmd.extend(["-E", program_string_extended]) + elif program_file: cmd.append(str(program_file)) + + if arguments: + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=False, # Perl scripts can exit with non-zero status on success (e.g., die) + ) + stdout = result.stdout + stderr = result.stderr + + if result.returncode != 0 and not check_syntax_only: + # For syntax check, non-zero can mean failure. For regular runs, it might be intended. + # We will return the output but let the user decide if it's an error. + # A more robust solution might check specific error patterns in stderr. + pass + + except FileNotFoundError: + raise RuntimeError("Perl executable not found. Please ensure 'perl' is in your system's PATH.") + except subprocess.CalledProcessError as e: + # This block is less likely to be hit with check=False, but kept for robustness. + return { + "error": "Perl script execution failed.", + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + + # --- Structured Result Return --- + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "return_code": result.returncode, + "output_files": [] # Perl scripts might create files, but we can't know them beforehand. + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/app/perl-perlio-gzip_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/app/perl-perlio-gzip_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0efbc5312bcbf514eaf3e46405f413944857b78d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/app/perl-perlio-gzip_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/app/perl-perlio-gzip_server.py') +SERVER_NAME = 'biosci_perl_perlio_gzip' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..bb5ea14fd375728aef216960210463ecbee62d6c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-perlio-gzip: + build: . + image: mcp-perl-perlio-gzip:latest + container_name: mcp-perl-perlio-gzip + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-perlio-gzip + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2cf4fd920c48edbdca6a64e0f46653a7e2bb32c7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-perlio-gzip + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-perlio-gzip/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7ad644bd6a34be129a6c4253b75f5fa224205512 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-pod-escapes via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-pod-escapes -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-pod-escapes_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-pod-escapes_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-pod-escapes_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/app/perl-pod-escapes_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/app/perl-pod-escapes_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2dbf356377a38cb8d6372b69ddbffec1c5818751 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/app/perl-pod-escapes_server.py @@ -0,0 +1,240 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +# No need to import mcp, as per instructions. + +@mcp.tool() +def perl_pod_escapes( + program_file: Optional[Path] = None, + program_arguments: Optional[List[str]] = None, + record_separator_octal: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debug_mode: Optional[str] = None, + debugging_flags: Optional[str] = None, + execute_program_string: Optional[List[str]] = None, + execute_program_string_extended: Optional[List[str]] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + module_operations: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + rudimentary_switch_parsing: bool = False, + search_path_for_program: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core_on_parse: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang: Optional[str] = None, + disable_all_warnings: bool = False, +) -> Dict[str, Any]: + """ + Executes the Perl interpreter with specified options, running a Perl script + or one-liner. + + This tool provides access to the command-line switches of the 'perl' + interpreter, allowing for flexible execution of Perl programs. + Note: The tool name 'perl_pod_escapes' is used as per the prompt, + but this function actually wraps the 'perl' interpreter. + + Args: + program_file: Path to the Perl script to execute. Required if no + `execute_program_string` or `execute_program_string_extended` + is provided. + program_arguments: Arguments to pass to the Perl script. + record_separator_octal: Specify record separator (e.g., '0' for NUL, '0777' for paragraph mode). + Pass an empty string ('') for just '-0'. + autosplit: Enable autosplit mode with -n or -p (splits $_ into @F). + unicode_features: Enables listed Unicode features (e.g., 'io' for UTF-8 I/O). + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). + debug_mode: Run program under debugger. Optionally specify debugger (e.g., ':MyDebugger'). + debugging_flags: Set debugging flags (argument is a bit mask or alphabets). + execute_program_string: One line of program (can be specified multiple times). + execute_program_string_extended: Like -e, but enables all optional features (can be specified multiple times). + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. + split_pattern: split() pattern for -a switch (e.g., '/\\t/'). + edit_in_place_extension: Edit <> files in place. Makes backup if extension supplied (e.g., '.bak'). + Pass an empty string ('') for just '-i'. + include_directories: Specify @INC/#include directory (can be specified multiple times). + line_ending_processing: Enable line ending processing, specifies line terminator (e.g., '0' for chomp). + Pass an empty string ('') for just '-l'. + module_operations: Execute "use/no module..." before executing program (e.g., 'strict', '-warnings'). + Can be specified multiple times. If a module name is provided without '-M' or '-m' prefix, + '-M' will be prepended by default. + loop_around_program: Assume "while (<>) { ... }" loop around program. + loop_and_print: Assume loop like -n but print line also, like sed. + rudimentary_switch_parsing: Enable rudimentary parsing for switches after programfile. + search_path_for_program: Look for programfile using PATH environment variable. + tainting_warnings: Enable tainting warnings. + tainting_checks: Enable tainting checks. + dump_core_on_parse: Dump core after parsing program. + allow_unsafe_operations: Allow unsafe operations. + print_version: Print version, patchlevel and license. + print_config_summary: Print configuration summary (or a single Config.pm variable, e.g., 'archname'). + Pass an empty string ('') for just '-V'. + enable_warnings: Enable many useful warnings. + enable_all_warnings: Enable all warnings. + ignore_text_before_shebang: Ignore text before #!perl line (optionally cd to directory). + Pass an empty string ('') for just '-x'. If a directory is provided, + Perl will cd to that directory before running the script. + disable_all_warnings: Disable all warnings. + """ + command = ["perl"] + output_files: List[Path] = [] + + # Input validation + if not program_file and not execute_program_string and not execute_program_string_extended: + raise ValueError("Either 'program_file' or at least one of " + "'execute_program_string' or 'execute_program_string_extended' must be provided.") + + if program_file and not program_file.is_file(): + raise FileNotFoundError(f"Program file not found: {program_file}") + + if loop_around_program and loop_and_print: + raise ValueError("Options '-n' (loop_around_program) and '-p' (loop_and_print) are mutually exclusive.") + + warning_flags_set = sum([enable_warnings, enable_all_warnings, disable_all_warnings]) + if warning_flags_set > 1: + raise ValueError("Only one of '-w' (enable_warnings), '-W' (enable_all_warnings), " + "or '-X' (disable_all_warnings) can be set.") + + if include_directories: + for d in include_directories: + if not d.is_dir(): + raise NotADirectoryError(f"Include directory not found: {d}") + + if ignore_text_before_shebang is not None and ignore_text_before_shebang != "": + dir_path = Path(ignore_text_before_shebang) + if not dir_path.is_dir(): + raise NotADirectoryError(f"Directory for -x option not found: {dir_path}") + + # Build command + if record_separator_octal is not None: + command.append(f"-0{record_separator_octal}") + if autosplit: + command.append("-a") + if unicode_features is not None: + command.append(f"-C{unicode_features}") + if check_syntax_only: + command.append("-c") + if debug_mode is not None: + command.append(f"-d{debug_mode}") + if debugging_flags is not None: + command.append(f"-D{debugging_flags}") + if execute_program_string: + for prog_str in execute_program_string: + command.extend(["-e", prog_str]) + if execute_program_string_extended: + for prog_str in execute_program_string_extended: + command.extend(["-E", prog_str]) + if no_sitecustomize: + command.append("-f") + if split_pattern is not None: + command.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + command.append(f"-i{edit_in_place_extension}") + # If -i is used and program_arguments are files, they are modified. + if program_arguments: + for arg in program_arguments: + arg_path = Path(arg) + # Only add existing files to output_files, as non-existent files + # would typically be created by the script, not modified in-place. + if arg_path.is_file(): + output_files.append(arg_path) + if include_directories: + for d in include_directories: + command.extend(["-I", str(d)]) + if line_ending_processing is not None: + command.append(f"-l{line_ending_processing}") + if module_operations: + for mod_op in module_operations: + # If the user provides the full flag (e.g., '-Mstrict'), use it directly. + # Otherwise, default to '-M'. + if mod_op.startswith('-M') or mod_op.startswith('-m'): + command.append(mod_op) + else: + command.append(f"-M{mod_op}") + if loop_around_program: + command.append("-n") + if loop_and_print: + command.append("-p") + if rudimentary_switch_parsing: + command.append("-s") + if search_path_for_program: + command.append("-S") + if tainting_warnings: + command.append("-t") + if tainting_checks: + command.append("-T") + if dump_core_on_parse: + command.append("-u") + if allow_unsafe_operations: + command.append("-U") + if print_version: + command.append("-v") + if print_config_summary is not None: + command.append(f"-V{print_config_summary}") + if enable_warnings: + command.append("-w") + if enable_all_warnings: + command.append("-W") + if ignore_text_before_shebang is not None: + command.append(f"-x{ignore_text_before_shebang}") + if disable_all_warnings: + command.append("-X") + + # Add program file and arguments + if program_file: + # Add '--' if there are program arguments to prevent misinterpretation of arguments as perl switches + if program_arguments: + command.append("--") + command.append(str(program_file)) + + if program_arguments: + command.extend(program_arguments) + + # Execute command + command_executed = " ".join(map(str, command)) + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = result.stdout + stderr = result.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "error": "Perl executable not found", + "returncode": 127, + "output_files": [] + } + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/app/perl-pod-escapes_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/app/perl-pod-escapes_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d153ffe73deeb4b4afcb142217c689aa300b8960 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/app/perl-pod-escapes_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/app/perl-pod-escapes_server.py') +SERVER_NAME = 'biosci_perl_pod_escapes' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..9f2efc1a4a764c8a94133d66afad60897554bdab --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-pod-escapes: + build: . + image: mcp-perl-pod-escapes:latest + container_name: mcp-perl-pod-escapes + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-pod-escapes + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f567f0c5a2c9e1a479b18d7bcf1abe981a9f3766 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-pod-escapes + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-escapes/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c66f8434c32382a3c2b5da7ec45dccbc31b4872e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-pod-usage via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-pod-usage -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-pod-usage_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-pod-usage_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-pod-usage_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/app/perl-pod-usage_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/app/perl-pod-usage_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a67d45b16329ce2e72000057fa1869a68224eb7e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/app/perl-pod-usage_server.py @@ -0,0 +1,132 @@ +import subprocess +from pathlib import Path +from typing import Optional, Dict, Any + +# In a real MCP environment, the @mcp.tool decorator would be provided by the framework. +# This is a placeholder for demonstration. +def tool(*args, **kwargs): + def decorator(f): + return f + return decorator + +class mcp: + tool = tool + +@mcp.tool() +def pod_usage( + input_file: Path, + message: Optional[str] = None, + verbose: int = 1, + sections: Optional[str] = None, + no_perldoc: bool = False, + output_to_stderr: bool = False, +) -> Dict[str, Any]: + """ + Extracts and prints a usage message from POD (Plain Old Documentation) + embedded within a Perl script. This tool is a wrapper around Perl's + Pod::Usage module, which is provided by the 'perl-pod-usage' conda package. + + Args: + input_file: Path to the Perl script containing POD documentation. + message: An optional message to print before the usage text. + verbose: Verbosity level of the usage message. + 0: Prints only the SYNOPSIS section. + 1: Prints SYNOPSIS and OPTIONS sections (default). + 2: Prints the entire man page. + 99: Used with the 'sections' parameter to specify custom sections. + sections: A pipe-delimited string of POD section titles to display + (e.g., "SYNOPSIS|OPTIONS"). Requires 'verbose' to be 99. + no_perldoc: If True, do not use the 'perldoc' command to format the + output, even for high verbosity levels. + output_to_stderr: If True, directs the usage message to stderr. + Otherwise, it goes to stdout. + + Returns: + A dictionary containing the command executed, stdout, stderr, + and a list of output files (always empty for this tool). + """ + # 1. Input validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + if verbose not in [0, 1, 2, 99]: + raise ValueError("The 'verbose' parameter must be one of 0, 1, 2, or 99.") + + if sections and verbose != 99: + raise ValueError("The 'sections' parameter can only be used when 'verbose' is set to 99.") + + # 2. Command construction + # We build a list of arguments for the pod2usage function in Perl. + perl_args = [] + perl_args.append(f"'-input' => '{str(input_file)}'") + perl_args.append(f"'-verbose' => {verbose}") + + # The pod2usage function exits by default. We use 'NOEXIT' to prevent this + # and allow us to capture the output from the subprocess call. + perl_args.append("'-exitval' => 'NOEXIT'") + + if message: + # Escape single quotes for the Perl string literal + escaped_message = message.replace("'", "\\'") + perl_args.append(f"'-msg' => '{escaped_message}'") + + if output_to_stderr: + perl_args.append("'-output' => \\*STDERR") + else: + perl_args.append("'-output' => \\*STDOUT") + + if sections: + escaped_sections = sections.replace("'", "\\'") + perl_args.append(f"'-sections' => '{escaped_sections}'") + + if no_perldoc: + perl_args.append("'-noperldoc' => 1") + + perl_hash_str = ", ".join(perl_args) + perl_script = f"use Pod::Usage; pod2usage({{{perl_hash_str}}});" + + command = ["perl", "-e", perl_script] + command_str = " ".join(command) + + # 3. Subprocess execution and error handling + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=False, # Manually check return code for better error reporting + ) + + if result.returncode != 0: + # Pod::Usage can fail if the input file has no POD, for example. + # The error message goes to stderr. + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "error": f"Perl execution failed with return code {result.returncode}.", + "output_files": [], + } + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: 'perl' command not found. Is Perl installed and in the system's PATH?", + "error": "Command not found.", + "output_files": [], + } + except Exception as e: + return { + "command_executed": command_str, + "stdout": "", + "stderr": str(e), + "error": "An unexpected error occurred during subprocess execution.", + "output_files": [], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/app/perl-pod-usage_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/app/perl-pod-usage_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..55ca2985b336ba195d29359d351ddadb0080a92f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/app/perl-pod-usage_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/app/perl-pod-usage_server.py') +SERVER_NAME = 'biosci_perl_pod_usage' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3052599ef8b79ab1571aba5e57408d64b5473214 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-pod-usage: + build: . + image: mcp-perl-pod-usage:latest + container_name: mcp-perl-pod-usage + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-pod-usage + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..442396d815afccf5484cc0b3194f67b42034c8a1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-pod-usage + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-pod-usage/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1d21cbea4ac5fce8270879b9a71c76034235224b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-postscript via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-postscript -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-postscript_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-postscript_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-postscript_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/app/perl-postscript_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/app/perl-postscript_server.py new file mode 100644 index 0000000000000000000000000000000000000000..84670bf1f1394e3a9244b5e30d7a171fc6d218d4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/app/perl-postscript_server.py @@ -0,0 +1,239 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +@mcp.tool() +def perl_postscript_execute( + script_path: Optional[str] = None, + one_liner: Optional[str] = None, + modules: Optional[List[str]] = None, + include_paths: Optional[List[str]] = None, + autosplit: bool = False, + split_pattern: Optional[str] = None, + warnings: bool = True, + all_warnings: bool = False, + taint_check: bool = False, + inplace_extension: Optional[str] = None, + line_ending_processing: bool = False, + assume_loop_n: bool = False, + assume_loop_p: bool = False, + script_args: Optional[List[str]] = None, +): + """ + Execute a Perl script or one-liner using the perl interpreter. + This tool is part of the perl-postscript package, which provides PostScript::TextBlock support. + + Args: + script_path: Path to the Perl script file (.pl) to execute. + one_liner: A string containing Perl code to execute (equivalent to -e). + modules: List of modules to load (equivalent to -M). e.g., ["PostScript::TextBlock"] + include_paths: List of directories to add to @INC (equivalent to -I). + autosplit: Enable autosplit mode with -n or -p (equivalent to -a). + split_pattern: Pattern for -a switch (equivalent to -F). + warnings: Enable useful warnings (equivalent to -w). + all_warnings: Enable all warnings (equivalent to -W). + taint_check: Enable taint checks (equivalent to -T). + inplace_extension: Edit files in place, optionally providing a backup extension (equivalent to -i). + line_ending_processing: Enable line ending processing (equivalent to -l). + assume_loop_n: Assume "while (<>) { ... }" loop around program (equivalent to -n). + assume_loop_p: Assume loop like -n but print line also (equivalent to -p). + script_args: Arguments to pass to the Perl script. + """ + cmd = ["perl"] + + # Flags + if all_warnings: + cmd.append("-W") + elif warnings: + cmd.append("-w") + + if taint_check: + cmd.append("-T") + + if autosplit: + cmd.append("-a") + + if split_pattern: + cmd.append(f"-F{split_pattern}") + + if inplace_extension is not None: + cmd.append(f"-i{inplace_extension}") + + if line_ending_processing: + cmd.append("-l") + + if assume_loop_n: + cmd.append("-n") + + if assume_loop_p: + cmd.append("-p") + + # Include paths + if include_paths: + for path in include_paths: + cmd.append(f"-I{path}") + + # Modules + if modules: + for module in modules: + cmd.append(f"-M{module}") + + # Execution source + if one_liner and script_path: + raise ValueError("Provide either 'one_liner' or 'script_path', not both.") + + if one_liner: + cmd.extend(["-e", one_liner]) + elif script_path: + p = Path(script_path) + if not p.exists(): + return {"error": f"Script file not found: {script_path}"} + cmd.append(str(p)) + else: + # If neither is provided, we might just be checking version or similar, + # but this function is for execution. + raise ValueError("Either 'one_liner' or 'script_path' must be provided.") + + # Script arguments + if script_args: + cmd.extend(script_args) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def perl_postscript_check_syntax( + script_path: str, + include_paths: Optional[List[str]] = None, + modules: Optional[List[str]] = None, +): + """ + Check the syntax of a Perl script without executing it (equivalent to perl -c). + + Args: + script_path: Path to the Perl script to check. + include_paths: List of directories to add to @INC. + modules: List of modules to load before checking. + """ + p = Path(script_path) + if not p.exists(): + return {"error": f"File not found: {script_path}"} + + cmd = ["perl", "-c"] + + if include_paths: + for path in include_paths: + cmd.append(f"-I{path}") + + if modules: + for module in modules: + cmd.append(f"-M{module}") + + cmd.append(str(p)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "syntax_ok" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Syntax check failed", + "status": "syntax_error" + } + +@mcp.tool() +def perl_postscript_get_info( + config_variable: Optional[str] = None, + show_version: bool = True, +): + """ + Get Perl version information or configuration details. + + Args: + config_variable: Specific configuration variable to print (equivalent to perl -V:variable). + show_version: Print version and patchlevel (equivalent to perl -v). + """ + if config_variable: + cmd = ["perl", f"-V:{config_variable}"] + elif show_version: + cmd = ["perl", "-v"] + else: + cmd = ["perl", "-V"] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stderr": e.stderr + } + +@mcp.tool() +def perl_postscript_debug_script( + script_path: str, + debugger: Optional[str] = None, + script_args: Optional[List[str]] = None, +): + """ + Run a Perl script under the debugger (equivalent to perl -d). + Note: This is primarily for non-interactive syntax/logic validation in this context. + + Args: + script_path: Path to the Perl script. + debugger: Specific debugger to use (e.g., 'ptkdb'). + script_args: Arguments for the script. + """ + p = Path(script_path) + if not p.exists(): + return {"error": f"File not found: {script_path}"} + + debug_flag = f"-d:{debugger}" if debugger else "-d" + cmd = ["perl", debug_flag, str(p)] + + if script_args: + cmd.extend(script_args) + + try: + # Debugging might require stdin, but in a tool context we capture output + result = subprocess.run(cmd, capture_output=True, text=True, timeout=30) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "info": "Debugger session terminated or timed out." + } + except subprocess.TimeoutExpired: + return {"error": "Debugger session timed out (interactive sessions not supported via MCP tool directly)."} + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stderr": e.stderr, + "error": str(e) + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/app/perl-postscript_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/app/perl-postscript_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..81900cb298a4c2987f1175606ac997f396b25415 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/app/perl-postscript_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/app/perl-postscript_server.py') +SERVER_NAME = 'biosci_perl_postscript' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..39cf53b545e2dbe0213f298eaca841ba73ed0f3d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-postscript: + build: . + image: mcp-perl-postscript:latest + container_name: mcp-perl-postscript + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-postscript + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1f6f93acaa643cba4cd3b51bf1ff66d621b11bb7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-postscript + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7ed1a2bbe62ecaafce2486e715b0f3e1be6836fb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-readonly via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-readonly -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-readonly_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-readonly_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-readonly_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/app/perl-readonly_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/app/perl-readonly_server.py new file mode 100644 index 0000000000000000000000000000000000000000..18f2b89fd687080b43423e02d965c745faec55c7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/app/perl-readonly_server.py @@ -0,0 +1,324 @@ +from typing import Optional, List, Dict +import subprocess +from pathlib import Path + +@mcp.tool() +def perl_interpreter( + program_file: Optional[str] = None, + one_liner: Optional[str] = None, + arguments: List[str] = [], + check_syntax_only: bool = False, + warnings: bool = False, + all_warnings: bool = False, + disable_warnings: bool = False, + taint_check: bool = False, + taint_warnings: bool = False, + include_dirs: List[str] = [], + modules: List[str] = [], + autosplit: bool = False, + split_pattern: Optional[str] = None, + line_ending_processing: bool = False, + inplace_edit_extension: Optional[str] = None, + assume_while_loop: bool = False, + assume_print_loop: bool = False, + unicode_features: Optional[str] = None, + debug_flags: Optional[str] = None, +): + """ + Execute the Perl interpreter with various switches. This is the base tool for running + Perl scripts or one-liners that utilize the Readonly module. + """ + cmd = ["perl"] + + if unicode_features: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if debug_flags: + cmd.append(f"-D{debug_flags}") + if warnings: + cmd.append("-w") + if all_warnings: + cmd.append("-W") + if disable_warnings: + cmd.append("-X") + if taint_check: + cmd.append("-T") + if taint_warnings: + cmd.append("-t") + if autosplit: + cmd.append("-a") + if split_pattern: + cmd.append(f"-F{split_pattern}") + if line_ending_processing: + cmd.append("-l") + if assume_while_loop: + cmd.append("-n") + if assume_print_loop: + cmd.append("-p") + + if inplace_edit_extension is not None: + cmd.append(f"-i{inplace_edit_extension}") + + for d in include_dirs: + cmd.append(f"-I{d}") + + for m in modules: + cmd.append(f"-M{m}") + + if one_liner: + cmd.extend(["-e", one_liner]) + + if program_file: + prog_path = Path(program_file) + if not prog_path.exists(): + return {"error": f"Program file not found: {program_file}"} + cmd.append(str(prog_path)) + + if arguments: + cmd.extend(arguments) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "return_code": result.returncode + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "return_code": e.returncode + } + +@mcp.tool() +def readonly_scalar( + variable_name: str, + value_expression: str, + test_code: str = "", +): + """ + Creates a deep read-only scalar using Readonly::Scalar. + + Args: + variable_name: The name of the variable (e.g., '$PI' or 'my $sca'). + value_expression: The Perl expression for the value (e.g., '3.14' or '{a => 1}'). + test_code: Optional Perl code to run after declaration to verify behavior. + """ + if not variable_name.startswith('$') and not variable_name.startswith('my $'): + return {"error": "Variable name must start with $ or 'my $'"} + + perl_code = f"use Readonly; Readonly::Scalar {variable_name} => {value_expression}; {test_code}" + + cmd = ["perl", "-MReadonly", "-e", perl_code] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Modification of a read-only value attempted or syntax error." + } + +@mcp.tool() +def readonly_array( + variable_name: str, + values_expression: str, + test_code: str = "", +): + """ + Creates a deep read-only array using Readonly::Array. + + Args: + variable_name: The name of the array (e.g., '@arr' or 'my @arr'). + values_expression: The Perl list of values (e.g., '1, 2, 3' or 'qw/a b c/'). + test_code: Optional Perl code to run after declaration. + """ + if not variable_name.startswith('@') and not variable_name.startswith('my @'): + return {"error": "Variable name must start with @ or 'my @'"} + + perl_code = f"use Readonly; Readonly::Array {variable_name} => {values_expression}; {test_code}" + + cmd = ["perl", "-MReadonly", "-e", perl_code] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def readonly_hash( + variable_name: str, + pairs_expression: str, + test_code: str = "", +): + """ + Creates a deep read-only hash using Readonly::Hash. + + Args: + variable_name: The name of the hash (e.g., '%h' or 'my %h'). + pairs_expression: The Perl key-value pairs (e.g., "key => 'val', k2 => 'v2'" or "{k=>'v'}"). + test_code: Optional Perl code to run after declaration. + """ + if not variable_name.startswith('%') and not variable_name.startswith('my %'): + return {"error": "Variable name must start with % or 'my %'"} + + perl_code = f"use Readonly; Readonly::Hash {variable_name} => {pairs_expression}; {test_code}" + + cmd = ["perl", "-MReadonly", "-e", perl_code] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def readonly_generic( + variable_name: str, + value_expression: Optional[str] = None, + test_code: str = "", +): + """ + Creates a read-only variable using the generic Readonly function. + This is shallow for complex structures unless using Perl 5.8+. + + Args: + variable_name: The name of the variable (e.g., '$var', '@arr', '%h'). + value_expression: The value to assign. If omitted, variable is initialized as undef. + test_code: Optional Perl code to run after declaration. + """ + if value_expression: + perl_code = f"use Readonly; Readonly {variable_name} => {value_expression}; {test_code}" + else: + perl_code = f"use Readonly; Readonly {variable_name}; {test_code}" + + cmd = ["perl", "-MReadonly", "-e", perl_code] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def readonly_scalar1( + variable_name: str, + value_expression: str, + test_code: str = "", +): + """ + Creates a shallow read-only scalar using Readonly::Scalar1. + Only the top level is read-only. + """ + perl_code = f"use Readonly; Readonly::Scalar1 {variable_name} => {value_expression}; {test_code}" + cmd = ["perl", "-MReadonly", "-e", perl_code] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return {"command_executed": " ".join(cmd), "stdout": result.stdout, "stderr": result.stderr} + except subprocess.CalledProcessError as e: + return {"command_executed": " ".join(cmd), "stdout": e.stdout, "stderr": e.stderr, "error": str(e)} + +@mcp.tool() +def readonly_array1( + variable_name: str, + values_expression: str, + test_code: str = "", +): + """ + Creates a shallow read-only array using Readonly::Array1. + """ + perl_code = f"use Readonly; Readonly::Array1 {variable_name} => {values_expression}; {test_code}" + cmd = ["perl", "-MReadonly", "-e", perl_code] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return {"command_executed": " ".join(cmd), "stdout": result.stdout, "stderr": result.stderr} + except subprocess.CalledProcessError as e: + return {"command_executed": " ".join(cmd), "stdout": e.stdout, "stderr": e.stderr, "error": str(e)} + +@mcp.tool() +def readonly_hash1( + variable_name: str, + pairs_expression: str, + test_code: str = "", +): + """ + Creates a shallow read-only hash using Readonly::Hash1. + """ + perl_code = f"use Readonly; Readonly::Hash1 {variable_name} => {pairs_expression}; {test_code}" + cmd = ["perl", "-MReadonly", "-e", perl_code] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return {"command_executed": " ".join(cmd), "stdout": result.stdout, "stderr": result.stderr} + except subprocess.CalledProcessError as e: + return {"command_executed": " ".join(cmd), "stdout": e.stdout, "stderr": e.stderr, "error": str(e)} + +@mcp.tool() +def readonly_clone( + source_definition: str, + source_variable: str, + test_code: str = "", +): + """ + Clones a read-only variable into a mutable one using Readonly::Clone. + + Args: + source_definition: Perl code to define the original readonly variable. + source_variable: The name of the variable to clone (e.g., '$scalar'). + test_code: Perl code to run with the clone (stored in $clone). + """ + perl_code = ( + f"use Readonly; {source_definition} " + f"my $clone = Readonly::Clone {source_variable}; " + f"{test_code}" + ) + cmd = ["perl", "-MReadonly", "-e", perl_code] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/app/perl-readonly_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/app/perl-readonly_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8d1e15406c2edffe29b19b80593a726f4c7463ae --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/app/perl-readonly_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/app/perl-readonly_server.py') +SERVER_NAME = 'biosci_perl_readonly' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..a69981f1f5dc718706204a0887c67384507a750c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-readonly: + build: . + image: mcp-perl-readonly:latest + container_name: mcp-perl-readonly + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-readonly + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7c37cb245428fded0616cd082b720724e28ceff6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-readonly + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-readonly/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..edbe021e509c063c20291eb08c3a12dbd222b0fd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-regexp-common via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-regexp-common -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-regexp-common_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-regexp-common_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-regexp-common_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/app/perl-regexp-common_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/app/perl-regexp-common_server.py new file mode 100644 index 0000000000000000000000000000000000000000..29c138eba48c33764af0821ba305d4300b9a51ea --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/app/perl-regexp-common_server.py @@ -0,0 +1,253 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +@mcp.tool() +def regexp_common_match_text( + pattern_keys: str, + input_text: str, + anchored: bool = True, +) -> dict: + """ + Check if a specific string matches a Regexp::Common pattern. + + Args: + pattern_keys: Comma-separated keys for the %RE hash (e.g., 'num,int' or 'net,IPv4'). + input_text: The text string to validate against the pattern. + anchored: If True, the pattern must match the entire string (adds ^ and $). + """ + # Construct the Perl script to perform the match + # We use shift @ARGV to safely pass arguments into the Perl environment + perl_script = ( + "use Regexp::Common; " + "my $keys_str = shift @ARGV; " + "my $text = shift @ARGV; " + "my $is_anchored = shift @ARGV; " + "my $re = $RE; " + "for (split ',', $keys_str) { $re = $re->{$_} } " + "my $pattern = ($is_anchored eq 'True') ? qr/^$re$/ : qr/$re/; " + "print 'MATCH' if $text =~ $pattern;" + ) + + cmd = [ + "perl", + "-MRegexp::Common", + "-e", perl_script, + pattern_keys, + input_text, + str(anchored) + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + is_match = "MATCH" in result.stdout + return { + "command_executed": " ".join(cmd), + "is_match": is_match, + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def regexp_common_filter_file( + pattern_keys: str, + input_file: str, + invert_match: bool = False, + output_file: Optional[str] = None, +) -> dict: + """ + Filter lines in a file based on a Regexp::Common pattern (similar to grep). + + Args: + pattern_keys: Comma-separated keys for the %RE hash (e.g., 'URI,HTTP' or 'comment,C++'). + input_file: Path to the input file to be filtered. + invert_match: If True, print lines that do NOT match the pattern. + output_file: Optional path to save the filtered output. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + # Construct the Perl script for line-by-line filtering + perl_script = ( + "use Regexp::Common; " + "my $keys_str = shift @ARGV; " + "my $is_invert = shift @ARGV; " + "my $re = $RE; " + "for (split ',', $keys_str) { $re = $re->{$_} } " + "while(<>) { " + " if ($is_invert eq 'True') { print unless /$re/ } " + " else { print if /$re/ } " + "}" + ) + + cmd = [ + "perl", + "-MRegexp::Common", + "-e", perl_script, + pattern_keys, + str(invert_match), + str(input_path) + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + if output_file: + output_path = Path(output_file) + output_path.write_text(result.stdout) + return { + "command_executed": " ".join(cmd), + "stdout": "Output written to " + output_file, + "stderr": result.stderr, + "output_files": [output_file] + } + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def regexp_common_extract_from_file( + pattern_keys: str, + input_file: str, + output_file: Optional[str] = None, +) -> dict: + """ + Extract all occurrences of a Regexp::Common pattern from a file. + + Args: + pattern_keys: Comma-separated keys for the %RE hash (e.g., 'net,IPv4' or 'zip,US'). + input_file: Path to the input file. + output_file: Optional path to save the extracted matches. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + # Construct the Perl script for global extraction + perl_script = ( + "use Regexp::Common; " + "my $keys_str = shift @ARGV; " + "my $re = $RE; " + "for (split ',', $keys_str) { $re = $re->{$_} } " + "while(<>) { " + " while(/$re/g) { print \"$&\n\" } " + "}" + ) + + cmd = [ + "perl", + "-MRegexp::Common", + "-e", perl_script, + pattern_keys, + str(input_path) + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + if output_file: + output_path = Path(output_file) + output_path.write_text(result.stdout) + return { + "command_executed": " ".join(cmd), + "stdout": "Extracted matches written to " + output_file, + "stderr": result.stderr, + "output_files": [output_file] + } + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def regexp_common_get_pattern( + pattern_keys: str, +) -> dict: + """ + Retrieve the raw regular expression string for a specific Regexp::Common category. + + Args: + pattern_keys: Comma-separated keys for the %RE hash (e.g., 'num,real' or 'balanced,-parens=>()'). + """ + # Construct the Perl script to print the regex object + perl_script = ( + "use Regexp::Common; " + "my $keys_str = shift @ARGV; " + "my $re = $RE; " + "for (split ',', $keys_str) { $re = $re->{$_} } " + "print $re;" + ) + + cmd = [ + "perl", + "-MRegexp::Common", + "-e", perl_script, + pattern_keys + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "pattern": result.stdout, + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def regexp_common_list_info() -> dict: + """ + Provide information about available Regexp::Common categories and usage. + """ + info = ( + "Regexp::Common provides a wide variety of regular expressions. " + "Common categories include:\n" + "- balanced: Balanced parentheses, brackets, etc.\n" + "- comment: Comments in various programming languages (C, C++, Java, etc.)\n" + "- delimited: Delimited strings (quotes, etc.)\n" + "- list: Lists of items\n" + "- net: Network addresses (IPv4, IPv6, MAC, etc.)\n" + "- num: Numbers (int, real, decimal, etc.)\n" + "- profanity: Common profane words\n" + "- URI: URIs (HTTP, FTP, etc.)\n" + "- zip: Zip codes for various countries\n\n" + "Usage: Provide keys as a comma-separated string, e.g., 'num,int' or 'net,IPv4'." + ) + return { + "info": info, + "documentation_url": "http://metacpan.org/pod/Regexp::Common" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/app/perl-regexp-common_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/app/perl-regexp-common_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..40fa5abafc994958d5744b976b7469df7042a093 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/app/perl-regexp-common_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/app/perl-regexp-common_server.py') +SERVER_NAME = 'biosci_perl_regexp_common' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..60800241442a189363c151db1201b7e4e1715676 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-regexp-common: + build: . + image: mcp-perl-regexp-common:latest + container_name: mcp-perl-regexp-common + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-regexp-common + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5484e305f9f162598c18204cceae97ba79c2b533 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-regexp-common + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-regexp-common/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..90c6424007c6f1ccfac3baba3c47a6c86c4faa78 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-role-tiny via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-role-tiny -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-role-tiny_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-role-tiny_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-role-tiny_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/app/perl-role-tiny_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/app/perl-role-tiny_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c0bf06fe733c34d9cc7a21d53a40b9974469ad9e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/app/perl-role-tiny_server.py @@ -0,0 +1,216 @@ +from typing import Optional, List +import subprocess +from pathlib import Path + +@mcp.tool() +def perl_role_tiny_run( + script_path: Optional[str] = None, + one_liner: Optional[str] = None, + use_modules: Optional[List[str]] = None, + include_dirs: Optional[List[str]] = None, + warnings_mode: str = "none", + loop_mode: str = "none", + autosplit: bool = False, + split_pattern: Optional[str] = None, + inplace_suffix: Optional[str] = None, + unicode_features: Optional[str] = None, + taint_check: bool = False, + script_args: Optional[List[str]] = None, +): + """ + Execute Perl code using the perl interpreter. This environment includes the Role::Tiny module. + + Args: + script_path: Path to a Perl script file to execute. + one_liner: A string containing Perl code to run (equivalent to -e). + use_modules: List of modules to load before execution (equivalent to -M). + include_dirs: List of directories to add to @INC (equivalent to -I). + warnings_mode: Warning level: 'none', 'normal' (-w), 'all' (-W), or 'silent' (-X). + loop_mode: Loop behavior: 'none', 'n' (while(<>)), or 'p' (while(<>) { print }). + autosplit: Enable autosplit mode with -n or -p (equivalent to -a). + split_pattern: Pattern for autosplit (equivalent to -F). + inplace_suffix: Extension for in-place editing (equivalent to -i). + unicode_features: Enable Unicode features (equivalent to -C). + taint_check: Enable taint checks (equivalent to -T). + script_args: Arguments to pass to the Perl script or one-liner. + """ + cmd = ["perl"] + + # Handle Warnings + if warnings_mode == "normal": + cmd.append("-w") + elif warnings_mode == "all": + cmd.append("-W") + elif warnings_mode == "silent": + cmd.append("-X") + + # Handle Taint + if taint_check: + cmd.append("-T") + + # Handle Unicode + if unicode_features: + cmd.append(f"-C{unicode_features}") + + # Handle Include Directories + if include_dirs: + for d in include_dirs: + cmd.append(f"-I{d}") + + # Handle Modules + if use_modules: + for m in use_modules: + cmd.append(f"-M{m}") + + # Handle In-place editing + if inplace_suffix is not None: + cmd.append(f"-i{inplace_suffix}") + + # Handle Loops and Autosplit + if loop_mode == "n": + cmd.append("-n") + elif loop_mode == "p": + cmd.append("-p") + + if autosplit: + cmd.append("-a") + if split_pattern: + cmd.append(f"-F{split_pattern}") + + # Handle Execution Source + if one_liner: + cmd.extend(["-e", one_liner]) + elif script_path: + p = Path(script_path) + if not p.exists(): + return {"error": f"Script file not found: {script_path}"} + cmd.append(str(p)) + else: + # If neither is provided, we can't execute much unless it's a version check + # but we have a separate tool for that. + return {"error": "Either script_path or one_liner must be provided."} + + # Handle Script Arguments + if script_args: + cmd.extend(script_args) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "return_code": result.returncode + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "error": "Perl execution failed" + } + +@mcp.tool() +def perl_role_tiny_check_syntax( + script_path: str, + use_modules: Optional[List[str]] = None, + include_dirs: Optional[List[str]] = None, +): + """ + Check the syntax of a Perl script without executing it (equivalent to perl -c). + + Args: + script_path: Path to the Perl script to check. + use_modules: List of modules to load during the check. + include_dirs: List of directories to add to @INC. + """ + p = Path(script_path) + if not p.exists(): + return {"error": f"Script file not found: {script_path}"} + + cmd = ["perl", "-c"] + + if include_dirs: + for d in include_dirs: + cmd.append(f"-I{d}") + + if use_modules: + for m in use_modules: + cmd.append(f"-M{m}") + + cmd.append(str(p)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "Syntax OK" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Syntax check failed" + } + +@mcp.tool() +def perl_role_tiny_info( + verbose: bool = False, + config_variable: Optional[str] = None, +): + """ + Get version and configuration information for the Perl interpreter. + + Args: + verbose: If True, provides a full configuration summary (equivalent to -V). + If False, provides version info (equivalent to -v). + config_variable: Specific configuration variable to query (e.g., 'archname'). + Only used if verbose is True. + """ + if verbose: + if config_variable: + cmd = ["perl", f"-V:{config_variable}"] + else: + cmd = ["perl", "-V"] + else: + cmd = ["perl", "-v"] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to retrieve Perl info" + } + +@mcp.tool() +def perl_role_tiny_list_inc(): + """ + List the Perl include paths (@INC) to verify where modules are searched. + """ + cmd = ["perl", "-e", "print join('\\n', @INC)"] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "include_paths": result.stdout.splitlines(), + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": "Failed to list @INC", + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/app/perl-role-tiny_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/app/perl-role-tiny_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0f91dc29d1064360b559af792a8c5277800a22cf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/app/perl-role-tiny_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/app/perl-role-tiny_server.py') +SERVER_NAME = 'biosci_perl_role_tiny' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..92888e30ffb40cd3f6e983511bd4ffb6e25ddea2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-role-tiny: + build: . + image: mcp-perl-role-tiny:latest + container_name: mcp-perl-role-tiny + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-role-tiny + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..31de7372e7d4737f56ac691ecf8397be71d6eae8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-role-tiny + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-role-tiny/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..30507aa71b79a8c29a679ef431080e2278aec72c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-scalar-list-utils via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-scalar-list-utils -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-scalar-list-utils_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-scalar-list-utils_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-scalar-list-utils_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/app/perl-scalar-list-utils_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/app/perl-scalar-list-utils_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f0306c161d58b67d0cc6d1677149a7257559b45e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/app/perl-scalar-list-utils_server.py @@ -0,0 +1,319 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Union, Dict, Any +from pydantic import Field, validate_call + +# No need to import mcp as per instructions. + +def _build_perl_command( + program_file: Optional[Path], + script_arguments: List[str], + record_separator_octal: Optional[str], + autosplit: bool, + unicode_features: Optional[Union[int, str]], + check_syntax_only: bool, + debugger: Optional[str], + debugging_flags: Optional[Union[int, str]], + execute_program_lines: List[str], + execute_program_lines_extended: List[str], + no_site_customize: bool, + split_pattern: Optional[str], + in_place_edit_extension: Optional[str], + include_directories: List[Path], + line_terminator_octal: Optional[str], + use_modules: List[str], + use_modules_import_semantics: List[str], + no_modules: List[str], + no_modules_import_semantics: List[str], + loop_around_program: bool, + loop_and_print: bool, + rudimentary_switch_parsing: bool, + search_path_for_program: bool, + tainting_warnings: bool, + tainting_checks: bool, + dump_core: bool, + allow_unsafe_operations: bool, + print_version: bool, + print_config_variable: Optional[str], + enable_warnings: bool, + enable_all_warnings: bool, + ignore_text_before_shebang: bool, + cd_to_directory_for_shebang: Optional[Path], + disable_all_warnings: bool, +) -> List[str]: + """ + Helper function to construct the Perl command based on provided parameters. + """ + cmd = ["perl"] + + if record_separator_octal is not None: + cmd.append(f"-0{record_separator_octal}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if debugger is not None: + cmd.append(f"-d{':' + debugger if debugger else ''}") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + for line in execute_program_lines: + cmd.extend(["-e", line]) + for line in execute_program_lines_extended: + cmd.extend(["-E", line]) + if no_site_customize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if in_place_edit_extension is not None: + cmd.append(f"-i{in_place_edit_extension}") + for inc_dir in include_directories: + cmd.extend(["-I", str(inc_dir)]) + if line_terminator_octal is not None: + cmd.append(f"-l{line_terminator_octal}") + for module in use_modules: + cmd.extend(["-m", module]) + for module in use_modules_import_semantics: + cmd.extend(["-M", module]) + for module in no_modules: + cmd.extend(["-m-", module]) + for module in no_modules_import_semantics: + cmd.extend(["-M-", module]) + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if rudimentary_switch_parsing: + cmd.append("-s") + if search_path_for_program: + cmd.append("-S") + if tainting_warnings: + cmd.append("-t") + if tainting_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if allow_unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config_variable is not None: + cmd.append(f"-V{':' + print_config_variable if print_config_variable else ''}") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if ignore_text_before_shebang: + if cd_to_directory_for_shebang: + cmd.append(f"-x{str(cd_to_directory_for_shebang)}") + else: + cmd.append("-x") + if disable_all_warnings: + cmd.append("-X") + + if program_file: + cmd.append(str(program_file)) + + if script_arguments: + cmd.extend(script_arguments) + + return cmd + +@mcp.tool() +@validate_call +def run_perl_script( + program_file: Optional[Path] = Field(None, description="Path to the Perl script to execute. Can be omitted if program lines are provided via -e or -E."), + script_arguments: List[str] = Field(default_factory=list, description="Arguments to pass to the Perl script."), + record_separator_octal: Optional[str] = Field(None, description="Specify the input record separator. If an empty string is provided, it defaults to '\\0' (e.g., '123' for -0123, or '' for -0)."), + autosplit: bool = Field(False, description="Enables autosplit mode, typically used with -n or -p, splitting $_ into @F."), + unicode_features: Optional[Union[int, str]] = Field(None, description="Enables specific Unicode features. Can be an integer bitmask or a string list (e.g., 1 for -C1, or 'all' for -Call)."), + check_syntax_only: bool = Field(False, description="Checks the script's syntax without executing it, running BEGIN and CHECK blocks."), + debugger: Optional[str] = Field(None, description="Runs the program under a debugger. If an empty string, uses the default debugger (e.g., 'MyDebugger' for -d:MyDebugger, or '' for -d)."), + debugging_flags: Optional[Union[int, str]] = Field(None, description="Set debugging flags (argument is a bit mask or alphabets). E.g., 1 for -D1, or 't' for -Dt."), + execute_program_lines: List[str] = Field(default_factory=list, description="One line of program to execute (can be specified multiple times)."), + execute_program_lines_extended: List[str] = Field(default_factory=list, description="Like -e, but enables all optional features (can be specified multiple times)."), + no_site_customize: bool = Field(False, description="Prevents the loading of $sitelib/sitecustomize.pl at startup."), + split_pattern: Optional[str] = Field(None, description="Specifies the pattern for the split() function when -a is used (e.g., '/\\s+/')."), + in_place_edit_extension: Optional[str] = Field(None, description="Edit <> files in place. If an empty string, no backup is made. If a string (e.g., '.bak'), a backup is created with that extension (e.g., '.bak' for -i.bak, or '' for -i)."), + include_directories: List[Path] = Field(default_factory=list, description="Specify @INC/#include directory (can be specified multiple times)."), + line_terminator_octal: Optional[str] = Field(None, description="Enable line ending processing and specifies the line terminator. If an empty string, enables processing with the default terminator (e.g., '012' for -l012, or '' for -l)."), + use_modules: List[str] = Field(default_factory=list, description="Execute 'use module;' before executing program (e.g., 'strict' for -mstrict)."), + use_modules_import_semantics: List[str] = Field(default_factory=list, description="Execute 'use module;' with import semantics (e.g., 'CGI' for -MCGI)."), + no_modules: List[str] = Field(default_factory=list, description="Execute 'no module;' before executing program (e.g., 'warnings' for -m-warnings)."), + no_modules_import_semantics: List[str] = Field(default_factory=list, description="Execute 'no module;' with import semantics (e.g., 'strict' for -M-strict)."), + loop_around_program: bool = Field(False, description="Assume 'while (<>) { ... }' loop around program (-n)."), + loop_and_print: bool = Field(False, description="Assume loop like -n but print line also, like sed (-p)."), + rudimentary_switch_parsing: bool = Field(False, description="Enable rudimentary parsing for switches after programfile (-s)."), + search_path_for_program: bool = Field(False, description="Look for programfile using PATH environment variable (-S)."), + tainting_warnings: bool = Field(False, description="Enable tainting warnings (-t)."), + tainting_checks: bool = Field(False, description="Enable tainting checks (-T)."), + dump_core: bool = Field(False, description="Dump core after parsing program (-u)."), + allow_unsafe_operations: bool = Field(False, description="Allow unsafe operations (-U)."), + print_version: bool = Field(False, description="Print Perl version, patchlevel, and license (-v)."), + print_config_variable: Optional[str] = Field(None, description="Print configuration summary or a single Config.pm variable. If an empty string, prints the full summary (e.g., 'archname' for -V:archname, or '' for -V)."), + enable_warnings: bool = Field(False, description="Enable many useful warnings (-w)."), + enable_all_warnings: bool = Field(False, description="Enable all warnings (-W)."), + ignore_text_before_shebang: bool = Field(False, description="Ignore text before the '#!perl' line (-x)."), + cd_to_directory_for_shebang: Optional[Path] = Field(None, description="Optionally change to this directory when -x is used (e.g., Path('/tmp') for -x/tmp). Requires 'ignore_text_before_shebang' to be True."), + disable_all_warnings: bool = Field(False, description="Disable all warnings (-X)."), +) -> Dict[str, Any]: + """ + Executes a Perl script with various interpreter options. + + This tool wraps the 'perl' interpreter, allowing execution of Perl scripts + with fine-grained control over its command-line switches. While the context + is 'perl-scalar-list-utils', this tool directly interfaces with the 'perl' + executable, making the 'Scalar::List::Utils' module available if installed + in the Perl environment. + + Parameters: + program_file: Path to the Perl script to execute. Can be omitted if program lines are provided via -e or -E. + script_arguments: A list of arguments to pass directly to the Perl script. + record_separator_octal: Specify the input record separator. If an empty string is provided, it defaults to '\\0'. + autosplit: Enables autosplit mode, typically used with -n or -p, splitting $_ into @F. + unicode_features: Enables specific Unicode features. Can be an integer bitmask or a string list (e.g., 'all'). + check_syntax_only: Checks the script's syntax without executing it, running BEGIN and CHECK blocks. + debugger: Runs the program under a debugger. If an empty string, uses the default debugger. + debugging_flags: Sets debugging flags. Can be an integer bitmask or a string of alphabets. + execute_program_lines: A list of Perl code lines to execute. Each string in the list corresponds to a separate -e switch. + execute_program_lines_extended: Similar to -e, but enables all optional features for each line. + no_site_customize: Prevents the loading of $sitelib/sitecustomize.pl at startup. + split_pattern: Specifies the pattern for the split() function when -a is used (e.g., '/\\s+/'). + in_place_edit_extension: Edits files in place. If an empty string, no backup is made. If a string (e.g., '.bak'), a backup is created with that extension. + include_directories: A list of directories to add to @INC for module searching. Each Path corresponds to a separate -I switch. + line_terminator_octal: Enables line ending processing and specifies the line terminator. If an empty string, enables processing with the default terminator. + use_modules: A list of module names to 'use' before execution (e.g., 'strict'). Each string corresponds to a separate -m switch. + use_modules_import_semantics: A list of module names to 'use' with import semantics (e.g., 'CGI'). Each string corresponds to a separate -M switch. + no_modules: A list of module names to 'no' (disable) before execution (e.g., 'warnings'). Each string corresponds to a separate -m- switch. + no_modules_import_semantics: A list of module names to 'no' (disable) with import semantics (e.g., 'strict'). Each string corresponds to a separate -M- switch. + loop_around_program: Assumes a 'while (<>) { ... }' loop around program (-n). + loop_and_print: Assumes a loop like -n but also prints each line, similar to 'sed' (-p). + rudimentary_switch_parsing: Enables rudimentary parsing for switches that appear after the program file (-s). + search_path_for_program: Looks for the program file using the PATH environment variable (-S). + tainting_warnings: Enables warnings related to data tainting (-t). + tainting_checks: Enables full tainting checks, which are stricter than warnings (-T). + dump_core: Dumps a core file after parsing the program (-u). + allow_unsafe_operations: Allows unsafe operations (-U). + print_version: Prints the Perl version, patchlevel, and license information (-v). + print_config_variable: Prints a configuration summary or the value of a specific Config.pm variable. If an empty string, prints the full summary. + enable_warnings: Enables many useful warnings (-w). + enable_all_warnings: Enables all warnings (-W). + ignore_text_before_shebang: Ignores text before the '#!perl' line (-x). + cd_to_directory_for_shebang: Optionally change to this directory when -x is used (e.g., Path('/tmp') for -x/tmp). Requires 'ignore_text_before_shebang' to be True. + disable_all_warnings: Disables all warnings (-X). + """ + # Input validation + if not program_file and not (execute_program_lines or execute_program_lines_extended): + raise ValueError("Either 'program_file' or at least one 'execute_program_line'/'execute_program_line_extended' must be provided.") + + if program_file and not program_file.is_file(): + raise FileNotFoundError(f"Program file not found: {program_file}") + + for inc_dir in include_directories: + if not inc_dir.is_dir(): + raise NotADirectoryError(f"Include directory not found or is not a directory: {inc_dir}") + + if cd_to_directory_for_shebang: + if not ignore_text_before_shebang: + raise ValueError("cd_to_directory_for_shebang can only be used when ignore_text_before_shebang is True (-x option).") + if not cd_to_directory_for_shebang.is_dir(): + raise NotADirectoryError(f"Directory for -x option not found or is not a directory: {cd_to_directory_for_shebang}") + + # Mutually exclusive warnings options + warning_flags_count = sum([enable_warnings, enable_all_warnings, disable_all_warnings]) + if warning_flags_count > 1: + raise ValueError("Only one of -w, -W, or -X can be enabled at a time.") + + # Mutually exclusive loop options + if loop_around_program and loop_and_print: + raise ValueError("Only one of -n or -p can be enabled at a time.") + + command = _build_perl_command( + program_file=program_file, + script_arguments=script_arguments, + record_separator_octal=record_separator_octal, + autosplit=autosplit, + unicode_features=unicode_features, + check_syntax_only=check_syntax_only, + debugger=debugger, + debugging_flags=debugging_flags, + execute_program_lines=execute_program_lines, + execute_program_lines_extended=execute_program_lines_extended, + no_site_customize=no_site_customize, + split_pattern=split_pattern, + in_place_edit_extension=in_place_edit_extension, + include_directories=include_directories, + line_terminator_octal=line_terminator_octal, + use_modules=use_modules, + use_modules_import_semantics=use_modules_import_semantics, + no_modules=no_modules, + no_modules_import_semantics=no_modules_import_semantics, + loop_around_program=loop_around_program, + loop_and_print=loop_and_print, + rudimentary_switch_parsing=rudimentary_switch_parsing, + search_path_for_program=search_path_for_program, + tainting_warnings=tainting_warnings, + tainting_checks=tainting_checks, + dump_core=dump_core, + allow_unsafe_operations=allow_unsafe_operations, + print_version=print_version, + print_config_variable=print_config_variable, + enable_warnings=enable_warnings, + enable_all_warnings=enable_all_warnings, + ignore_text_before_shebang=ignore_text_before_shebang, + cd_to_directory_for_shebang=cd_to_directory_for_shebang, + disable_all_warnings=disable_all_warnings, + ) + + stdout_data = "" + stderr_data = "" + output_files: List[Path] = [] + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout_data = process.stdout + stderr_data = process.stderr + + # The -i switch modifies files in place that are processed by the Perl script's + # <> operator (typically command-line arguments after the program file). + # Without knowing the specific input files passed to the script, we cannot + # reliably list them as output_files. Therefore, this list remains empty. + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"Perl script execution failed with exit code {e.returncode}", + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'perl' executable not found. Please ensure Perl is installed and in your PATH.", + "output_files": [], + "error": "Perl executable not found.", + } + except Exception as e: + return { + "command_executed": " ".join(command), + "stdout": stdout_data, + "stderr": stderr_data, + "output_files": [], + "error": f"An unexpected error occurred: {str(e)}", + } + + return { + "command_executed": " ".join(command), + "stdout": stdout_data, + "stderr": stderr_data, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/app/perl-scalar-list-utils_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/app/perl-scalar-list-utils_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..18703186d49263ce80572eec20e2a6a8b777d899 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/app/perl-scalar-list-utils_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/app/perl-scalar-list-utils_server.py') +SERVER_NAME = 'biosci_perl_scalar_list_utils' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..b1d7df7d2e4c819fb3e40d027bff1ad512c88c48 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/app/requirements.txt @@ -0,0 +1 @@ +pydantic==2.13.3 diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b250c460fd34b7952c4ac9abb2ca6bbe43ba7557 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-scalar-list-utils: + build: . + image: mcp-perl-scalar-list-utils:latest + container_name: mcp-perl-scalar-list-utils + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-scalar-list-utils + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..17f522203d4d70a3bae31c877548510795248451 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-scalar-list-utils + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..789aa886bf8bd292297707f78435d515c716853d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-scalar-list-utils/requirements.txt @@ -0,0 +1,3 @@ +pydantic==2.13.3 +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4a31d52f12e79e4bf101df5121d804b94b96d5fc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-sereal-decoder via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-sereal-decoder -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-sereal-decoder_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-sereal-decoder_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-sereal-decoder_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/app/perl-sereal-decoder_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/app/perl-sereal-decoder_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3bafb6dce949db1fd8f049617ee922308881e953 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/app/perl-sereal-decoder_server.py @@ -0,0 +1,216 @@ +import subprocess +import json +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def sereal_decode( + input_file: str, + output_file: Optional[str] = None, + mode: str = "standard", + offset: int = 0, + refuse_snappy: bool = False, + refuse_objects: bool = False, + no_bless_objects: bool = False, + no_thaw_objects: bool = False, + validate_utf8: bool = False, + max_recursion_depth: int = 10000, + max_num_hash_entries: int = 0, + max_num_array_entries: int = 0, + max_string_length: int = 0, + max_uncompressed_size: int = 0, + incremental: bool = False, + alias_smallint: bool = False, +): + """ + Decodes a Sereal-encoded binary file into a JSON-formatted structure. + + This tool wraps the Sereal::Decoder Perl module, providing access to its + high-performance binary deserialization capabilities. + + Args: + input_file: Path to the Sereal-encoded binary file. + output_file: Optional path to save the decoded JSON output. If not provided, output is returned in stdout. + mode: Decoding mode. Options: 'standard' (decode data), 'with_header' (decode data and header), 'only_header' (decode only header). + offset: Byte offset to start decoding from within the file. + refuse_snappy: If true, refuse Snappy-compressed input data. + refuse_objects: If true, refuse deserializing any objects in the input stream. + no_bless_objects: If true, deserialize objects without blessing them into Perl classes. + no_thaw_objects: If true, deserialize frozen objects as raw arguments instead of calling THAW. + validate_utf8: If true, refuse invalid UTF-8 byte sequences. + max_recursion_depth: Limit on the depth of nested structures (default 10000). + max_num_hash_entries: Maximum number of hash entries allowed (0 for no limit). + max_num_array_entries: Maximum number of array entries allowed (0 for no limit). + max_string_length: Maximum string length allowed (0 for no limit). + max_uncompressed_size: Maximum size of uncompressed blobs (0 for no limit). + incremental: If true, destructively parse documents out of the input. + alias_smallint: If true, alias small integers for memory efficiency. + """ + # Input validation + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + if mode not in ["standard", "with_header", "only_header"]: + return {"error": "Invalid mode. Must be 'standard', 'with_header', or 'only_header'."} + + if max_recursion_depth < 0: + max_recursion_depth = 10000 + + # Construct Perl script + # We use JSON::PP (core Perl) to output the decoded structure as JSON + perl_script = f""" +use Sereal::Decoder; +use JSON::PP; +use Fcntl qw(:seek); + +my $decoder = Sereal::Decoder->new({{ + refuse_snappy => {1 if refuse_snappy else 0}, + refuse_objects => {1 if refuse_objects else 0}, + no_bless_objects => {1 if no_bless_objects else 0}, + no_thaw_objects => {1 if no_thaw_objects else 0}, + validate_utf8 => {1 if validate_utf8 else 0}, + max_recursion_depth => {max_recursion_depth}, + max_num_hash_entries => {max_num_hash_entries}, + max_num_array_entries => {max_num_array_entries}, + max_string_length => {max_string_length}, + max_uncompressed_size => {max_uncompressed_size}, + incremental => {1 if incremental else 0}, + alias_smallint => {1 if alias_smallint else 0}, +}}); + +my $filename = '{input_file}'; +open my $fh, '<:raw', $filename or die "Could not open $filename: $!"; +my $blob; +{{ local $/; $blob = <$fh>; }} +close $fh; + +my ($data, $header); +my $mode = '{mode}'; +my $offset = {offset}; + +if ($mode eq 'only_header') {{ + $header = $decoder->decode_only_header_with_offset($blob, $offset); +}} elsif ($mode eq 'with_header') {{ + ($header, $data) = $decoder->decode_with_header_and_offset($blob, $offset); +}} else {{ + $data = $decoder->decode_with_offset($blob, $offset); +}} + +my $bytes_consumed = $decoder->bytes_consumed(); + +my $result = {{ + header => $header, + data => $data, + bytes_consumed => $bytes_consumed +}}; + +print JSON::PP->new->utf8->canonical->encode($result); +""" + + try: + # Execute Perl one-liner + process = subprocess.run( + ["perl", "-e", perl_script], + capture_output=True, + text=True, + check=True + ) + + decoded_json = process.stdout + + if output_file: + output_path = Path(output_file) + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(decoded_json) + return { + "command_executed": f"perl -e '...Sereal::Decoder logic...'", + "stdout": "Output written to file.", + "stderr": process.stderr, + "output_files": [str(output_path)] + } + else: + return { + "command_executed": f"perl -e '...Sereal::Decoder logic...'", + "stdout": decoded_json, + "stderr": process.stderr, + "output_files": [] + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Perl execution failed. Ensure perl-sereal-decoder is installed." + } + +@mcp.tool() +def sereal_looks_like_sereal(input_file: str): + """ + Performs a quick check to see if a file appears to be a valid Sereal document. + + This is not a full validation but checks for a reasonable Sereal header. + + Args: + input_file: Path to the file to check. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + perl_script = f""" +use Sereal::Decoder; +my $filename = '{input_file}'; +open my $fh, '<:raw', $filename or die $!; +read($fh, my $buffer, 1024); +close $fh; +my $res = Sereal::Decoder->looks_like_sereal($buffer); +print $res ? "true" : "false"; +""" + + try: + process = subprocess.run( + ["perl", "-e", perl_script], + capture_output=True, + text=True, + check=True + ) + + is_sereal = process.stdout.strip() == "true" + + return { + "command_executed": "Sereal::Decoder->looks_like_sereal()", + "is_sereal": is_sereal, + "stdout": process.stdout, + "stderr": process.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Validation check failed." + } + +@mcp.tool() +def sereal_get_version(): + """ + Returns the version information for the installed Sereal::Decoder module. + """ + try: + process = subprocess.run( + ["perl", "-MSereal::Decoder", "-e", "print $Sereal::Decoder::VERSION"], + capture_output=True, + text=True, + check=True + ) + return { + "sereal_decoder_version": process.stdout.strip(), + "command_executed": "perl -MSereal::Decoder -e 'print $Sereal::Decoder::VERSION'" + } + except subprocess.CalledProcessError as e: + return { + "error": "Could not determine Sereal::Decoder version. Is it installed?", + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/app/perl-sereal-decoder_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/app/perl-sereal-decoder_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1de66585d6ed6d549366a38e0ef3a40473bbbc54 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/app/perl-sereal-decoder_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/app/perl-sereal-decoder_server.py') +SERVER_NAME = 'biosci_perl_sereal_decoder' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f4f9a5950fbb5a750c98b82e5919bb97635214be --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-sereal-decoder: + build: . + image: mcp-perl-sereal-decoder:latest + container_name: mcp-perl-sereal-decoder + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-sereal-decoder + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6d066bd07d2b78eb3077580795823d5a5b995a2c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-sereal-decoder + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-decoder/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce0732acb035b6464ba027b9ff294d98f2657675 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-sereal-encoder via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-sereal-encoder -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-sereal-encoder_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-sereal-encoder_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-sereal-encoder_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/app/perl-sereal-encoder_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/app/perl-sereal-encoder_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3bba133ae6daaab5fdbbcc2d8de3cc05299f1c1e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/app/perl-sereal-encoder_server.py @@ -0,0 +1,272 @@ +import subprocess +import json +from pathlib import Path +from typing import Optional, List, Literal +import tempfile +import os + +@mcp.tool() +def encode_to_sereal( + input_json_string: str, + output_sereal_file: Path, +) -> dict: + """ + Encodes a JSON string representing a Perl data structure into Sereal binary format. + + This tool creates a temporary Perl script that uses the Sereal::Encoder module + to serialize the provided JSON data. The JSON data is passed to the Perl script's + STDIN, and the resulting Sereal binary data is written to the specified output file. + + Args: + input_json_string: A JSON string representing the data structure to encode. + This will be passed to the Perl script's STDIN. + Example: '{"name": "Alice", "age": 30}' + output_sereal_file: The path to the output file where the Sereal-encoded + binary data will be written. The parent directory will + be created if it does not exist. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + Includes an 'error' key if the process fails. + """ + # Input validation + if not input_json_string: + raise ValueError("Input JSON string cannot be empty.") + try: + # Basic Python-side validation to catch obvious JSON errors early + json.loads(input_json_string) + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON input string: {e}") + + # Ensure the output directory exists + if not output_sereal_file.parent.exists(): + output_sereal_file.parent.mkdir(parents=True, exist_ok=True) + + # Perl script content to encode data using Sereal::Encoder + perl_script_content = """ +use strict; +use warnings; +use Sereal::Encoder; +use JSON; + +my $json_string = do { local $/; }; # Read all from STDIN +my $data; +eval { + $data = decode_json($json_string); +}; +if ($@) { + die "Failed to decode JSON from STDIN: $@"; +} + +my $encoder = Sereal::Encoder->new(); +my $encoded_data = $encoder->encode($data); + +my $output_file = $ARGV[0]; +open my $fh, '>:raw', $output_file or die "Could not open '$output_file' for writing: $!"; +print $fh $encoded_data; +close $fh; +""" + + command_executed: List[str] = [] + stdout: str = "" + stderr: str = "" + output_files: List[Path] = [] + temp_script_path: Optional[Path] = None + + try: + # Write the Perl script to a temporary file + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".pl") as temp_script_file: + temp_script_file.write(perl_script_content) + temp_script_path = Path(temp_script_file.name) + + # Construct the command to execute the Perl script + command = ["perl", str(temp_script_path), str(output_sereal_file)] + command_executed = command + + # Execute the Perl script, passing JSON input via stdin + process = subprocess.run( + command, + input=input_json_string.encode('utf-8'), # Encode JSON string to bytes for stdin + capture_output=True, + check=True # Raise CalledProcessError for non-zero exit codes + ) + stdout = process.stdout.decode('utf-8') + stderr = process.stderr.decode('utf-8') + + if output_sereal_file.is_file(): + output_files.append(output_sereal_file) + + except subprocess.CalledProcessError as e: + stdout = e.stdout.decode('utf-8') if e.stdout else "" + stderr = e.stderr.decode('utf-8') if e.stderr else "" + return { + "command_executed": " ".join(command_executed), + "stdout": stdout, + "stderr": stderr, + "output_files": [], + "error": f"Perl script failed with exit code {e.returncode}" + } + except Exception as e: + return { + "command_executed": " ".join(command_executed), + "stdout": stdout, + "stderr": stderr, + "output_files": [], + "error": f"An unexpected error occurred: {e}" + } + finally: + # Clean up the temporary Perl script + if temp_script_path and temp_script_path.exists(): + os.remove(temp_script_path) + + return { + "command_executed": " ".join(command_executed), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files + } + + +@mcp.tool() +def decode_from_sereal( + input_sereal_file: Path, + output_format: Literal['json', 'dumper'] = 'json', + output_file: Optional[Path] = None, +) -> dict: + """ + Decodes Sereal binary data from a file into a human-readable format (JSON or Perl Data::Dumper). + + This tool creates a temporary Perl script that uses the Sereal::Decoder module + to deserialize Sereal binary data from the specified input file. The decoded + data can be output as JSON or Perl's Data::Dumper format. + + Args: + input_sereal_file: The path to the input file containing Sereal-encoded binary data. + output_format: The desired output format for the decoded data. + Can be 'json' for JSON output or 'dumper' for Perl Data::Dumper output. + Defaults to 'json'. + output_file: Optional path to the output file where the decoded data will be written. + If not provided, the decoded data will be returned in stdout. + The parent directory will be created if it does not exist. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + Includes an 'error' key if the process fails. + """ + # Input validation + if not input_sereal_file.is_file(): + raise FileNotFoundError(f"Input Sereal file not found: {input_sereal_file}") + + if output_file: + if not output_file.parent.exists(): + output_file.parent.mkdir(parents=True, exist_ok=True) + + # Perl script content to decode data using Sereal::Decoder + perl_script_content = """ +use strict; +use warnings; +use Sereal::Decoder; +use JSON; +use Data::Dumper; + +my $sereal_file = $ARGV[0]; +my $output_format = $ARGV[1]; + +open my $fh, '<:raw', $sereal_file or die "Could not open '$sereal_file' for reading: $!"; +my $encoded_data = do { local $/; <$fh> }; # Read entire binary file +close $fh; + +my $decoder = Sereal::Decoder->new(); +my $decoded_data; +eval { + $decoded_data = $decoder->decode($encoded_data); +}; +if ($@) { + die "Failed to decode Sereal data from '$sereal_file': $@"; +} + +my $output_string; +if ($output_format eq 'json') { + eval { + $output_string = encode_json($decoded_data); + }; + if ($@) { + die "Failed to encode decoded data to JSON: $@"; + } +} elsif ($output_format eq 'dumper') { + $Data::Dumper::Sortkeys = 1; # For consistent output + $output_string = Dumper($decoded_data); +} else { + die "Unsupported output format: $output_format. Must be 'json' or 'dumper'."; +} + +if (@ARGV > 2) { # If output_file is provided as a third argument + my $out_file = $ARGV[2]; + open my $out_fh, '>', $out_file or die "Could not open '$out_file' for writing: $!"; + print $out_fh $output_string; + close $out_fh; +} else { + print $output_string; # Print to STDOUT if no output file specified +} +""" + + command_executed: List[str] = [] + stdout: str = "" + stderr: str = "" + output_files: List[Path] = [] + temp_script_path: Optional[Path] = None + + try: + # Write the Perl script to a temporary file + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".pl") as temp_script_file: + temp_script_file.write(perl_script_content) + temp_script_path = Path(temp_script_file.name) + + # Construct the command to execute the Perl script + command = ["perl", str(temp_script_path), str(input_sereal_file), output_format] + if output_file: + command.append(str(output_file)) + command_executed = command + + # Execute the Perl script + process = subprocess.run( + command, + capture_output=True, + text=True, # Capture stdout/stderr as text + check=True # Raise CalledProcessError for non-zero exit codes + ) + stdout = process.stdout + stderr = process.stderr + + if output_file and output_file.is_file(): + output_files.append(output_file) + + except subprocess.CalledProcessError as e: + stdout = e.stdout if e.stdout else "" + stderr = e.stderr if e.stderr else "" + return { + "command_executed": " ".join(command_executed), + "stdout": stdout, + "stderr": stderr, + "output_files": [], + "error": f"Perl script failed with exit code {e.returncode}" + } + except Exception as e: + return { + "command_executed": " ".join(command_executed), + "stdout": stdout, + "stderr": stderr, + "output_files": [], + "error": f"An unexpected error occurred: {e}" + } + finally: + # Clean up the temporary Perl script + if temp_script_path and temp_script_path.exists(): + os.remove(temp_script_path) + + return { + "command_executed": " ".join(command_executed), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/app/perl-sereal-encoder_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/app/perl-sereal-encoder_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..98e37c54dc9562cd9e1f17baef0371a26b759569 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/app/perl-sereal-encoder_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/app/perl-sereal-encoder_server.py') +SERVER_NAME = 'biosci_perl_sereal_encoder' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3a547830e541a9115a6407092259ce0a81c24d40 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-sereal-encoder: + build: . + image: mcp-perl-sereal-encoder:latest + container_name: mcp-perl-sereal-encoder + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-sereal-encoder + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cec07e618163bd874e91986c3561f0c10a6e6dc3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-sereal-encoder + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal-encoder/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c7fc5b8ec86f042e98e1a6bd6a6f3cdba4d8e7dc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-sereal via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-sereal -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-sereal_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-sereal_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-sereal_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/app/perl-sereal_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/app/perl-sereal_server.py new file mode 100644 index 0000000000000000000000000000000000000000..60da427900f1c8d9c9fdb46c9ea362831b460d8f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/app/perl-sereal_server.py @@ -0,0 +1,209 @@ +import subprocess +import shlex +from pathlib import Path +from typing import Optional, List + +# MCP decorator is omitted as per instructions, but would be present in a real MCP environment. +# @mcp.tool( +# name="perl-sereal", +# description="A wrapper for the Perl interpreter, the execution environment for the Sereal module." +# ) +def perl_interpreter( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + execute_program: Optional[List[str]] = None, + execute_program_features: Optional[List[str]] = None, + check_syntax_only: bool = False, + print_version: bool = False, + print_config_variable: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + use_module: Optional[List[str]] = None, + no_module: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + autosplit: bool = False, + split_pattern: Optional[str] = None, + in_place_edit_extension: Optional[str] = None, + record_separator: Optional[str] = None, + line_terminator: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + enable_tainting_checks: bool = False, + enable_tainting_warnings: bool = False, + allow_unsafe_operations: bool = False, + run_under_debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + unicode_features: Optional[str] = None, + no_sitecustomize: bool = False, + enable_switch_parsing: bool = False, + search_path_for_program: bool = False, + dump_core: bool = False, + ignore_text_before_shebang_dir: Optional[Path] = None, +) -> dict: + """ + Executes a Perl script or command. This tool wraps the `perl` interpreter, + which is the execution environment for Perl modules like Sereal. + + Args: + programfile: Path to the Perl program file to execute. + arguments: A list of arguments to pass to the program file. + execute_program: One or more lines of a program to be executed via the -e switch. + execute_program_features: Like execute_program, but enables all optional features (-E). + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). Corresponds to -c. + print_version: Print version, patchlevel, and license. Corresponds to -v. + print_config_variable: Print configuration summary. If a value is provided, prints a single Config.pm variable. Corresponds to -V[:variable]. + include_directories: Specify @INC/#include directories. Corresponds to -I. + use_module: Execute "use module..." before the program. Corresponds to -M. + no_module: Execute "no module..." before the program. Corresponds to -m. + loop_around_program: Assume "while (<>) { ... }" loop around the program. Corresponds to -n. + loop_and_print: Assume loop like -n but also print the line. Corresponds to -p. + autosplit: Enable autosplit mode with -n or -p (splits $_ into @F). Corresponds to -a. + split_pattern: Specify the split() pattern for the -a switch. Corresponds to -F. + in_place_edit_extension: Edit <> files in place. If an extension is supplied, a backup is made. Corresponds to -i[extension]. + record_separator: Specify the record separator (e.g., as an octal value). Corresponds to -0[octal]. + line_terminator: Enable line ending processing and specify the line terminator. Corresponds to -l[octal]. + enable_warnings: Enable many useful warnings. Corresponds to -w. + enable_all_warnings: Enable all warnings. Corresponds to -W. + disable_all_warnings: Disable all warnings. Corresponds to -X. + enable_tainting_checks: Enable tainting checks for security. Corresponds to -T. + enable_tainting_warnings: Enable tainting warnings. Corresponds to -t. + allow_unsafe_operations: Allow unsafe operations. Corresponds to -U. + run_under_debugger: Run the program under the specified debugger. Corresponds to -d[:debugger]. + debugging_flags: Set debugging flags. Corresponds to -D[number/list]. + unicode_features: Enable the listed Unicode features. Corresponds to -C[number/list]. + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. Corresponds to -f. + enable_switch_parsing: Enable rudimentary parsing for switches after the program file. Corresponds to -s. + search_path_for_program: Look for the program file using the PATH environment variable. Corresponds to -S. + dump_core: Dump core after parsing the program. Corresponds to -u. + ignore_text_before_shebang_dir: Ignore text before #!perl line and optionally cd to the specified directory. Corresponds to -x[directory]. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if programfile and (execute_program or execute_program_features): + raise ValueError("Cannot specify both a 'programfile' and 'execute_program'/'execute_program_features'.") + + if not any([programfile, execute_program, execute_program_features, print_version, print_config_variable is not None]): + raise ValueError("Must provide a program to run (e.g., 'programfile' or 'execute_program') or an info flag (e.g., 'print_version').") + + if programfile and not programfile.exists(): + raise FileNotFoundError(f"The specified program file does not exist: {programfile}") + + if autosplit and not (loop_around_program or loop_and_print): + raise ValueError("Autosplit mode (-a) requires a loop flag (-n or -p) to be enabled.") + + if split_pattern and not autosplit: + raise ValueError("A split pattern (-F) can only be used with autosplit mode (-a).") + + if sum([enable_warnings, enable_all_warnings, disable_all_warnings]) > 1: + raise ValueError("Warning flags -w, -W, and -X are mutually exclusive.") + + # --- Command Construction --- + cmd = ["perl"] + + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if run_under_debugger is not None: + cmd.append(f"-d{run_under_debugger}") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if execute_program: + for prog_line in execute_program: + cmd.extend(["-e", prog_line]) + if execute_program_features: + for prog_line in execute_program_features: + cmd.extend(["-E", prog_line]) + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if in_place_edit_extension is not None: + cmd.append(f"-i{in_place_edit_extension}") + if include_directories: + for directory in include_directories: + cmd.extend(["-I", str(directory)]) + if line_terminator is not None: + cmd.append(f"-l{line_terminator}") + if use_module: + for mod in use_module: + cmd.extend(["-M", mod]) + if no_module: + for mod in no_module: + cmd.extend(["-m", mod]) + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if enable_switch_parsing: + cmd.append("-s") + if search_path_for_program: + cmd.append("-S") + if enable_tainting_warnings: + cmd.append("-t") + if enable_tainting_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if allow_unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config_variable is not None: + cmd.append(f"-V{print_config_variable}") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if ignore_text_before_shebang_dir: + cmd.extend(["-x", str(ignore_text_before_shebang_dir)]) + if disable_all_warnings: + cmd.append("-X") + + if programfile: + cmd.append(str(programfile)) + + if arguments: + cmd.append("--") + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = shlex.join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # --- Structured Result Return --- + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [] # The interpreter itself doesn't guarantee output files. + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/app/perl-sereal_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/app/perl-sereal_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fc6d749d723c9c149f97b56a80a61a213f94a981 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/app/perl-sereal_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/app/perl-sereal_server.py') +SERVER_NAME = 'biosci_perl_sereal' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..17b091ee6a6e0de26c0dc58fd19826c191dfd0a2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-sereal: + build: . + image: mcp-perl-sereal:latest + container_name: mcp-perl-sereal + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-sereal + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..72cebcb51617d918039b61e1eb78a8efaa052893 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-sereal + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sereal/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..80a693e4e1d785ba51843123c7c2186243c8ce9f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-set-intervaltree via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-set-intervaltree -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-set-intervaltree_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-set-intervaltree_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-set-intervaltree_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/app/perl-set-intervaltree_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/app/perl-set-intervaltree_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4b48e3670fd7a56d1813b70939917edf40726e9a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/app/perl-set-intervaltree_server.py @@ -0,0 +1,696 @@ +import subprocess +import json +from pathlib import Path +from typing import List, Optional, Union, Tuple, Dict +import tempfile + +# Helper function to run Perl commands +def _run_perl_command( + command_args: List[str], + input_data: Optional[str] = None, +) -> Dict[str, Union[str, List[Path]]]: + """ + Executes a Perl command and captures its output. + """ + try: + process = subprocess.run( + ["perl"] + command_args, + capture_output=True, + text=True, + check=True, + input=input_data + ) + stdout = process.stdout.strip() + stderr = process.stderr.strip() + return { + "command_executed": "perl " + " ".join(command_args), + "stdout": stdout, + "stderr": stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": "perl " + " ".join(command_args), + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "error": f"Perl command failed with exit code {e.returncode}", + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": "perl " + " ".join(command_args), + "stdout": "", + "stderr": "Error: 'perl' executable not found. Please ensure Perl is installed and in your PATH.", + "error": "Perl executable not found", + "output_files": [], + } + +# --- Generic Perl Execution Tool --- + +@mcp.tool() +def perl_execute( + program_file: Optional[Path] = None, + program_string: Optional[str] = None, + arguments: Optional[List[str]] = None, + stdin_input: Optional[str] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[Union[int, str]] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debugging_flags: Optional[Union[int, str]] = None, + enable_all_features: bool = False, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + module_to_use: Optional[str] = None, + module_to_no_use: Optional[str] = None, + assume_while_loop: bool = False, + assume_while_loop_and_print: bool = False, + rudimentary_switch_parsing: bool = False, + search_path_for_program: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: Optional[str] = None, # None for no -V, "" for -V, "var" for -V:var + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang: Optional[Path] = None, + disable_all_warnings: bool = False, + additional_perl_switches: Optional[List[str]] = None, +) -> Dict[str, Union[str, List[Path]]]: + """ + Executes a Perl script or one-liner with specified Perl interpreter switches. + + This tool provides a generic interface to the Perl interpreter, allowing + execution of Perl programs and scripts with various command-line options. + It is designed to run any Perl code, including scripts that utilize + modules like Set::IntervalTree. + + Args: + program_file: Path to the Perl script file to execute. + program_string: Perl code to execute as a one-liner (using -e or -E). + arguments: List of arguments to pass to the Perl script or one-liner. + stdin_input: Optional string to pass to the Perl script's standard input. + record_separator: Specify record separator (e.g., '\\0' for -0). + autosplit: Enable autosplit mode with -n or -p (splits $_ into @F). + unicode_features: Enables listed Unicode features (number or list). + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). + debugger: Run program under debugger (e.g., 'perl -d:MyDebugger'). + debugging_flags: Set debugging flags (bit mask or alphabets). + enable_all_features: Like -e, but enables all optional features (uses -E). + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup (-f). + split_pattern: split() pattern for -a switch (e.g., '/\\s+/'). + edit_in_place_extension: Edit <> files in place (makes backup if extension supplied, e.g., '.bak'). + include_directories: Specify @INC/#include directory (several -I's allowed). + line_ending_processing: Enable line ending processing, specifies line terminator (e.g., '\\n'). + module_to_use: Execute "use module..." before executing program (e.g., 'Set::IntervalTree'). + module_to_no_use: Execute "no module..." before executing program (e.g., 'strict'). + assume_while_loop: Assume "while (<>) { ... }" loop around program (-n). + assume_while_loop_and_print: Assume loop like -n but print line also, like sed (-p). + rudimentary_switch_parsing: Enable rudimentary parsing for switches after programfile (-s). + search_path_for_program: Look for programfile using PATH environment variable (-S). + tainting_warnings: Enable tainting warnings (-t). + tainting_checks: Enable tainting checks (-T). + dump_core: Dump core after parsing program (-u). + allow_unsafe_operations: Allow unsafe operations (-U). + print_version: Print version, patchlevel and license (-v). + print_config_summary: Print configuration summary. Pass `None` to omit `-V`, + an empty string `""` for `-V`, or a variable name + (e.g., `"archname"`) for `-V:variable`. + enable_warnings: Enable many useful warnings (-w). + enable_all_warnings: Enable all warnings (-W). + ignore_text_before_shebang: Ignore text before #!perl line (optionally cd to directory) (-x). + disable_all_warnings: Disable all warnings (-X). + additional_perl_switches: A list of any other Perl command-line switches not explicitly covered. + """ + if not program_file and not program_string: + raise ValueError("Either 'program_file' or 'program_string' must be provided.") + if program_file and program_string: + raise ValueError("Cannot provide both 'program_file' and 'program_string'.") + if program_file and not program_file.is_file(): + raise FileNotFoundError(f"Program file not found: {program_file}") + if ignore_text_before_shebang and not ignore_text_before_shebang.is_dir(): + raise NotADirectoryError(f"Directory for -x option not found: {ignore_text_before_shebang}") + + cmd = [] + + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if debugger is not None: + cmd.append(f"-d:{debugger}") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if enable_all_features: + cmd.append("-E") + elif program_string: # -e is only used if -E is not and program_string is provided + cmd.append("-e") + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + cmd.append(f"-i{edit_in_place_extension}") + if include_directories: + for inc_dir in include_directories: + if not inc_dir.is_dir(): + raise NotADirectoryError(f"Include directory not found: {inc_dir}") + cmd.append(f"-I{inc_dir}") + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + if module_to_use is not None: + cmd.append(f"-m{module_to_use}") + if module_to_no_use is not None: + cmd.append(f"-M-{module_to_no_use}") # Note the - for no module + if assume_while_loop: + cmd.append("-n") + if assume_while_loop_and_print: + cmd.append("-p") + if rudimentary_switch_parsing: + cmd.append("-s") + if search_path_for_program: + cmd.append("-S") + if tainting_warnings: + cmd.append("-t") + if tainting_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if allow_unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config_summary is not None: + if print_config_summary == "": + cmd.append("-V") + else: + cmd.append(f"-V:{print_config_summary}") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if ignore_text_before_shebang is not None: + cmd.append(f"-x{ignore_text_before_shebang}") + if disable_all_warnings: + cmd.append("-X") + if additional_perl_switches: + cmd.extend(additional_perl_switches) + + if program_string: + cmd.append(program_string) + elif program_file: + cmd.append(str(program_file)) + + if arguments: + cmd.extend(arguments) + + return _run_perl_command(cmd, input_data=stdin_input) + +# --- Set::IntervalTree specific tools --- + +def _generate_intervaltree_script( + operation: str, + intervals_to_build: Optional[List[Tuple[Union[str, int], int, int]]] = None, + object_id: Optional[Union[str, int]] = None, + low: Optional[int] = None, + high: Optional[int] = None, + query: Optional[int] = None, + coderef_filter: Optional[str] = None, # Perl code string for the filter +) -> str: + """Generates a Perl script to perform a Set::IntervalTree operation.""" + script_lines = [ + "use strict;", + "use warnings;", + "use Set::IntervalTree;", + "use JSON;", + "", + "my $tree = Set::IntervalTree->new;", + ] + + if intervals_to_build: + for obj, l, h in intervals_to_build: + # Escape string objects for Perl + obj_str = f"'{obj}'" if isinstance(obj, str) else str(obj) + script_lines.append(f"$tree->insert({obj_str}, {l}, {h});") + + script_lines.append("") # Add a blank line for readability + + if operation == "insert": + if object_id is None or low is None or high is None: + raise ValueError("object_id, low, and high must be provided for insert operation.") + obj_str = f"'{object_id}'" if isinstance(object_id, str) else str(object_id) + script_lines.append(f"$tree->insert({obj_str}, {low}, {high});") + script_lines.append("print JSON->new->utf8->encode({status => 'success', message => 'Interval inserted'});") + elif operation == "fetch": + if low is None or high is None: + raise ValueError("low and high must be provided for fetch operation.") + script_lines.append(f"my $results = $tree->fetch({low}, {high});") + script_lines.append("print JSON->new->utf8->encode($results);") + elif operation == "fetch_window": + if low is None or high is None: + raise ValueError("low and high must be provided for fetch_window operation.") + script_lines.append(f"my $results = $tree->fetch_window({low}, {high});") + script_lines.append("print JSON->new->utf8->encode($results);") + elif operation == "fetch_nearest_up": + if query is None: + raise ValueError("query must be provided for fetch_nearest_up operation.") + script_lines.append(f"my $result = $tree->fetch_nearest_up({query});") + script_lines.append("print JSON->new->utf8->encode($result ? [$result] : []);") # Return as array for consistency + elif operation == "fetch_nearest_down": + if query is None: + raise ValueError("query must be provided for fetch_nearest_down operation.") + script_lines.append(f"my $result = $tree->fetch_nearest_down({query});") + script_lines.append("print JSON->new->utf8->encode($result ? [$result] : []);") # Return as array for consistency + elif operation == "remove": + if low is None or high is None: + raise ValueError("low and high must be provided for remove operation.") + if coderef_filter: + script_lines.append(f"my $removed = $tree->remove({low}, {high}, sub {{ {coderef_filter} }});") + else: + script_lines.append(f"my $removed = $tree->remove({low}, {high});") + script_lines.append("print JSON->new->utf8->encode($removed);") + elif operation == "remove_window": + if low is None or high is None: + raise ValueError("low and high must be provided for remove_window operation.") + if coderef_filter: + script_lines.append(f"my $removed = $tree->remove_window({low}, {high}, sub {{ {coderef_filter} }});") + else: + script_lines.append(f"my $removed = $tree->remove_window({low}, {high});") + script_lines.append("print JSON->new->utf8->encode($removed);") + else: + raise ValueError(f"Unknown operation: {operation}") + + return "\n".join(script_lines) + +@mcp.tool() +def intervaltree_insert( + object_id: Union[str, int], + low: int, + high: int, + initial_intervals: Optional[List[Tuple[Union[str, int], int, int]]] = None, +) -> Dict[str, Union[str, List[Path], List[Union[str, int]], Dict]]: + """ + Inserts a single interval into a Set::IntervalTree. + + This tool creates a new interval tree (optionally pre-populated with + `initial_intervals`), inserts the specified interval, and confirms the operation. + Note: Due to the library's nature, the tree state is not persisted across calls. + + Args: + object_id: The object to associate with the interval (can be any Perl scalar, represented as string/int). + low: The lower bound of the interval (inclusive). + high: The upper bound of the interval (exclusive). + initial_intervals: An optional list of (object_id, low, high) tuples to pre-populate the tree. + Each object_id can be a string or an integer. + Returns: + A dictionary containing command execution details and a status message. + """ + if not isinstance(low, int) or not isinstance(high, int): + raise TypeError("Low and high bounds must be integers.") + if low >= high: + raise ValueError("Low bound must be strictly less than high bound.") + if initial_intervals: + for i, (obj, l, h) in enumerate(initial_intervals): + if not isinstance(l, int) or not isinstance(h, int): + raise TypeError(f"Initial interval {i} has non-integer bounds: ({obj}, {l}, {h})") + if l >= h: + raise ValueError(f"Initial interval {i} has low bound >= high bound: ({obj}, {l}, {h})") + + with tempfile.TemporaryDirectory() as tmpdir: + tmp_path = Path(tmpdir) + script_path = tmp_path / "insert_script.pl" + + perl_script_content = _generate_intervaltree_script( + operation="insert", + intervals_to_build=initial_intervals, + object_id=object_id, + low=low, + high=high, + ) + script_path.write_text(perl_script_content) + + result = _run_perl_command([str(script_path)]) + + # Attempt to parse JSON output + try: + if result["stdout"]: + result["parsed_output"] = json.loads(result["stdout"]) + except json.JSONDecodeError: + result["parsed_output"] = {"error": "Failed to parse JSON output", "raw_stdout": result["stdout"]} + + return result + +@mcp.tool() +def intervaltree_fetch( + low: int, + high: int, + input_intervals: List[Tuple[Union[str, int], int, int]], +) -> Dict[str, Union[str, List[Path], List[Union[str, int]]]]: + """ + Fetches all intervals from a Set::IntervalTree that overlap a specified range. + + This tool builds an interval tree from `input_intervals`, then queries it + for all items whose ranges overlap the specified `low` and `high` bounds. + + Args: + low: The lower bound of the query region (inclusive). + high: The upper bound of the query region (exclusive). + input_intervals: A list of (object_id, low, high) tuples to build the tree. + Each object_id can be a string or an integer. + Returns: + A dictionary containing command execution details and a list of overlapping objects. + """ + if not isinstance(low, int) or not isinstance(high, int): + raise TypeError("Low and high bounds must be integers.") + if low >= high: + raise ValueError("Low bound must be strictly less than high bound.") + if not input_intervals: + raise ValueError("input_intervals cannot be empty for fetch operation.") + for i, (obj, l, h) in enumerate(input_intervals): + if not isinstance(l, int) or not isinstance(h, int): + raise TypeError(f"Input interval {i} has non-integer bounds: ({obj}, {l}, {h})") + if l >= h: + raise ValueError(f"Input interval {i} has low bound >= high bound: ({obj}, {l}, {h})") + + with tempfile.TemporaryDirectory() as tmpdir: + tmp_path = Path(tmpdir) + script_path = tmp_path / "fetch_script.pl" + + perl_script_content = _generate_intervaltree_script( + operation="fetch", + intervals_to_build=input_intervals, + low=low, + high=high, + ) + script_path.write_text(perl_script_content) + + result = _run_perl_command([str(script_path)]) + + try: + if result["stdout"]: + result["fetched_objects"] = json.loads(result["stdout"]) + else: + result["fetched_objects"] = [] + except json.JSONDecodeError: + result["fetched_objects"] = [] + result["error"] = f"Failed to parse JSON output: {result['stdout']}" + + return result + +@mcp.tool() +def intervaltree_fetch_window( + low: int, + high: int, + input_intervals: List[Tuple[Union[str, int], int, int]], +) -> Dict[str, Union[str, List[Path], List[Union[str, int]]]]: + """ + Fetches all intervals from a Set::IntervalTree that are completely contained within a specified range. + + This tool builds an interval tree from `input_intervals`, then queries it + for all items whose ranges are completely contained within the specified + `low` and `high` bounds. + + Args: + low: The lower bound of the query region (inclusive). + high: The upper bound of the query region (exclusive). + input_intervals: A list of (object_id, low, high) tuples to build the tree. + Each object_id can be a string or an integer. + Returns: + A dictionary containing command execution details and a list of contained objects. + """ + if not isinstance(low, int) or not isinstance(high, int): + raise TypeError("Low and high bounds must be integers.") + if low >= high: + raise ValueError("Low bound must be strictly less than high bound.") + if not input_intervals: + raise ValueError("input_intervals cannot be empty for fetch_window operation.") + for i, (obj, l, h) in enumerate(input_intervals): + if not isinstance(l, int) or not isinstance(h, int): + raise TypeError(f"Input interval {i} has non-integer bounds: ({obj}, {l}, {h})") + if l >= h: + raise ValueError(f"Input interval {i} has low bound >= high bound: ({obj}, {l}, {h})") + + with tempfile.TemporaryDirectory() as tmpdir: + tmp_path = Path(tmpdir) + script_path = tmp_path / "fetch_window_script.pl" + + perl_script_content = _generate_intervaltree_script( + operation="fetch_window", + intervals_to_build=input_intervals, + low=low, + high=high, + ) + script_path.write_text(perl_script_content) + + result = _run_perl_command([str(script_path)]) + + try: + if result["stdout"]: + result["fetched_objects"] = json.loads(result["stdout"]) + else: + result["fetched_objects"] = [] + except json.JSONDecodeError: + result["fetched_objects"] = [] + result["error"] = f"Failed to parse JSON output: {result['stdout']}" + + return result + +@mcp.tool() +def intervaltree_fetch_nearest_up( + query: int, + input_intervals: List[Tuple[Union[str, int], int, int]], +) -> Dict[str, Union[str, List[Path], List[Union[str, int]]]]: + """ + Searches for the closest interval upstream that does not contain the query position. + + This tool builds an interval tree from `input_intervals`, then queries it + for the closest interval upstream of `query` that does not contain `query`. + + Args: + query: The position to use for the search. + input_intervals: A list of (object_id, low, high) tuples to build the tree. + Each object_id can be a string or an integer. + Returns: + A dictionary containing command execution details and a list (potentially empty or single-item) of the nearest upstream object. + """ + if not isinstance(query, int): + raise TypeError("Query position must be an integer.") + if not input_intervals: + raise ValueError("input_intervals cannot be empty for fetch_nearest_up operation.") + for i, (obj, l, h) in enumerate(input_intervals): + if not isinstance(l, int) or not isinstance(h, int): + raise TypeError(f"Input interval {i} has non-integer bounds: ({obj}, {l}, {h})") + if l >= h: + raise ValueError(f"Input interval {i} has low bound >= high bound: ({obj}, {l}, {h})") + + with tempfile.TemporaryDirectory() as tmpdir: + tmp_path = Path(tmpdir) + script_path = tmp_path / "fetch_nearest_up_script.pl" + + perl_script_content = _generate_intervaltree_script( + operation="fetch_nearest_up", + intervals_to_build=input_intervals, + query=query, + ) + script_path.write_text(perl_script_content) + + result = _run_perl_command([str(script_path)]) + + try: + if result["stdout"]: + result["fetched_objects"] = json.loads(result["stdout"]) + else: + result["fetched_objects"] = [] + except json.JSONDecodeError: + result["fetched_objects"] = [] + result["error"] = f"Failed to parse JSON output: {result['stdout']}" + + return result + +@mcp.tool() +def intervaltree_fetch_nearest_down( + query: int, + input_intervals: List[Tuple[Union[str, int], int, int]], +) -> Dict[str, Union[str, List[Path], List[Union[str, int]]]]: + """ + Searches for the closest interval downstream that does not contain the query position. + + This tool builds an interval tree from `input_intervals`, then queries it + for the closest interval downstream of `query` that does not contain `query`. + + Args: + query: The position to use for the search. + input_intervals: A list of (object_id, low, high) tuples to build the tree. + Each object_id can be a string or an integer. + Returns: + A dictionary containing command execution details and a list (potentially empty or single-item) of the nearest downstream object. + """ + if not isinstance(query, int): + raise TypeError("Query position must be an integer.") + if not input_intervals: + raise ValueError("input_intervals cannot be empty for fetch_nearest_down operation.") + for i, (obj, l, h) in enumerate(input_intervals): + if not isinstance(l, int) or not isinstance(h, int): + raise TypeError(f"Input interval {i} has non-integer bounds: ({obj}, {l}, {h})") + if l >= h: + raise ValueError(f"Input interval {i} has low bound >= high bound: ({obj}, {l}, {h})") + + with tempfile.TemporaryDirectory() as tmpdir: + tmp_path = Path(tmpdir) + script_path = tmp_path / "fetch_nearest_down_script.pl" + + perl_script_content = _generate_intervaltree_script( + operation="fetch_nearest_down", + intervals_to_build=input_intervals, + query=query, + ) + script_path.write_text(perl_script_content) + + result = _run_perl_command([str(script_path)]) + + try: + if result["stdout"]: + result["fetched_objects"] = json.loads(result["stdout"]) + else: + result["fetched_objects"] = [] + except json.JSONDecodeError: + result["fetched_objects"] = [] + result["error"] = f"Failed to parse JSON output: {result['stdout']}" + + return result + +@mcp.tool() +def intervaltree_remove( + low: int, + high: int, + input_intervals: List[Tuple[Union[str, int], int, int]], + coderef_filter: Optional[str] = None, +) -> Dict[str, Union[str, List[Path], List[Union[str, int]]]]: + """ + Removes items from a Set::IntervalTree that overlap a specified region. + + This tool builds an interval tree from `input_intervals`, then removes + items whose ranges overlap the specified `low` and `high` bounds. + An optional Perl coderef can be provided to filter which overlapping items are removed. + + Args: + low: The lower bound of the region to query for removal (inclusive). + high: The upper bound of the region to query for removal (exclusive). + input_intervals: A list of (object_id, low, high) tuples to build the tree. + Each object_id can be a string or an integer. + coderef_filter: An optional Perl code string for filtering. The coderef receives + ($item, $low, $high) as arguments. If it returns true, the item is removed. + Example: 'return $item < 100;' + Returns: + A dictionary containing command execution details and a list of the objects that were removed. + """ + if not isinstance(low, int) or not isinstance(high, int): + raise TypeError("Low and high bounds must be integers.") + if low >= high: + raise ValueError("Low bound must be strictly less than high bound.") + if not input_intervals: + raise ValueError("input_intervals cannot be empty for remove operation.") + for i, (obj, l, h) in enumerate(input_intervals): + if not isinstance(l, int) or not isinstance(h, int): + raise TypeError(f"Input interval {i} has non-integer bounds: ({obj}, {l}, {h})") + if l >= h: + raise ValueError(f"Input interval {i} has low bound >= high bound: ({obj}, {l}, {h})") + + with tempfile.TemporaryDirectory() as tmpdir: + tmp_path = Path(tmpdir) + script_path = tmp_path / "remove_script.pl" + + perl_script_content = _generate_intervaltree_script( + operation="remove", + intervals_to_build=input_intervals, + low=low, + high=high, + coderef_filter=coderef_filter, + ) + script_path.write_text(perl_script_content) + + result = _run_perl_command([str(script_path)]) + + try: + if result["stdout"]: + result["removed_objects"] = json.loads(result["stdout"]) + else: + result["removed_objects"] = [] + except json.JSONDecodeError: + result["removed_objects"] = [] + result["error"] = f"Failed to parse JSON output: {result['stdout']}" + + return result + +@mcp.tool() +def intervaltree_remove_window( + low: int, + high: int, + input_intervals: List[Tuple[Union[str, int], int, int]], + coderef_filter: Optional[str] = None, +) -> Dict[str, Union[str, List[Path], List[Union[str, int]]]]: + """ + Removes items from a Set::IntervalTree that are completely contained within a specified region. + + This tool builds an interval tree from `input_intervals`, then removes + items whose ranges are completely contained within the specified `low` and `high` bounds. + An optional Perl coderef can be provided to filter which contained items are removed. + + Args: + low: The lower bound of the region to query for removal (inclusive). + high: The upper bound of the region to query for removal (exclusive). + input_intervals: A list of (object_id, low, high) tuples to build the tree. + Each object_id can be a string or an integer. + coderef_filter: An optional Perl code string for filtering. The coderef receives + ($item, $low, $high) as arguments. If it returns true, the item is removed. + Example: 'return $item < 100;' + Returns: + A dictionary containing command execution details and a list of the objects that were removed. + """ + if not isinstance(low, int) or not isinstance(high, int): + raise TypeError("Low and high bounds must be integers.") + if low >= high: + raise ValueError("Low bound must be strictly less than high bound.") + if not input_intervals: + raise ValueError("input_intervals cannot be empty for remove_window operation.") + for i, (obj, l, h) in enumerate(input_intervals): + if not isinstance(l, int) or not isinstance(h, int): + raise TypeError(f"Input interval {i} has non-integer bounds: ({obj}, {l}, {h})") + if l >= h: + raise ValueError(f"Input interval {i} has low bound >= high bound: ({obj}, {l}, {h})") + + with tempfile.TemporaryDirectory() as tmpdir: + tmp_path = Path(tmpdir) + script_path = tmp_path / "remove_window_script.pl" + + perl_script_content = _generate_intervaltree_script( + operation="remove_window", + intervals_to_build=input_intervals, + low=low, + high=high, + coderef_filter=coderef_filter, + ) + script_path.write_text(perl_script_content) + + result = _run_perl_command([str(script_path)]) + + try: + if result["stdout"]: + result["removed_objects"] = json.loads(result["stdout"]) + else: + result["removed_objects"] = [] + except json.JSONDecodeError: + result["removed_objects"] = [] + result["error"] = f"Failed to parse JSON output: {result['stdout']}" + + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/app/perl-set-intervaltree_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/app/perl-set-intervaltree_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7087ccd3e54fadc0d7edba7419b4cd652fd1ce4a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/app/perl-set-intervaltree_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/app/perl-set-intervaltree_server.py') +SERVER_NAME = 'biosci_perl_set_intervaltree' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4915dff7e53543675a7c63e70f1a8067a07c6ab9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-set-intervaltree: + build: . + image: mcp-perl-set-intervaltree:latest + container_name: mcp-perl-set-intervaltree + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-set-intervaltree + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6694d34e706a2f2630df4f41a4dc4fab62d5d4bd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-set-intervaltree + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intervaltree/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intspan/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intspan/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-intspan/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-scalar/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-scalar/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-set-scalar/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..267217daa05b75e4068fb85c6ec3ef0d962e4e0d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-soap-lite via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-soap-lite -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-soap-lite_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-soap-lite_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-soap-lite_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/app/perl-soap-lite_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/app/perl-soap-lite_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b1fd18ff69a0b32a568e0e2d4335e74d33285daa --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/app/perl-soap-lite_server.py @@ -0,0 +1,190 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +@mcp.tool() +def soap_lite_stubmaker( + wsdl_source: str, + output_dir: Optional[str] = None, +) -> Dict[str, Any]: + """ + Generate Perl client stubs from a WSDL (Web Services Description Language) source using stubmaker.pl. + + Args: + wsdl_source: The URL or local file path to the WSDL file. + output_dir: Optional directory where the generated .pm files should be saved. + """ + # Input validation + if not wsdl_source: + return {"error": "wsdl_source is required"} + + command = ["stubmaker.pl", wsdl_source] + + if output_dir: + out_path = Path(output_dir) + if not out_path.exists(): + try: + out_path.mkdir(parents=True, exist_ok=True) + except Exception as e: + return {"error": f"Could not create output directory: {str(e)}"} + command.append(str(out_path)) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "status": "success", + "message": f"Stubs generated for {wsdl_source}" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "stubmaker.pl failed to execute", + "exit_code": e.returncode + } + except FileNotFoundError: + return {"error": "stubmaker.pl not found in the environment. Ensure perl-soap-lite is installed."} + +@mcp.tool() +def perl_soap_lite_run( + script_path: Optional[str] = None, + one_liner: Optional[str] = None, + arguments: List[str] = [], + include_dirs: List[str] = [], + warnings: bool = True, + taint_check: bool = False, +) -> Dict[str, Any]: + """ + Execute a Perl script or one-liner that utilizes the SOAP::Lite module. + + Args: + script_path: Path to a .pl script to execute. + one_liner: A string containing Perl code to execute (equivalent to perl -e). + arguments: List of command-line arguments to pass to the script. + include_dirs: List of directories to add to @INC (equivalent to -I). + warnings: Enable Perl warnings (equivalent to -w). Default is True. + taint_check: Enable taint checks (equivalent to -T). Default is False. + """ + if not script_path and not one_liner: + return {"error": "Either script_path or one_liner must be provided."} + + command = ["perl"] + + # Add SOAP::Lite module by default + command.extend(["-MSOAP::Lite"]) + + if warnings: + command.append("-w") + + if taint_check: + command.append("-T") + + for directory in include_dirs: + command.append(f"-I{directory}") + + if one_liner: + command.extend(["-e", one_liner]) + elif script_path: + path = Path(script_path) + if not path.exists(): + return {"error": f"Script file not found: {script_path}"} + command.append(str(path)) + + if arguments: + command.append("--") + command.extend(arguments) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Perl execution failed", + "exit_code": e.returncode + } + +@mcp.tool() +def perl_soap_lite_check_syntax( + script_path: str, + include_dirs: List[str] = [], +) -> Dict[str, Any]: + """ + Check the syntax of a Perl script using SOAP::Lite without executing it. + + Args: + script_path: Path to the Perl script to check. + include_dirs: List of directories to add to @INC. + """ + path = Path(script_path) + if not path.exists(): + return {"error": f"File not found: {script_path}"} + + command = ["perl", "-MSOAP::Lite", "-c", str(path)] + + for directory in include_dirs: + command.insert(2, f"-I{directory}") + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "status": "syntax_ok" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Syntax check failed", + "exit_code": e.returncode + } + +@mcp.tool() +def soap_lite_version_info() -> Dict[str, Any]: + """ + Retrieve version information for the installed Perl and SOAP::Lite module. + """ + # Check Perl version + perl_v = subprocess.run(["perl", "-v"], capture_output=True, text=True) + + # Check SOAP::Lite version + soap_v = subprocess.run( + ["perl", "-MSOAP::Lite", "-e", "print $SOAP::Lite::VERSION"], + capture_output=True, + text=True + ) + + return { + "perl_version_raw": perl_v.stdout.splitlines()[1] if perl_v.returncode == 0 else "Unknown", + "soap_lite_version": soap_v.stdout if soap_v.returncode == 0 else "Not installed or error", + "status": "success" if soap_v.returncode == 0 else "error" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/app/perl-soap-lite_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/app/perl-soap-lite_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ca8773ff81ef1d9c5f3fecc9a141b8961945144c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/app/perl-soap-lite_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/app/perl-soap-lite_server.py') +SERVER_NAME = 'biosci_perl_soap_lite' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..292b0a680c7904ecbadc4619047172b8fd8fc1c5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-soap-lite: + build: . + image: mcp-perl-soap-lite:latest + container_name: mcp-perl-soap-lite + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-soap-lite + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5eaf531c6e72e20eda5b390bf7b50cb70cb58511 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-soap-lite + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..20b9399cea728ff3e21f1d30850a01974396bfa0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-socket via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-socket -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-socket_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-socket_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-socket_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/app/perl-socket_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/app/perl-socket_server.py new file mode 100644 index 0000000000000000000000000000000000000000..42be0179cb68132017d1f8eb82ceff2e69651b23 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/app/perl-socket_server.py @@ -0,0 +1,1152 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Union, Dict, Any + +# Helper function to run perl commands +def _run_perl_command( + command_args: List[str], + input_script_content: Optional[str] = None, + script_file: Optional[Path] = None, + script_arguments: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Internal helper to execute a Perl command. + Handles temporary script files and structured error reporting. + """ + cmd = ["perl"] + command_args + + temp_script_path: Optional[Path] = None + if input_script_content: + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".pl") as f: + f.write(input_script_content) + temp_script_path = Path(f.name) + cmd.append(str(temp_script_path)) + elif script_file: + if not script_file.is_file(): + raise ValueError(f"Program file not found: {script_file}") + cmd.append(str(script_file)) + + if script_arguments: + cmd.extend(script_arguments) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + stdout = result.stdout.strip() + stderr = result.stderr.strip() + + # For these tools, we don't expect specific output files to be generated + # that need to be tracked. If -i is used, it modifies input files in place. + output_files: List[str] = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "error": f"Perl command failed with exit code {e.returncode}", + "output_files": [], + } + finally: + if temp_script_path and temp_script_path.exists(): + temp_script_path.unlink() + +@mcp.tool() +def perl_execute_script( + program_file: Optional[Path] = None, + program_lines: Optional[List[str]] = None, + script_arguments: Optional[List[str]] = None, + record_separator_octal: Optional[str] = None, + autosplit_mode: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + run_debugger: Optional[str] = None, + debug_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + use_modules: Optional[List[str]] = None, + no_use_modules: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + rudimentary_switch_parsing: bool = False, + look_for_programfile_in_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core_after_parsing: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang_dir: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> Dict[str, Any]: + """ + Executes a Perl script with various interpreter options. + + This tool provides a generic interface to run Perl scripts, allowing + fine-grained control over the Perl interpreter's behavior via its + command-line switches. + + Args: + program_file: Path to the main Perl script file to execute. + Cannot be used with `program_lines`. + program_lines: A list of Perl code lines to execute directly. + Each string in the list corresponds to a `-e` switch. + Cannot be used with `program_file`. + script_arguments: Arguments to pass to the Perl script (available in @ARGV). + record_separator_octal: Specify record separator (e.g., '0' for NUL, '0777' for paragraph mode). + autosplit_mode: Enable autosplit mode with -n or -p (splits $_ into @F). + unicode_features: Enables listed Unicode features (e.g., 'all', 'io'). + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). + run_debugger: Run program under debugger (optional debugger name, e.g., 'ptkdb'). + debug_flags: Set debugging flags (argument is a bit mask or alphabets). + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. + split_pattern: split() pattern for -a switch (e.g., '/\s+/'). + edit_in_place_extension: Edit <> files in place (makes backup if extension supplied, e.g., '.bak'). + include_directories: Specify @INC/#include directories (several -I's allowed). + line_ending_processing: Enable line ending processing, specifies line terminator (e.g., '012' for LF). + use_modules: Execute "use module..." before executing program (e.g., 'Socket', 'strict'). + no_use_modules: Execute "no module..." before executing program (e.g., 'warnings'). + loop_around_program: Assume "while (<>) { ... }" loop around program. + loop_and_print: Assume loop like -n but print line also, like sed. + rudimentary_switch_parsing: Enable rudimentary parsing for switches after programfile. + look_for_programfile_in_path: Look for programfile using PATH environment variable. + tainting_warnings: Enable tainting warnings. + tainting_checks: Enable tainting checks. + dump_core_after_parsing: Dump core after parsing program. + allow_unsafe_operations: Allow unsafe operations. + print_version: Print version, patchlevel and license. + print_config_summary: Print configuration summary (or a single Config.pm variable, e.g., 'archname'). + enable_warnings: Enable many useful warnings. + enable_all_warnings: Enable all warnings. + ignore_text_before_shebang_dir: Ignore text before #!perl line (optionally cd to directory). + disable_all_warnings: Disable all warnings. + """ + cmd_args: List[str] = [] + + # Input validation for program_file and program_lines + if program_file and program_lines: + raise ValueError("Cannot specify both 'program_file' and 'program_lines'. Choose one.") + + # If no script is provided, at least one of -v or -V must be true to do something. + if not program_file and not program_lines and not print_version and not print_config_summary: + raise ValueError( + "Either 'program_file' or 'program_lines' must be provided, " + "or 'print_version' or 'print_config_summary' must be true to execute Perl." + ) + + if record_separator_octal is not None: + cmd_args.append(f"-0{record_separator_octal}") + if autosplit_mode: + cmd_args.append("-a") + if unicode_features is not None: + cmd_args.append(f"-C{unicode_features}") + if check_syntax_only: + cmd_args.append("-c") + if run_debugger is not None: + cmd_args.append(f"-d:{run_debugger}" if run_debugger else "-d") + if debug_flags is not None: + cmd_args.append(f"-D{debug_flags}") + + # Handle -e (and implicitly -E if user includes it in program_lines) + if program_lines: + for line in program_lines: + cmd_args.append("-e") + cmd_args.append(line) + + if no_sitecustomize: + cmd_args.append("-f") + if split_pattern is not None: + cmd_args.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + cmd_args.append(f"-i{edit_in_place_extension}") + if include_directories: + for d in include_directories: + if not d.is_dir(): + raise ValueError(f"Include directory not found or is not a directory: {d}") + cmd_args.append("-I") + cmd_args.append(str(d)) + if line_ending_processing is not None: + cmd_args.append(f"-l{line_ending_processing}") + + # Handle -m/-M modules + if use_modules: + for module in use_modules: + cmd_args.append(f"-M{module}") # Use -M for 'use' + if no_use_modules: + for module in no_use_modules: + cmd_args.append(f"-m-{module}") # Use -m- for 'no' + + if loop_around_program: + cmd_args.append("-n") + if loop_and_print: + cmd_args.append("-p") + if rudimentary_switch_parsing: + cmd_args.append("-s") + if look_for_programfile_in_path: + cmd_args.append("-S") + if tainting_warnings: + cmd_args.append("-t") + if tainting_checks: + cmd_args.append("-T") + if dump_core_after_parsing: + cmd_args.append("-u") + if allow_unsafe_operations: + cmd_args.append("-U") + if print_version: + cmd_args.append("-v") + if print_config_summary is not None: + cmd_args.append(f"-V:{print_config_summary}" if print_config_summary else "-V") + if enable_warnings: + cmd_args.append("-w") + if enable_all_warnings: + cmd_args.append("-W") + if ignore_text_before_shebang_dir is not None: + if not ignore_text_before_shebang_dir.is_dir(): + raise ValueError(f"Directory for -x not found or is not a directory: {ignore_text_before_shebang_dir}") + cmd_args.append(f"-x{ignore_text_before_shebang_dir}") + if disable_all_warnings: + cmd_args.append("-X") + + return _run_perl_command( + command_args=cmd_args, + script_file=program_file, + script_arguments=script_arguments, + ) + +@mcp.tool() +def socket_inet_aton( + hostname: str, +) -> Dict[str, Any]: + """ + Converts a hostname string to a packed IPv4 address. + + Args: + hostname: The hostname or IPv4 address string (e.g., "localhost", "127.0.0.1"). + + Returns: + A dictionary containing the command executed, stdout (packed IP in hex), + stderr, and any output files. The stdout will be a JSON string. + """ + if not hostname: + raise ValueError("Hostname cannot be empty.") + + perl_script = f""" +use Socket qw(inet_aton); +use JSON; # Requires Perl JSON module +my $hostname = shift @ARGV; +my $packed_ip = inet_aton($hostname); +if (defined $packed_ip) {{ + my $hex_ip = unpack 'H*', $packed_ip; + print encode_json({{ packed_ip_hex => $hex_ip }}); +}} else {{ + print encode_json({{ error => "Failed to convert hostname to IP", hostname => $hostname }}); + exit 1; +}} +""" + return _run_perl_command( + command_args=[], + input_script_content=perl_script, + script_arguments=[hostname], + ) + +@mcp.tool() +def socket_inet_ntoa( + packed_ip_hex: str, +) -> Dict[str, Any]: + """ + Converts a packed IPv4 address (in hex format) to a human-readable string. + + Args: + packed_ip_hex: The packed IPv4 address in hexadecimal string format. + Must be 8 characters long (4 bytes). + + Returns: + A dictionary containing the command executed, stdout (IPv4 address string), + stderr, and any output files. The stdout will be a JSON string. + """ + if not packed_ip_hex: + raise ValueError("Packed IP (hex) cannot be empty.") + if not all(c in "0123456789abcdefABCDEF" for c in packed_ip_hex): + raise ValueError("Packed IP (hex) must be a valid hexadecimal string.") + if len(packed_ip_hex) != 8: # 4 bytes * 2 hex chars/byte + raise ValueError(f"Packed IP (hex) must be 8 characters long for IPv4, got {len(packed_ip_hex)}.") + + perl_script = f""" +use Socket qw(inet_ntoa); +use JSON; # Requires Perl JSON module +my $hex_ip = shift @ARGV; +my $packed_ip = pack 'H*', $hex_ip; +my $ip_string = inet_ntoa($packed_ip); +if (defined $ip_string) {{ + print encode_json({{ ip_address => $ip_string }}); +}} else {{ + print encode_json({{ error => "Failed to convert packed IP to string", packed_ip_hex => $hex_ip }}); + exit 1; +}} +""" + return _run_perl_command( + command_args=[], + input_script_content=perl_script, + script_arguments=[packed_ip_hex], + ) + +@mcp.tool() +def socket_inet_pton( + address_family: str, + ip_string: str, +) -> Dict[str, Any]: + """ + Converts an IP address string (IPv4 or IPv6) to a packed binary address. + + Args: + address_family: The address family constant (e.g., "AF_INET", "AF_INET6"). + Must be one of the AF_* constants from Socket. + ip_string: The IP address string (e.g., "192.168.1.1", "::1"). + + Returns: + A dictionary containing the command executed, stdout (packed IP in hex), + stderr, and any output files. The stdout will be a JSON string. + """ + if not address_family: + raise ValueError("Address family cannot be empty.") + if address_family not in ["AF_INET", "AF_INET6"]: + raise ValueError("Address family must be 'AF_INET' or 'AF_INET6'.") + if not ip_string: + raise ValueError("IP string cannot be empty.") + + perl_script = f""" +use Socket qw(inet_pton {address_family}); +use JSON; # Requires Perl JSON module +my $af = shift @ARGV; +my $ip_string = shift @ARGV; +my $packed_ip = inet_pton(eval $af, $ip_string); +if (defined $packed_ip) {{ + my $hex_ip = unpack 'H*', $packed_ip; + print encode_json({{ packed_ip_hex => $hex_ip }}); +}} else {{ + print encode_json({{ error => "Failed to convert IP string to packed IP", ip_string => $ip_string, address_family => $af }}); + exit 1; +}} +""" + return _run_perl_command( + command_args=[], + input_script_content=perl_script, + script_arguments=[address_family, ip_string], + ) + +@mcp.tool() +def socket_inet_ntop( + address_family: str, + packed_ip_hex: str, +) -> Dict[str, Any]: + """ + Converts a packed binary IP address (IPv4 or IPv6, in hex format) to a human-readable string. + + Args: + address_family: The address family constant (e.g., "AF_INET", "AF_INET6"). + Must be one of the AF_* constants from Socket. + packed_ip_hex: The packed IP address in hexadecimal string format. + Must be 8 characters for AF_INET (4 bytes) or 32 for AF_INET6 (16 bytes). + + Returns: + A dictionary containing the command executed, stdout (IP address string), + stderr, and any output files. The stdout will be a JSON string. + """ + if not address_family: + raise ValueError("Address family cannot be empty.") + if address_family not in ["AF_INET", "AF_INET6"]: + raise ValueError("Address family must be 'AF_INET' or 'AF_INET6'.") + if not packed_ip_hex: + raise ValueError("Packed IP (hex) cannot be empty.") + if not all(c in "0123456789abcdefABCDEF" for c in packed_ip_hex): + raise ValueError("Packed IP (hex) must be a valid hexadecimal string.") + + if address_family == "AF_INET" and len(packed_ip_hex) != 8: # 4 bytes + raise ValueError(f"Packed IP (hex) for AF_INET must be 8 characters long, got {len(packed_ip_hex)}.") + if address_family == "AF_INET6" and len(packed_ip_hex) != 32: # 16 bytes + raise ValueError(f"Packed IP (hex) for AF_INET6 must be 32 characters long, got {len(packed_ip_hex)}.") + + perl_script = f""" +use Socket qw(inet_ntop {address_family}); +use JSON; # Requires Perl JSON module +my $af = shift @ARGV; +my $hex_ip = shift @ARGV; +my $packed_ip = pack 'H*', $hex_ip; +my $ip_string = inet_ntop(eval $af, $packed_ip); +if (defined $ip_string) {{ + print encode_json({{ ip_address => $ip_string }}); +}} else {{ + print encode_json({{ error => "Failed to convert packed IP to string", packed_ip_hex => $hex_ip, address_family => $af }}); + exit 1; +}} +""" + return _run_perl_command( + command_args=[], + input_script_content=perl_script, + script_arguments=[address_family, packed_ip_hex], + ) + +@mcp.tool() +def socket_pack_sockaddr_in( + port: int, + ip_address_hex: str, +) -> Dict[str, Any]: + """ + Packs a port number and an IPv4 address into a sockaddr_in structure. + + Args: + port: The port number (0-65535). + ip_address_hex: The IPv4 address in packed hexadecimal string format. + Must be 8 characters long (4 bytes). + + Returns: + A dictionary containing the command executed, stdout (packed sockaddr_in in hex), + stderr, and any output files. The stdout will be a JSON string. + """ + if not (0 <= port <= 65535): + raise ValueError("Port number must be between 0 and 65535.") + if not ip_address_hex: + raise ValueError("IP address (hex) cannot be empty.") + if not all(c in "0123456789abcdefABCDEF" for c in ip_address_hex): + raise ValueError("IP address (hex) must be a valid hexadecimal string.") + if len(ip_address_hex) != 8: + raise ValueError(f"IP address (hex) must be 8 characters long for IPv4, got {len(ip_address_hex)}.") + + perl_script = f""" +use Socket qw(pack_sockaddr_in); +use JSON; # Requires Perl JSON module +my $port = shift @ARGV; +my $hex_ip = shift @ARGV; +my $packed_ip = pack 'H*', $hex_ip; +my $sockaddr = pack_sockaddr_in($port, $packed_ip); +if (defined $sockaddr) {{ + my $hex_sockaddr = unpack 'H*', $sockaddr; + print encode_json({{ sockaddr_in_hex => $hex_sockaddr }}); +}} else {{ + print encode_json({{ error => "Failed to pack sockaddr_in", port => $port, ip_address_hex => $hex_ip }}); + exit 1; +}} +""" + return _run_perl_command( + command_args=[], + input_script_content=perl_script, + script_arguments=[str(port), ip_address_hex], + ) + +@mcp.tool() +def socket_unpack_sockaddr_in( + sockaddr_in_hex: str, +) -> Dict[str, Any]: + """ + Unpacks a sockaddr_in structure (in hex format) into a port number and an IPv4 address. + + Args: + sockaddr_in_hex: The sockaddr_in structure in hexadecimal string format. + + Returns: + A dictionary containing the command executed, stdout (port and IPv4 address string), + stderr, and any output files. The stdout will be a JSON string. + """ + if not sockaddr_in_hex: + raise ValueError("sockaddr_in (hex) cannot be empty.") + if not all(c in "0123456789abcdefABCDEF" for c in sockaddr_in_hex): + raise ValueError("sockaddr_in (hex) must be a valid hexadecimal string.") + + perl_script = f""" +use Socket qw(unpack_sockaddr_in inet_ntoa); +use JSON; # Requires Perl JSON module +my $hex_sockaddr = shift @ARGV; +my $sockaddr = pack 'H*', $hex_sockaddr; +my ($port, $packed_ip) = unpack_sockaddr_in($sockaddr); +if (defined $port && defined $packed_ip) {{ + my $ip_string = inet_ntoa($packed_ip); # Convert packed IP to string for readability + print encode_json({{ port => $port, ip_address => $ip_string, packed_ip_hex => unpack('H*', $packed_ip) }}); +}} else {{ + print encode_json({{ error => "Failed to unpack sockaddr_in", sockaddr_in_hex => $hex_sockaddr }}); + exit 1; +}} +""" + return _run_perl_command( + command_args=[], + input_script_content=perl_script, + script_arguments=[sockaddr_in_hex], + ) + +@mcp.tool() +def socket_pack_sockaddr_in6( + port: int, + ip6_address_hex: str, + scope_id: int = 0, + flowinfo: int = 0, +) -> Dict[str, Any]: + """ + Packs a port number, an IPv6 address, scope ID, and flow info into a sockaddr_in6 structure. + + Args: + port: The port number (0-65535). + ip6_address_hex: The IPv6 address in packed hexadecimal string format. + Must be 32 characters long (16 bytes). + scope_id: The scope ID number (default: 0). Must be non-negative. + flowinfo: The flow label number (default: 0). Must be between 0 and 0xFFFFF. + + Returns: + A dictionary containing the command executed, stdout (packed sockaddr_in6 in hex), + stderr, and any output files. The stdout will be a JSON string. + """ + if not (0 <= port <= 65535): + raise ValueError("Port number must be between 0 and 65535.") + if not ip6_address_hex: + raise ValueError("IPv6 address (hex) cannot be empty.") + if not all(c in "0123456789abcdefABCDEF" for c in ip6_address_hex): + raise ValueError("IPv6 address (hex) must be a valid hexadecimal string.") + if len(ip6_address_hex) != 32: # 16 bytes * 2 hex chars/byte + raise ValueError(f"IPv6 address (hex) must be 32 characters long, got {len(ip6_address_hex)}.") + if not (0 <= scope_id): + raise ValueError("Scope ID must be a non-negative integer.") + if not (0 <= flowinfo <= 0xFFFFF): # Flow info is 20 bits + raise ValueError("Flow info must be between 0 and 1048575 (0xFFFFF).") + + perl_script = f""" +use Socket qw(pack_sockaddr_in6); +use JSON; # Requires Perl JSON module +my $port = shift @ARGV; +my $hex_ip6 = shift @ARGV; +my $scope_id = shift @ARGV; +my $flowinfo = shift @ARGV; +my $packed_ip6 = pack 'H*', $hex_ip6; +my $sockaddr = pack_sockaddr_in6($port, $packed_ip6, $scope_id, $flowinfo); +if (defined $sockaddr) {{ + my $hex_sockaddr = unpack 'H*', $sockaddr; + print encode_json({{ sockaddr_in6_hex => $hex_sockaddr }}); +}} else {{ + print encode_json({{ error => "Failed to pack sockaddr_in6", port => $port, ip6_address_hex => $hex_ip6, scope_id => $scope_id, flowinfo => $flowinfo }}); + exit 1; +}} +""" + return _run_perl_command( + command_args=[], + input_script_content=perl_script, + script_arguments=[str(port), ip6_address_hex, str(scope_id), str(flowinfo)], + ) + +@mcp.tool() +def socket_unpack_sockaddr_in6( + sockaddr_in6_hex: str, +) -> Dict[str, Any]: + """ + Unpacks a sockaddr_in6 structure (in hex format) into a port number, IPv6 address, scope ID, and flow info. + + Args: + sockaddr_in6_hex: The sockaddr_in6 structure in hexadecimal string format. + + Returns: + A dictionary containing the command executed, stdout (port, IPv6 address string, scope ID, flow info), + stderr, and any output files. The stdout will be a JSON string. + """ + if not sockaddr_in6_hex: + raise ValueError("sockaddr_in6 (hex) cannot be empty.") + if not all(c in "0123456789abcdefABCDEF" for c in sockaddr_in6_hex): + raise ValueError("sockaddr_in6 (hex) must be a valid hexadecimal string.") + + perl_script = f""" +use Socket qw(unpack_sockaddr_in6 inet_ntop AF_INET6); +use JSON; # Requires Perl JSON module +my $hex_sockaddr = shift @ARGV; +my $sockaddr = pack 'H*', $hex_sockaddr; +my ($port, $packed_ip6, $scope_id, $flowinfo) = unpack_sockaddr_in6($sockaddr); +if (defined $port && defined $packed_ip6) {{ + my $ip6_string = inet_ntop(AF_INET6, $packed_ip6); # Convert packed IP to string for readability + print encode_json({{ port => $port, ip6_address => $ip6_string, packed_ip6_hex => unpack('H*', $packed_ip6), scope_id => $scope_id, flowinfo => $flowinfo }}); +}} else {{ + print encode_json({{ error => "Failed to unpack sockaddr_in6", sockaddr_in6_hex => $hex_sockaddr }}); + exit 1; +}} +""" + return _run_perl_command( + command_args=[], + input_script_content=perl_script, + script_arguments=[sockaddr_in6_hex], + ) + +@mcp.tool() +def socket_pack_sockaddr_un( + path: Path, +) -> Dict[str, Any]: + """ + Packs a pathname into a sockaddr_un structure. + + Args: + path: The pathname for the Unix domain socket. + + Returns: + A dictionary containing the command executed, stdout (packed sockaddr_un in hex), + stderr, and any output files. The stdout will be a JSON string. + """ + if not path: + raise ValueError("Path cannot be empty.") + + perl_script = f""" +use Socket qw(pack_sockaddr_un); +use JSON; # Requires Perl JSON module +my $path = shift @ARGV; +my $sockaddr = pack_sockaddr_un($path); +if (defined $sockaddr) {{ + my $hex_sockaddr = unpack 'H*', $sockaddr; + print encode_json({{ sockaddr_un_hex => $hex_sockaddr }}); +}} else {{ + print encode_json({{ error => "Failed to pack sockaddr_un", path => $path }}); + exit 1; +}} +""" + return _run_perl_command( + command_args=[], + input_script_content=perl_script, + script_arguments=[str(path)], + ) + +@mcp.tool() +def socket_unpack_sockaddr_un( + sockaddr_un_hex: str, +) -> Dict[str, Any]: + """ + Unpacks a sockaddr_un structure (in hex format) into a pathname. + + Args: + sockaddr_un_hex: The sockaddr_un structure in hexadecimal string format. + + Returns: + A dictionary containing the command executed, stdout (pathname), + stderr, and any output files. The stdout will be a JSON string. + """ + if not sockaddr_un_hex: + raise ValueError("sockaddr_un (hex) cannot be empty.") + if not all(c in "0123456789abcdefABCDEF" for c in sockaddr_un_hex): + raise ValueError("sockaddr_un (hex) must be a valid hexadecimal string.") + + perl_script = f""" +use Socket qw(unpack_sockaddr_un); +use JSON; # Requires Perl JSON module +my $hex_sockaddr = shift @ARGV; +my $sockaddr = pack 'H*', $hex_sockaddr; +my ($path) = unpack_sockaddr_un($sockaddr); +if (defined $path) {{ + print encode_json({{ path => $path }}); +}} else {{ + print encode_json({{ error => "Failed to unpack sockaddr_un", sockaddr_un_hex => $hex_sockaddr }}); + exit 1; +}} +""" + return _run_perl_command( + command_args=[], + input_script_content=perl_script, + script_arguments=[sockaddr_un_hex], + ) + +@mcp.tool() +def socket_sockaddr_family( + sockaddr_hex: str, +) -> Dict[str, Any]: + """ + Returns the address family tag from a packed socket address. + + Args: + sockaddr_hex: The packed socket address in hexadecimal string format. + + Returns: + A dictionary containing the command executed, stdout (address family constant integer), + stderr, and any output files. The stdout will be a JSON string. + """ + if not sockaddr_hex: + raise ValueError("sockaddr (hex) cannot be empty.") + if not all(c in "0123456789abcdefABCDEF" for c in sockaddr_hex): + raise ValueError("sockaddr (hex) must be a valid hexadecimal string.") + + perl_script = f""" +use Socket qw(sockaddr_family); +use JSON; # Requires Perl JSON module +my $hex_sockaddr = shift @ARGV; +my $sockaddr = pack 'H*', $hex_sockaddr; +my $family = sockaddr_family($sockaddr); +if (defined $family) {{ + print encode_json({{ address_family => $family }}); +}} else {{ + print encode_json({{ error => "Failed to get sockaddr family", sockaddr_hex => $hex_sockaddr }}); + exit 1; +}} +""" + return _run_perl_command( + command_args=[], + input_script_content=perl_script, + script_arguments=[sockaddr_hex], + ) + +@mcp.tool() +def socket_pack_ip_mreq( + multiaddr_hex: str, + interface_hex: Optional[str] = None, +) -> Dict[str, Any]: + """ + Packs an IPv4 multicast address and an optional interface address into an ip_mreq structure. + + Args: + multiaddr_hex: The IPv4 multicast address in packed hexadecimal string format (8 chars). + interface_hex: The IPv4 interface address in packed hexadecimal string format (8 chars, optional, defaults to INADDR_ANY '00000000'). + + Returns: + A dictionary containing the command executed, stdout (packed ip_mreq in hex), + stderr, and any output files. The stdout will be a JSON string. + """ + if not multiaddr_hex: + raise ValueError("Multicast address (hex) cannot be empty.") + if not all(c in "0123456789abcdefABCDEF" for c in multiaddr_hex): + raise ValueError("Multicast address (hex) must be a valid hexadecimal string.") + if len(multiaddr_hex) != 8: + raise ValueError(f"Multicast address (hex) must be 8 characters long for IPv4, got {len(multiaddr_hex)}.") + + if interface_hex is not None: + if not all(c in "0123456789abcdefABCDEF" for c in interface_hex): + raise ValueError("Interface address (hex) must be a valid hexadecimal string.") + if len(interface_hex) != 8: + raise ValueError(f"Interface address (hex) must be 8 characters long for IPv4, got {len(interface_hex)}.") + else: + interface_hex = "00000000" # Represents INADDR_ANY + + perl_script = f""" +use Socket qw(pack_ip_mreq); +use JSON; # Requires Perl JSON module +my $hex_multiaddr = shift @ARGV; +my $hex_interface = shift @ARGV; +my $multiaddr = pack 'H*', $hex_multiaddr; +my $interface = pack 'H*', $hex_interface; +my $ip_mreq = pack_ip_mreq($multiaddr, $interface); +if (defined $ip_mreq) {{ + my $hex_ip_mreq = unpack 'H*', $ip_mreq; + print encode_json({{ ip_mreq_hex => $hex_ip_mreq }}); +}} else {{ + print encode_json({{ error => "Failed to pack ip_mreq", multiaddr_hex => $hex_multiaddr, interface_hex => $hex_interface }}); + exit 1; +}} +""" + return _run_perl_command( + command_args=[], + input_script_content=perl_script, + script_arguments=[multiaddr_hex, interface_hex], + ) + +@mcp.tool() +def socket_unpack_ip_mreq( + ip_mreq_hex: str, +) -> Dict[str, Any]: + """ + Unpacks an ip_mreq structure (in hex format) into an IPv4 multicast address and an interface address. + + Args: + ip_mreq_hex: The ip_mreq structure in hexadecimal string format. + + Returns: + A dictionary containing the command executed, stdout (multicast address string, interface address string), + stderr, and any output files. The stdout will be a JSON string. + """ + if not ip_mreq_hex: + raise ValueError("ip_mreq (hex) cannot be empty.") + if not all(c in "0123456789abcdefABCDEF" for c in ip_mreq_hex): + raise ValueError("ip_mreq (hex) must be a valid hexadecimal string.") + + perl_script = f""" +use Socket qw(unpack_ip_mreq inet_ntoa); +use JSON; # Requires Perl JSON module +my $hex_ip_mreq = shift @ARGV; +my $ip_mreq = pack 'H*', $hex_ip_mreq; +my ($multiaddr, $interface) = unpack_ip_mreq($ip_mreq); +if (defined $multiaddr && defined $interface) {{ + my $multiaddr_str = inet_ntoa($multiaddr); + my $interface_str = inet_ntoa($interface); + print encode_json({{ multiaddr => $multiaddr_str, interface => $interface_str, multiaddr_hex => unpack('H*', $multiaddr), interface_hex => unpack('H*', $interface) }}); +}} else {{ + print encode_json({{ error => "Failed to unpack ip_mreq", ip_mreq_hex => $ip_mreq_hex }}); + exit 1; +}} +""" + return _run_perl_command( + command_args=[], + input_script_content=perl_script, + script_arguments=[ip_mreq_hex], + ) + +@mcp.tool() +def socket_pack_ip_mreq_source( + multiaddr_hex: str, + source_hex: str, + interface_hex: Optional[str] = None, +) -> Dict[str, Any]: + """ + Packs an IPv4 multicast address, source address, and an optional interface address into an ip_mreq_source structure. + + Args: + multiaddr_hex: The IPv4 multicast address in packed hexadecimal string format (8 chars). + source_hex: The IPv4 source address in packed hexadecimal string format (8 chars). + interface_hex: The IPv4 interface address in packed hexadecimal string format (8 chars, optional, defaults to INADDR_ANY '00000000'). + + Returns: + A dictionary containing the command executed, stdout (packed ip_mreq_source in hex), + stderr, and any output files. The stdout will be a JSON string. + """ + if not multiaddr_hex: + raise ValueError("Multicast address (hex) cannot be empty.") + if not all(c in "0123456789abcdefABCDEF" for c in multiaddr_hex): + raise ValueError("Multicast address (hex) must be a valid hexadecimal string.") + if len(multiaddr_hex) != 8: + raise ValueError(f"Multicast address (hex) must be 8 characters long for IPv4, got {len(multiaddr_hex)}.") + + if not source_hex: + raise ValueError("Source address (hex) cannot be empty.") + if not all(c in "0123456789abcdefABCDEF" for c in source_hex): + raise ValueError("Source address (hex) must be a valid hexadecimal string.") + if len(source_hex) != 8: + raise ValueError(f"Source address (hex) must be 8 characters long for IPv4, got {len(source_hex)}.") + + if interface_hex is not None: + if not all(c in "0123456789abcdefABCDEF" for c in interface_hex): + raise ValueError("Interface address (hex) must be a valid hexadecimal string.") + if len(interface_hex) != 8: + raise ValueError(f"Interface address (hex) must be 8 characters long for IPv4, got {len(interface_hex)}.") + else: + interface_hex = "00000000" # Represents INADDR_ANY + + perl_script = f""" +use Socket qw(pack_ip_mreq_source); +use JSON; # Requires Perl JSON module +my $hex_multiaddr = shift @ARGV; +my $hex_source = shift @ARGV; +my $hex_interface = shift @ARGV; +my $multiaddr = pack 'H*', $hex_multiaddr; +my $source = pack 'H*', $hex_source; +my $interface = pack 'H*', $hex_interface; +my $ip_mreq_source = pack_ip_mreq_source($multiaddr, $source, $interface); +if (defined $ip_mreq_source) {{ + my $hex_ip_mreq_source = unpack 'H*', $ip_mreq_source; + print encode_json({{ ip_mreq_source_hex => $hex_ip_mreq_source }}); +}} else {{ + print encode_json({{ error => "Failed to pack ip_mreq_source", multiaddr_hex => $hex_multiaddr, source_hex => $hex_source, interface_hex => $hex_interface }}); + exit 1; +}} +""" + return _run_perl_command( + command_args=[], + input_script_content=perl_script, + script_arguments=[multiaddr_hex, source_hex, interface_hex], + ) + +@mcp.tool() +def socket_unpack_ip_mreq_source( + ip_mreq_source_hex: str, +) -> Dict[str, Any]: + """ + Unpacks an ip_mreq_source structure (in hex format) into an IPv4 multicast address, source address, and interface address. + + Args: + ip_mreq_source_hex: The ip_mreq_source structure in hexadecimal string format. + + Returns: + A dictionary containing the command executed, stdout (multicast address string, source address string, interface address string), + stderr, and any output files. The stdout will be a JSON string. + """ + if not ip_mreq_source_hex: + raise ValueError("ip_mreq_source (hex) cannot be empty.") + if not all(c in "0123456789abcdefABCDEF" for c in ip_mreq_source_hex): + raise ValueError("ip_mreq_source (hex) must be a valid hexadecimal string.") + + perl_script = f""" +use Socket qw(unpack_ip_mreq_source inet_ntoa); +use JSON; # Requires Perl JSON module +my $hex_ip_mreq_source = shift @ARGV; +my $ip_mreq_source = pack 'H*', $hex_ip_mreq_source; +my ($multiaddr, $source, $interface) = unpack_ip_mreq_source($ip_mreq_source); +if (defined $multiaddr && defined $source && defined $interface) {{ + my $multiaddr_str = inet_ntoa($multiaddr); + my $source_str = inet_ntoa($source); + my $interface_str = inet_ntoa($interface); + print encode_json({{ multiaddr => $multiaddr_str, source => $source_str, interface => $interface_str, multiaddr_hex => unpack('H*', $multiaddr), source_hex => unpack('H*', $source), interface_hex => unpack('H*', $interface) }}); +}} else {{ + print encode_json({{ error => "Failed to unpack ip_mreq_source", ip_mreq_source_hex => $ip_mreq_source_hex }}); + exit 1; +}} +""" + return _run_perl_command( + command_args=[], + input_script_content=perl_script, + script_arguments=[ip_mreq_source_hex], + ) + +@mcp.tool() +def socket_pack_ipv6_mreq( + multiaddr6_hex: str, + ifindex: int, +) -> Dict[str, Any]: + """ + Packs an IPv6 multicast address and an interface number into an ipv6_mreq structure. + + Args: + multiaddr6_hex: The IPv6 multicast address in packed hexadecimal string format (32 chars). + ifindex: The interface number. + + Returns: + A dictionary containing the command executed, stdout (packed ipv6_mreq in hex), + stderr, and any output files. The stdout will be a JSON string. + """ + if not multiaddr6_hex: + raise ValueError("IPv6 multicast address (hex) cannot be empty.") + if not all(c in "0123456789abcdefABCDEF" for c in multiaddr6_hex): + raise ValueError("IPv6 multicast address (hex) must be a valid hexadecimal string.") + if len(multiaddr6_hex) != 32: + raise ValueError(f"IPv6 multicast address (hex) must be 32 characters long, got {len(multiaddr6_hex)}.") + if not (0 <= ifindex): + raise ValueError("Interface index must be a non-negative integer.") + + perl_script = f""" +use Socket qw(pack_ipv6_mreq); +use JSON; # Requires Perl JSON module +my $hex_multiaddr6 = shift @ARGV; +my $ifindex = shift @ARGV; +my $multiaddr6 = pack 'H*', $hex_multiaddr6; +my $ipv6_mreq = pack_ipv6_mreq($multiaddr6, $ifindex); +if (defined $ipv6_mreq) {{ + my $hex_ipv6_mreq = unpack 'H*', $ipv6_mreq; + print encode_json({{ ipv6_mreq_hex => $hex_ipv6_mreq }}); +}} else {{ + print encode_json({{ error => "Failed to pack ipv6_mreq", multiaddr6_hex => $hex_multiaddr6, ifindex => $ifindex }}); + exit 1; +}} +""" + return _run_perl_command( + command_args=[], + input_script_content=perl_script, + script_arguments=[multiaddr6_hex, str(ifindex)], + ) + +@mcp.tool() +def socket_unpack_ipv6_mreq( + ipv6_mreq_hex: str, +) -> Dict[str, Any]: + """ + Unpacks an ipv6_mreq structure (in hex format) into an IPv6 multicast address and an interface number. + + Args: + ipv6_mreq_hex: The ipv6_mreq structure in hexadecimal string format. + + Returns: + A dictionary containing the command executed, stdout (IPv6 address string, interface number), + stderr, and any output files. The stdout will be a JSON string. + """ + if not ipv6_mreq_hex: + raise ValueError("ipv6_mreq (hex) cannot be empty.") + if not all(c in "0123456789abcdefABCDEF" for c in ipv6_mreq_hex): + raise ValueError("ipv6_mreq (hex) must be a valid hexadecimal string.") + + perl_script = f""" +use Socket qw(unpack_ipv6_mreq inet_ntop AF_INET6); +use JSON; # Requires Perl JSON module +my $hex_ipv6_mreq = shift @ARGV; +my $ipv6_mreq = pack 'H*', $hex_ipv6_mreq; +my ($multiaddr6, $ifindex) = unpack_ipv6_mreq($ipv6_mreq); +if (defined $multiaddr6 && defined $ifindex) {{ + my $multiaddr6_str = inet_ntop(AF_INET6, $multiaddr6); + print encode_json({{ multiaddr6 => $multiaddr6_str, ifindex => $ifindex, multiaddr6_hex => unpack('H*', $multiaddr6) }}); +}} else {{ + print encode_json({{ error => "Failed to unpack ipv6_mreq", ipv6_mreq_hex => $ipv6_mreq_hex }}); + exit 1; +}} +""" + return _run_perl_command( + command_args=[], + input_script_content=perl_script, + script_arguments=[ipv6_mreq_hex], + ) + +@mcp.tool() +def socket_getaddrinfo( + host: Optional[str] = None, + service: Optional[str] = None, + family: Optional[str] = None, # e.g., "AF_INET", "AF_INET6", "AF_UNSPEC" + socktype: Optional[str] = None, # e.g., "SOCK_STREAM", "SOCK_DGRAM" + protocol: Optional[str] = None, # e.g., "IPPROTO_TCP", "IPPROTO_UDP" + flags: Optional[List[str]] = None, # e.g., "AI_CANONNAME", "AI_PASSIVE" +) -> Dict[str, Any]: + """ + Translates the name of a host and/or service to a list of socket address structures. + + Args: + host: The hostname or IP address string to resolve. + service: The service name or port number string (e.g., "http", "80"). + family: The address family constant (e.g., "AF_INET", "AF_INET6", "AF_UNSPEC"). + Must be a valid AF_* constant string. + socktype: The socket type constant (e.g., "SOCK_STREAM", "SOCK_DGRAM"). + Must be a valid SOCK_* constant string. + protocol: The protocol constant (e.g., "IPPROTO_TCP", "IPPROTO_UDP"). + Must be a valid IPPROTO_* constant string. + flags: A list of flag constants (e.g., "AI_CANONNAME", "AI_PASSIVE"). + Must be valid AI_* constant strings. + + Returns: + A dictionary containing the command executed, stdout (JSON array of address info hashes), + stderr, and any output files. The stdout will be a JSON string. + """ + if not host and not service: + raise ValueError("Either 'host' or 'service' must be provided.") + + # Basic validation for known constants. This list is not exhaustive but covers common ones. + valid_families = ["AF_INET", "AF_INET6", "AF_UNIX", "AF_UNSPEC"] + valid_socktypes = ["SOCK_STREAM", "SOCK_DGRAM", "SOCK_RAW"] + valid_protocols = ["IPPROTO_IP", "IPPROTO_IPV6", "IPPROTO_TCP", "IPPROTO_UDP"] + valid_flags = ["AI_PASSIVE", "AI_CANONNAME", "AI_NUMERICHOST", "AI_NUMERICSERV", "AI_V4MAPPED", "AI_ALL", "AI_ADDRCONFIG"] + + if family is not None and family not in valid_families: + raise ValueError(f"Invalid address family: {family}. Must be one of {valid_families}.") + if socktype is not None and socktype not in valid_socktypes: + raise ValueError(f"Invalid socket type: {socktype}. Must be one of {valid_socktypes}.") + if protocol is not None and protocol not in valid_protocols: + raise ValueError(f"Invalid protocol: {protocol}. Must be one of {valid_protocols}.") + if flags: + for f in flags: + if f not in valid_flags: + raise ValueError(f"Invalid flag: {f}. Must be one of {valid_flags}.") + + perl_script_parts = [ + "use Socket qw(:addrinfo);", # Imports getaddrinfo and all AI_*, NI_*, EAI_* constants + "use JSON;", # Requires Perl JSON module + "my ($host, $service, $family_str, $socktype_str, $protocol_str, $flags_arr_str) = @ARGV;", + "my $hints = {};", + "if ($family_str ne '') { $hints->{family} = eval $family_str; }", + "if ($socktype_str ne '') { $hints->{socktype} = eval $socktype_str; }", + "if ($protocol_str ne '') { $hints->{protocol} = eval $protocol_str; }", + "if ($flags_arr_str ne '') {", + " my @flags_list = split(/,/, $flags_arr_str);", + " my $flags_val = 0;", + " foreach my $flag_name (@flags_list) {", + " $flags_val |= eval $flag_name;", + " }", + " $hints->{flags} = $flags_val;", + "}", + "my @res = getaddrinfo($host eq '' ? undef : $host, $service eq '' ? undef : $service, $hints);", + "my @output_results;", + "if (@res) {", + " foreach my $ai (@res) {", + " # Map integer constants back to string names for readability", + " my $family_name = $ai->{family};", + " if ($ai->{family} == AF_INET) { $family_name = 'AF_INET'; }", + " elsif ($ai->{family} == AF_INET6) { $family_name = 'AF_INET6'; }", + " elsif ($ai->{family} == AF_UNIX) { $family_name = 'AF_UNIX'; }", + " elsif ($ai->{family} == AF_UNSPEC) { $family_name = 'AF_UNSPEC'; }", + " my $socktype_name = $ai->{socktype};", + " if ($ai->{socktype} == SOCK_STREAM) { $socktype_name = 'SOCK_STREAM'; }", + " elsif ($ai->{socktype} == SOCK_DGRAM) { $socktype_name = 'SOCK_DGRAM'; }", + " elsif ($ai->{socktype} == SOCK_RAW) { $socktype_name = 'SOCK_RAW'; }", + " my $protocol_name = $ai->{protocol};", + " if ($ai->{protocol} == IPPROTO_TCP) { $protocol_name = 'IPPROTO_TCP'; }", + " elsif ($ai->{protocol} == IPPROTO_UDP) { $protocol_name = 'IPPROTO_UDP'; }", + " elsif ($ai->{protocol} == IPPROTO_IP) { $protocol_name = 'IPPROTO_IP'; }", + " elsif ($ai->{protocol} == IPPROTO_IPV6) { $protocol_name = 'IPPROTO_IPV6'; }", + " push @output_results, {", + " family => $family_name,", + " socktype => $socktype_name,", + " protocol => $protocol_name,", + " addr_hex => unpack('H*', $ai->{addr}),", # Packed address in hex + " canonname => $ai->{canonname} // undef,", + " };", + " }", + " print encode_json(\\@output_results);", + "} else {", + " print encode_json({ error => EAI_ERROR, gai_error => EAI_ERROR_STR });", # EAI_ERROR and EAI_ERROR_STR are from :addrinfo + " exit 1;", + "}", + ] + perl_script = "\n".join(perl_script_parts) + + # Prepare arguments for the Perl script + script_args = [ + host if host is not None else "", + service if service is not None else "", + family if family is not None else "", + socktype if socktype is not None else "", + protocol if protocol is not None else "", + ",".join(flags) if flags else "", + ] + + return _run_perl_command( + command_args=[], + input_script_content=perl_script, + script_arguments=script_args, + ) + +@mcp.tool() +def socket_getnameinfo( + sockaddr_hex: str, + flags: Optional[List[str]] = None, # e.g., "NI_NUMERICHOST", "NI_NUMERICSERV" +) -> Dict[str, Any]: + """ + Translates a socket address structure to a host name and service name. + + Args: + sockaddr_hex: The packed socket address structure in hexadecimal string format. + flags: A list of flag constants (e.g., "NI_NUMERICHOST", "NI_NUMERICSERV"). + Must be valid NI_* constant strings. + + Returns: + A dictionary containing the command executed, stdout (JSON hash with host and service), + stderr, and any output files. The stdout will be a JSON string. + """ + if not sockaddr_hex: + raise ValueError("sockaddr (hex) cannot be empty.") + if not all(c in "0123456789abcdefABCDEF" for c in sockaddr_hex): + raise ValueError("sockaddr (hex) must be a valid hexadecimal string.") + + valid_flags = ["NI_NUMERICHOST", "NI_NUMERICSERV", "NI_NOFQDN", "NI_NAMEREQD", "NI_DGRAM"] + if flags: + for f in flags: + if f not in valid_flags: + raise ValueError(f"Invalid flag: {f}. Must be one of {valid_flags}.") + + perl_script_parts = [ + "use Socket qw(:addrinfo);", # Imports getnameinfo and all NI_*, EAI_* constants + "use JSON;", # Requires Perl JSON module + "my ($hex_sockaddr, $flags_arr_str) = @ARGV;", + "my $sockaddr = pack 'H*', $hex_sockaddr;", + "my $flags_val = 0;", + "if ($flags_arr_str ne '') {", + " my @flags_list = split(/,/, $flags_arr_str);", + " foreach my $flag_name (@flags_list) {", + " $flags_val |= eval $flag_name;", + " }", + "}", + "my ($host, $service) = getnameinfo($sockaddr, $flags_val);", + "if (defined $host && defined $service) {", + " print encode_json({ host => $host, service => $service });", + "} else {", + " print encode_json({ error => EAI_ERROR, gai_error => EAI_ERROR_STR });", + " exit 1;", + "}", + ] + perl_script = "\n".join(perl_script_parts) + + # Prepare arguments for the Perl script + script_args = [ + sockaddr_hex, + ",".join(flags) if flags else "", + ] + + return _run_perl_command( + command_args=[], + input_script_content=perl_script, + script_arguments=script_args, + ) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/app/perl-socket_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/app/perl-socket_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..74a81eafb89d7515d04e23bc775b913e18fd221d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/app/perl-socket_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/app/perl-socket_server.py') +SERVER_NAME = 'biosci_perl_socket' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..9dc34905ecd727dd819199412f50347b4a9231ae --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-socket: + build: . + image: mcp-perl-socket:latest + container_name: mcp-perl-socket + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-socket + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ffdd4ed4de1c37747f2b6f1c25a5cf7eccc441ff --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-socket + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-socket/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..087f4f752018a2a44d076efcb3b797af82740a45 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-sort-naturally via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-sort-naturally -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-sort-naturally_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-sort-naturally_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-sort-naturally_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/app/perl-sort-naturally_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/app/perl-sort-naturally_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ce982451c25a45bda82def584b0a284907c9a211 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/app/perl-sort-naturally_server.py @@ -0,0 +1,121 @@ +from typing import Optional +import subprocess +from pathlib import Path + +@mcp.tool() +def nsort( + input_file: str, + output_file: Optional[str] = None, +) -> dict: + """ + Performs a case-insensitive natural sort on the lines of a file. + Natural sorting treats numeral parts numerically (e.g., "10" comes after "2"). + + Args: + input_file: Path to the input file to be sorted. + output_file: Optional path to save the sorted output. If not provided, output is returned in stdout. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + # Construct the Perl one-liner using the Sort::Naturally module + # nsort is the case-insensitive version + perl_script = "print nsort(<>)" + command = ["perl", "-MSort::Naturally", "-e", perl_script, str(input_path)] + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + + stdout_content = result.stdout + + if output_file: + output_path = Path(output_file) + output_path.write_text(stdout_content) + return { + "command_executed": " ".join(command), + "stdout": f"Output written to {output_file}", + "stderr": result.stderr, + "output_files": [str(output_path)] + } + + return { + "command_executed": " ".join(command), + "stdout": stdout_content, + "stderr": result.stderr, + "output_files": [] + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed. Ensure 'perl-sort-naturally' is installed. Error: {str(e)}" + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def sort_naturally( + input_file: str, + output_file: Optional[str] = None, +) -> dict: + """ + Performs a case-sensitive natural sort on the lines of a file. + Natural sorting treats numeral parts numerically (e.g., "10" comes after "2"). + + Args: + input_file: Path to the input file to be sorted. + output_file: Optional path to save the sorted output. If not provided, output is returned in stdout. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + # Construct the Perl one-liner using the Sort::Naturally module + # sort_naturally is the case-sensitive version + perl_script = "print sort_naturally(<>)" + command = ["perl", "-MSort::Naturally", "-e", perl_script, str(input_path)] + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + + stdout_content = result.stdout + + if output_file: + output_path = Path(output_file) + output_path.write_text(stdout_content) + return { + "command_executed": " ".join(command), + "stdout": f"Output written to {output_file}", + "stderr": result.stderr, + "output_files": [str(output_path)] + } + + return { + "command_executed": " ".join(command), + "stdout": stdout_content, + "stderr": result.stderr, + "output_files": [] + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed. Ensure 'perl-sort-naturally' is installed. Error: {str(e)}" + } + except Exception as e: + return {"error": str(e)} diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/app/perl-sort-naturally_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/app/perl-sort-naturally_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..73fe893c1eb545f97324437b3042388b3dba1c55 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/app/perl-sort-naturally_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/app/perl-sort-naturally_server.py') +SERVER_NAME = 'biosci_perl_sort_naturally' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..111c06639193290d0cd78a16c2a5793aa1edd559 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-sort-naturally: + build: . + image: mcp-perl-sort-naturally:latest + container_name: mcp-perl-sort-naturally + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-sort-naturally + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8f39ce296e8a3c580c3cceebb69a85f41e6d8c54 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-sort-naturally + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sort-naturally/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7fc8c5b8680b8e98e822ec5145ab3f07e3c9f935 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-spreadsheet-parseexcel via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-spreadsheet-parseexcel -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-spreadsheet-parseexcel_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-spreadsheet-parseexcel_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-spreadsheet-parseexcel_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/app/perl-spreadsheet-parseexcel_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/app/perl-spreadsheet-parseexcel_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8e2836f772d8229f8dbfffd402ad9d413e019055 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/app/perl-spreadsheet-parseexcel_server.py @@ -0,0 +1,344 @@ +import subprocess +import json +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def parse_excel_summary( + input_file: str, +) -> Dict[str, Any]: + """ + Summarize an Excel (.xls) file, listing all worksheets and their dimensions. + + Args: + input_file: Path to the Excel (.xls) file. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + if not input_path.is_file(): + return {"error": f"Input path is not a file: {input_file}"} + if input_path.suffix.lower() not in ['.xls']: + return {"error": f"Input file must be an .xls Excel file: {input_file}"} + + # Perl script to extract workbook metadata + # Using str.format to avoid f-string brace escaping issues with Perl syntax + perl_script_template = """ + use Spreadsheet::ParseExcel; + use JSON; + my $parser = Spreadsheet::ParseExcel->new(); + my $workbook = $parser->parse('{input_path_str}'); + if (!defined $workbook) {{ + die $parser->error(); + }} + my @sheets; + for my $worksheet ($workbook->worksheets()) {{ + my ($row_min, $row_max) = $worksheet->row_range(); + my ($col_min, $col_max) = $worksheet->col_range(); + push @sheets, {{ + name => $worksheet->get_name(), + rows => ($row_max - $row_min + 1), + cols => ($col_max - $col_min + 1), + row_range => [$row_min, $row_max], + col_range => [$col_min, $col_max] + }}; + }} + print encode_json(\\@sheets); + """ + perl_script = perl_script_template.format(input_path_str=str(input_path)) + + try: + result = subprocess.run( + ["perl", "-e", perl_script], + capture_output=True, + text=True, + check=True + ) + sheets_info = json.loads(result.stdout) + return { + "command_executed": f"perl -MSpreadsheet::ParseExcel ... {input_file}", + "file": input_file, + "worksheets": sheets_info, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to parse Excel file", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd, + "output_files": [] + } + except json.JSONDecodeError as e: + return { + "error": "Failed to decode JSON output from Perl script", + "stdout": result.stdout, + "stderr": result.stderr, + "command_executed": f"perl -MSpreadsheet::ParseExcel ... {input_file}", + "output_files": [] + } + +@mcp.tool() +def parse_excel_sheet_to_csv( + input_file: str, + sheet_index: int = 0, + output_csv: Optional[str] = None, +) -> Dict[str, Any]: + """ + Convert a specific worksheet from an Excel (.xls) file to a CSV file. + + Args: + input_file: Path to the Excel (.xls) file. + sheet_index: Index of the worksheet to extract (starting from 0). Must be non-negative. + output_csv: Optional path for the output CSV. If not provided, returns content in stdout. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + if not input_path.is_file(): + return {"error": f"Input path is not a file: {input_file}"} + if input_path.suffix.lower() not in ['.xls']: + return {"error": f"Input file must be an .xls Excel file: {input_file}"} + if sheet_index < 0: + return {"error": f"Sheet index must be non-negative, got: {sheet_index}"} + + # Perl script to extract a sheet as CSV + # Using str.format to avoid f-string brace escaping issues with Perl syntax + perl_script_template = """ + use Spreadsheet::ParseExcel; + my $parser = Spreadsheet::ParseExcel->new(); + my $workbook = $parser->parse('{input_path_str}'); + die $parser->error() if !defined $workbook; + my $worksheet = $workbook->worksheet({sheet_index_val}); + die "Worksheet at index {sheet_index_val} not found" if !defined $worksheet; + + my ($row_min, $row_max) = $worksheet->row_range(); + my ($col_min, $col_max) = $worksheet->col_range(); + + for my $row ($row_min .. $row_max) {{ + my @row_data; + for my $col ($col_min .. $col_max) {{ + my $cell = $worksheet->get_cell($row, $col); + if ($cell) {{ + my $val = $cell->value(); + $val =~ s/"/""/g; # Escape quotes + push @row_data, qq("$val"); + }} else {{ + push @row_data, '""'; + }} + }} + print join(",", @row_data) . "\\n"; + }} + """ + perl_script = perl_script_template.format( + input_path_str=str(input_path), + sheet_index_val=sheet_index + ) + + try: + result = subprocess.run( + ["perl", "-e", perl_script], + capture_output=True, + text=True, + check=True + ) + + output_files = [] + stdout_message = result.stdout + if output_csv: + out_path = Path(output_csv) + try: + out_path.write_text(result.stdout) + output_files.append(str(out_path)) + stdout_message = f"Content written to file: {output_csv}" + except IOError as e: + return { + "error": f"Failed to write output CSV to {output_csv}: {e}", + "stdout": result.stdout, + "stderr": result.stderr, + "command_executed": f"perl -MSpreadsheet::ParseExcel (extract sheet {sheet_index})", + "output_files": [] + } + + return { + "command_executed": f"perl -MSpreadsheet::ParseExcel (extract sheet {sheet_index})", + "stdout": stdout_message, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "error": f"Failed to extract sheet {sheet_index}", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd, + "output_files": [] + } + +@mcp.tool() +def parse_excel_to_json( + input_file: str, +) -> Dict[str, Any]: + """ + Convert the entire content of an Excel (.xls) file into a JSON structure. + + Args: + input_file: Path to the Excel (.xls) file. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + if not input_path.is_file(): + return {"error": f"Input path is not a file: {input_file}"} + if input_path.suffix.lower() not in ['.xls']: + return {"error": f"Input file must be an .xls Excel file: {input_file}"} + + # Using str.format to avoid f-string brace escaping issues with Perl syntax + perl_script_template = """ + use Spreadsheet::ParseExcel; + use JSON; + my $parser = Spreadsheet::ParseExcel->new(); + my $workbook = $parser->parse('{input_path_str}'); + die $parser->error() if !defined $workbook; + + my %data; + for my $worksheet ($workbook->worksheets()) {{ + my $name = $worksheet->get_name(); + my ($row_min, $row_max) = $worksheet->row_range(); + my ($col_min, $col_max) = $worksheet->col_range(); + my @rows; + for my $row ($row_min .. $row_max) {{ + my @row_data; + for my $col ($col_min .. $col_max) {{ + my $cell = $worksheet->get_cell($row, $col); + push @row_data, $cell ? $cell->value() : undef; + }} + push @rows, \\@row_data; + }} + $data{{$name}} = \\@rows; + }} + print encode_json(\\%data); + """ + perl_script = perl_script_template.format(input_path_str=str(input_path)) + + try: + result = subprocess.run( + ["perl", "-e", perl_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "perl -MSpreadsheet::ParseExcel -MJSON ...", + "data": json.loads(result.stdout), + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to convert workbook to JSON", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd, + "output_files": [] + } + except json.JSONDecodeError as e: + return { + "error": "Failed to decode JSON output from Perl script", + "stdout": result.stdout, + "stderr": result.stderr, + "command_executed": "perl -MSpreadsheet::ParseExcel -MJSON ...", + "output_files": [] + } + +@mcp.tool() +def parse_excel_cell( + input_file: str, + sheet_index: int = 0, + row: int = 0, + col: int = 0, +) -> Dict[str, Any]: + """ + Retrieve the value and format of a specific cell in an Excel (.xls) file. + + Args: + input_file: Path to the Excel (.xls) file. + sheet_index: Index of the worksheet (starting from 0). Must be non-negative. + row: Row index (starting from 0). Must be non-negative. + col: Column index (starting from 0). Must be non-negative. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + if not input_path.is_file(): + return {"error": f"Input path is not a file: {input_file}"} + if input_path.suffix.lower() not in ['.xls']: + return {"error": f"Input file must be an .xls Excel file: {input_file}"} + if sheet_index < 0: + return {"error": f"Sheet index must be non-negative, got: {sheet_index}"} + if row < 0: + return {"error": f"Row index must be non-negative, got: {row}"} + if col < 0: + return {"error": f"Column index must be non-negative, got: {col}"} + + # Using str.format to avoid f-string brace escaping issues with Perl syntax + perl_script_template = """ + use Spreadsheet::ParseExcel; + use JSON; + my $parser = Spreadsheet::ParseExcel->new(); + my $workbook = $parser->parse('{input_path_str}'); + die $parser->error() if !defined $workbook; + my $worksheet = $workbook->worksheet({sheet_index_val}); + die "Sheet not found" if !defined $worksheet; + + my $cell = $worksheet->get_cell({row_val}, {col_val}); + if ($cell) {{ + print encode_json({{ + value => $cell->value(), + unformatted => $cell->unformatted(), + type => $cell->type(), + format => $cell->{{FormatNo}} + }}); + }} else {{ + print encode_json({{value => undef, status => "empty"}}); + }} + """ + perl_script = perl_script_template.format( + input_path_str=str(input_path), + sheet_index_val=sheet_index, + row_val=row, + col_val=col + ) + + try: + result = subprocess.run( + ["perl", "-e", perl_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"perl -MSpreadsheet::ParseExcel (get cell {row},{col})", + "cell_data": json.loads(result.stdout), + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to retrieve cell data", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd, + "output_files": [] + } + except json.JSONDecodeError as e: + return { + "error": "Failed to decode JSON output from Perl script", + "stdout": result.stdout, + "stderr": result.stderr, + "command_executed": f"perl -MSpreadsheet::ParseExcel (get cell {row},{col})", + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/app/perl-spreadsheet-parseexcel_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/app/perl-spreadsheet-parseexcel_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f00628b0219f5634688d08be43d8889e34877565 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/app/perl-spreadsheet-parseexcel_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/app/perl-spreadsheet-parseexcel_server.py') +SERVER_NAME = 'biosci_perl_spreadsheet_parseexcel' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2cbb77445cc214574474f6cd390d37024acf5d14 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-spreadsheet-parseexcel: + build: . + image: mcp-perl-spreadsheet-parseexcel:latest + container_name: mcp-perl-spreadsheet-parseexcel + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-spreadsheet-parseexcel + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4909298335736f9d45a848ad0f0812b132d943a8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-spreadsheet-parseexcel + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0d19939cd82e43d1b0a7dfd52fbd5cd927ce86b2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-spreadsheet-writeexcel via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-spreadsheet-writeexcel -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-spreadsheet-writeexcel_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-spreadsheet-writeexcel_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-spreadsheet-writeexcel_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/app/perl-spreadsheet-writeexcel_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/app/perl-spreadsheet-writeexcel_server.py new file mode 100644 index 0000000000000000000000000000000000000000..349af6b5f676e3abe5ac72c9d53a364d0942aa18 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/app/perl-spreadsheet-writeexcel_server.py @@ -0,0 +1,221 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# In a real MCP implementation, the mcp module would be imported. +# For this exercise, we assume it's available and the decorator works as expected. +# import mcp + +# This is a placeholder for the MCP decorator. +# In a real environment, this would be provided by the MCP framework. +def tool(): + def decorator(func): + return func + return decorator + +mcp = type('mcp', (), {'tool': tool}) + + +@mcp.tool() +def run_perl_interpreter( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + program_line: Optional[List[str]] = None, + program_line_features: Optional[List[str]] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + use_debugger: bool = False, + debugger_name: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + in_place_edit_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending: Optional[str] = None, + use_module: Optional[List[str]] = None, + no_module: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + parse_switches: bool = False, + search_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core: bool = False, + unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: bool = False, + print_config_variable: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang: bool = False, + cd_to_directory_for_x: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> Dict[str, Any]: + """ + Wraps the Perl interpreter, allowing execution of scripts like those using Spreadsheet::WriteExcel. + + This tool provides a comprehensive interface to the Perl interpreter's command-line options. + It is designed to run any Perl script, including those that leverage libraries such as + Spreadsheet::WriteExcel to create Excel files. + + Args: + programfile: Path to the Perl program file to execute. + arguments: A list of arguments to be passed to the program file. + program_line: Specifies a line of the program using the -e switch. Can be used multiple times. + program_line_features: Like -e, but enables all optional features (-E switch). + record_separator: Specify record separator (e.g., '\\0') using the -0 switch. + autosplit: Enable autosplit mode with -n or -p (splits $_ into @F) using the -a switch. + unicode_features: Enable the listed Unicode features using the -C switch. + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks) using the -c switch. + use_debugger: Run the program under the debugger (-d switch). + debugger_name: Specify a specific debugger to use (e.g., -d:DebuggerName). + debugging_flags: Set debugging flags (-D switch). + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup (-f switch). + split_pattern: Specify the split() pattern for the -a switch (-F switch). + in_place_edit_extension: Edit <> files in place. Makes a backup if an extension is supplied (-i switch). + include_directories: Specify @INC/#include directory. Can be used multiple times (-I switch). + line_ending: Enable line ending processing, specifies line terminator (-l switch). + use_module: Execute "use module..." before executing the program (-M switch). + no_module: Execute "no module..." before executing the program (-m switch). + loop_around_program: Assume "while (<>) { ... }" loop around the program (-n switch). + loop_and_print: Assume loop like -n but also print the line, like sed (-p switch). + parse_switches: Enable rudimentary parsing for switches after the program file (-s switch). + search_path: Look for the program file using the PATH environment variable (-S switch). + tainting_warnings: Enable tainting warnings (-t switch). + tainting_checks: Enable tainting checks (-T switch). + dump_core: Dump core after parsing the program (-u switch). + unsafe_operations: Allow unsafe operations (-U switch). + print_version: Print version, patchlevel, and license (-v switch). + print_config_summary: Print configuration summary (-V switch). + print_config_variable: Print a single Config.pm variable (-V:variable). + enable_warnings: Enable many useful warnings (-w switch). + enable_all_warnings: Enable all warnings (-W switch). + ignore_text_before_shebang: Ignore text before #!perl line (-x switch). + cd_to_directory_for_x: Optionally cd to a directory with the -x switch. + disable_all_warnings: Disable all warnings (-X switch). + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # Input Validation + if not any([programfile, program_line, program_line_features, print_version, print_config_summary, print_config_variable]): + raise ValueError("Execution requirement missing: you must provide a 'programfile', 'program_line', 'program_line_features', or request version/config info.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"Program file not found: {programfile}") + + if include_directories: + for d in include_directories: + if not d.is_dir(): + raise NotADirectoryError(f"Include directory not found: {d}") + + if cd_to_directory_for_x and not cd_to_directory_for_x.is_dir(): + raise NotADirectoryError(f"Directory for -x option not found: {cd_to_directory_for_x}") + + if debugger_name and not use_debugger: + raise ValueError("'debugger_name' can only be used when 'use_debugger' is True.") + + if cd_to_directory_for_x and not ignore_text_before_shebang: + raise ValueError("'cd_to_directory_for_x' can only be used when 'ignore_text_before_shebang' is True.") + + # Command Construction + cmd = ["perl"] + + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if use_debugger: + cmd.append(f"-d{':' + debugger_name if debugger_name else ''}") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if in_place_edit_extension is not None: + cmd.append(f"-i{in_place_edit_extension}") + if include_directories: + for d in include_directories: + cmd.extend(["-I", str(d)]) + if line_ending is not None: + cmd.append(f"-l{line_ending}") + if use_module: + for m in use_module: + cmd.extend(["-M", m]) + if no_module: + for m in no_module: + cmd.extend(["-m", m]) + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if parse_switches: + cmd.append("-s") + if search_path: + cmd.append("-S") + if tainting_warnings: + cmd.append("-t") + if tainting_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config_summary or print_config_variable: + cmd.append(f"-V{':' + print_config_variable if print_config_variable else ''}") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if ignore_text_before_shebang: + cmd.append(f"-x{str(cd_to_directory_for_x) if cd_to_directory_for_x else ''}") + if disable_all_warnings: + cmd.append("-X") + if program_line: + for line in program_line: + cmd.extend(["-e", line]) + if program_line_features: + for line in program_line_features: + cmd.extend(["-E", line]) + + if programfile: + cmd.append(str(programfile)) + if arguments: + cmd.extend(arguments) + + command_executed = " ".join(cmd) + + # Subprocess Execution + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] # The interpreter itself doesn't guarantee output files + } + except FileNotFoundError: + raise RuntimeError("The 'perl' executable was not found in the system's PATH. Please ensure Perl is installed and accessible.") + except subprocess.CalledProcessError as e: + # For failed executions, return a structured error with captured output + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed with return code {e.returncode}", + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/app/perl-spreadsheet-writeexcel_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/app/perl-spreadsheet-writeexcel_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6b7ea7417274587fbd4004ac0014a021cb472d6c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/app/perl-spreadsheet-writeexcel_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/app/perl-spreadsheet-writeexcel_server.py') +SERVER_NAME = 'biosci_perl_spreadsheet_writeexcel' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..830345fa6ac5dad62b8734e80899362e4f929809 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-spreadsheet-writeexcel: + build: . + image: mcp-perl-spreadsheet-writeexcel:latest + container_name: mcp-perl-spreadsheet-writeexcel + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-spreadsheet-writeexcel + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..911fe58de269ce55c63564047603fa5a68bc15e9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-spreadsheet-writeexcel + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..62b855dee06b42f75ad5319df2426e8452aa596d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-statistics-basic via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-statistics-basic -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-statistics-basic_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-statistics-basic_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-statistics-basic_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/app/perl-statistics-basic_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/app/perl-statistics-basic_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5be3aa53be4f03227086413e0679a63415ee1a9c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/app/perl-statistics-basic_server.py @@ -0,0 +1,250 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any +from pydantic import Field # Used for default_factory to handle mutable default arguments for lists + +@mcp.tool() +def run_perl_script( + program_file: Optional[Path] = None, + program_arguments: List[str] = Field(default_factory=list), + execute_program_lines: List[str] = Field(default_factory=list), + execute_program_lines_extended: List[str] = Field(default_factory=list), + record_separator_octal: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debug_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: List[Path] = Field(default_factory=list), + line_ending_terminator_octal: Optional[str] = None, + use_modules: List[str] = Field(default_factory=list), + no_modules: List[str] = Field(default_factory=list), + assume_loop_n: bool = False, + assume_loop_p: bool = False, + parse_switches_after_programfile: bool = False, + look_for_programfile_in_path: bool = False, + enable_tainting_warnings: bool = False, + enable_tainting_checks: bool = False, + dump_core_after_parsing: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary_variable: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang_dir: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> Dict[str, Any]: + """ + Executes a Perl script or Perl code with various interpreter options. + + This tool wraps the general 'perl' interpreter, allowing the execution of any Perl script + or one-liner, including those that utilize Perl modules like 'Statistics::Basic'. + The parameters correspond to the command-line switches of the 'perl' interpreter + as described by 'perl -h'. + + Args: + program_file: Path to the Perl script to execute. If not provided, + at least one of `execute_program_lines` or `execute_program_lines_extended` + must be supplied. + program_arguments: Arguments to be passed to the Perl script itself. + execute_program_lines: One or more lines of Perl program code to execute. + Equivalent to '-e program'. Can be specified multiple times. + execute_program_lines_extended: One or more lines of Perl program code to execute, + like '-e', but enables all optional features. + Equivalent to '-E program'. Can be specified multiple times. + record_separator_octal: Specify record separator. If an empty string (""), + it defaults to '\0'. Otherwise, provide an octal string. + Equivalent to '-0[octal]'. + autosplit: Enable autosplit mode with -n or -p (splits $_ into @F). Equivalent to '-a'. + unicode_features: Enables the listed Unicode features. Equivalent to '-C[number/list]'. + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). Equivalent to '-c'. + debugger: Run program under debugger. Optionally specify debugger name. + Equivalent to '-d[:debugger]'. + debug_flags: Set debugging flags (argument is a bit mask or alphabets). + Equivalent to '-D[number/list]'. + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. Equivalent to '-f'. + split_pattern: split() pattern for -a switch (//'s are optional). + Equivalent to '-F/pattern/'. + edit_in_place_extension: Edit <> files in place. Makes backup if extension supplied. + If an empty string (""), no backup is made. + Equivalent to '-i[extension]'. + include_directories: Specify @INC/#include directory. Can be specified multiple times. + Equivalent to '-Idirectory'. + line_ending_terminator_octal: Enable line ending processing, specifies line terminator. + If an empty string (""), enables processing with default terminator. + Otherwise, provide an octal string. Equivalent to '-l[octal]'. + use_modules: Execute "use module..." before executing program. Equivalent to '-mmodule' or '-Mmodule'. + Provide module names (e.g., "Statistics::Basic"). + no_modules: Execute "no module..." before executing program. Equivalent to '-m-module' or '-M-module'. + Provide module names. + assume_loop_n: Assume "while (<>) { ... }" loop around program. Equivalent to '-n'. + assume_loop_p: Assume loop like -n but print line also, like sed. Equivalent to '-p'. + parse_switches_after_programfile: Enable rudimentary parsing for switches after programfile. + Equivalent to '-s'. + look_for_programfile_in_path: Look for programfile using PATH environment variable. + Equivalent to '-S'. + enable_tainting_warnings: Enable tainting warnings. Equivalent to '-t'. + enable_tainting_checks: Enable tainting checks. Equivalent to '-T'. + dump_core_after_parsing: Dump core after parsing program. Equivalent to '-u'. + allow_unsafe_operations: Allow unsafe operations. Equivalent to '-U'. + print_version: Print version, patchlevel and license. Equivalent to '-v'. + print_config_summary_variable: Print configuration summary. Optionally specify a single + Config.pm variable. If an empty string (""), prints full summary. + Equivalent to '-V[:variable]'. + enable_warnings: Enable many useful warnings. Equivalent to '-w'. + enable_all_warnings: Enable all warnings. Equivalent to '-W'. + ignore_text_before_shebang_dir: Ignore text before #!perl line. Optionally cd to directory. + If an empty string (""), ignores text without changing directory. + Otherwise, provide a directory path. Equivalent to '-x[directory]'. + disable_all_warnings: Disable all warnings. Equivalent to '-X'. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + cmd = ["perl"] + output_files: List[Path] = [] + + # --- Input Validation --- + if not program_file and not execute_program_lines and not execute_program_lines_extended: + raise ValueError("Either 'program_file' or at least one of '-e'/'E' program lines must be provided.") + + if program_file: + if not program_file.is_file(): + raise FileNotFoundError(f"Program file not found: {program_file}") + + if assume_loop_n and assume_loop_p: + raise ValueError("Options '-n' and '-p' are mutually exclusive.") + + if disable_all_warnings and (enable_warnings or enable_all_warnings): + raise ValueError("Option '-X' (disable all warnings) conflicts with '-w' or '-W' (enable warnings).") + + if ignore_text_before_shebang_dir: + if not ignore_text_before_shebang_dir.is_dir(): + raise NotADirectoryError(f"Directory for -x option not found: {ignore_text_before_shebang_dir}") + + for d in include_directories: + if not d.is_dir(): + raise NotADirectoryError(f"Include directory not found: {d}") + + # --- Construct Command --- + + # Options with optional arguments that are appended directly + if record_separator_octal is not None: + cmd.append(f"-0{record_separator_octal}") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if debugger is not None: + cmd.append(f"-d{debugger}") + if debug_flags is not None: + cmd.append(f"-D{debug_flags}") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + cmd.append(f"-i{edit_in_place_extension}") + if line_ending_terminator_octal is not None: + cmd.append(f"-l{line_ending_terminator_octal}") + if print_config_summary_variable is not None: + cmd.append(f"-V{print_config_summary_variable}") + if ignore_text_before_shebang_dir is not None: + cmd.append(f"-x{ignore_text_before_shebang_dir}") + + # Boolean flags + if autosplit: + cmd.append("-a") + if check_syntax_only: + cmd.append("-c") + if no_sitecustomize: + cmd.append("-f") + if assume_loop_n: + cmd.append("-n") + if assume_loop_p: + cmd.append("-p") + if parse_switches_after_programfile: + cmd.append("-s") + if look_for_programfile_in_path: + cmd.append("-S") + if enable_tainting_warnings: + cmd.append("-t") + if enable_tainting_checks: + cmd.append("-T") + if dump_core_after_parsing: + cmd.append("-u") + if allow_unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if disable_all_warnings: + cmd.append("-X") + + # List-based options + for d in include_directories: + cmd.extend(["-I", str(d)]) + + for module in use_modules: + cmd.extend(["-M", module]) # Using -M for 'use' + + for module in no_modules: + cmd.extend(["-m-", module]) # Using -m- for 'no' + + # Program lines (-e, -E) + for line in execute_program_lines: + cmd.extend(["-e", line]) + for line in execute_program_lines_extended: + cmd.extend(["-E", line]) + + # Add '--' if there are program arguments and a script/code to run. + # This separates Perl's own switches from the script's arguments. + if program_arguments and (program_file or execute_program_lines or execute_program_lines_extended): + cmd.append("--") + + # Program file + if program_file: + cmd.append(str(program_file)) + + # Program arguments + for arg in program_arguments: + cmd.append(arg) + + command_executed = " ".join(str(arg) for arg in cmd) + + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": output_files, + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Is Perl installed and in your PATH?", + "error": "Perl executable not found.", + "returncode": 127, + "output_files": output_files, + } + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/app/perl-statistics-basic_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/app/perl-statistics-basic_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b284496e8cf71c75f87afa7271dde74277159e67 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/app/perl-statistics-basic_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/app/perl-statistics-basic_server.py') +SERVER_NAME = 'biosci_perl_statistics_basic' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..b1d7df7d2e4c819fb3e40d027bff1ad512c88c48 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/app/requirements.txt @@ -0,0 +1 @@ +pydantic==2.13.3 diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d3e719805db62b6d4544aeca1fa5398edd0ad50c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-statistics-basic: + build: . + image: mcp-perl-statistics-basic:latest + container_name: mcp-perl-statistics-basic + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-statistics-basic + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f7a2ac684827a09a1ffd8ce1150bcdfaccd89607 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-statistics-basic + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..789aa886bf8bd292297707f78435d515c716853d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-basic/requirements.txt @@ -0,0 +1,3 @@ +pydantic==2.13.3 +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..889dd321e2be8b6e49e4905db643661f3c5fdc9b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-statistics-descriptive via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-statistics-descriptive -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-statistics-descriptive_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-statistics-descriptive_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-statistics-descriptive_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/app/perl-statistics-descriptive_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/app/perl-statistics-descriptive_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a5cc96cd9e16d0e77466cc8a5257d404b1c6da71 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/app/perl-statistics-descriptive_server.py @@ -0,0 +1,170 @@ +import subprocess +import tempfile +import json +from pathlib import Path +from typing import Optional, Dict, Any + +# The user specified "NO NEED to import mcp", so this is a placeholder. +# In a real MCP environment, you would use `from mcp import tool`. +class McpPlaceholder: + def tool(self, *args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = McpPlaceholder() + +# This Perl script uses the Statistics::Descriptive module to perform calculations. +# It reads numbers from an input file and prints results as a JSON object to stdout. +_PERL_SCRIPT_TEMPLATE = """ +use strict; +use warnings; +use Statistics::Descriptive; +use JSON; + +# Ensure the script receives exactly one argument: the input file path. +if (@ARGV != 1) { + die "Usage: $0 \\n"; +} +my $input_file = $ARGV[0]; + +# Open the input file for reading, with error handling. +open(my $fh, '<', $input_file) or die "Error: Could not open file '$input_file' for reading: $!\\n"; + +# Read all numbers from the file, skipping any non-numeric lines. +my @data; +while (my $line = <$fh>) { + chomp $line; + # A robust regex to match integers and floating-point numbers (including scientific notation). + if ($line =~ /^-?[\d.]+(?:e-?\d+)?$/i) { + push @data, $line; + } +} +close $fh; + +# Check if any valid numeric data was found in the file. +if (@data == 0) { + die "Error: No numeric data found in '$input_file'\\n"; +} + +# Create a full statistics object. +my $stat = Statistics::Descriptive::Full->new(); + +# Add the collected data to the stats object. +$stat->add_data(@data); + +# Calculate a comprehensive set of descriptive statistics. +# Using eval blocks to handle cases where a statistic cannot be calculated (e.g., mode for unique data). +my %results = ( + count => $stat->count(), + mean => $stat->mean(), + median => $stat->median(), + mode => eval { $stat->mode() }, + sum => $stat->sum(), + variance => $stat->variance(), + standard_deviation => $stat->standard_deviation(), + min => $stat->min(), + max => $stat->max(), + sample_range => $stat->sample_range(), + skewness => $stat->skewness(), + kurtosis => $stat->kurtosis(), + percentile_25 => $stat->percentile(25), + percentile_50 => $stat->percentile(50), + percentile_75 => $stat->percentile(75) +); + +# Convert the results hash to a JSON string and print it to STDOUT. +print encode_json(\\%results); +""" + +@mcp.tool() +def calculate_descriptive_statistics( + input_file: Path, + output_file: Optional[Path] = None +) -> Dict[str, Any]: + """ + Calculates descriptive statistics for a list of numbers using the Perl Statistics::Descriptive module. + + This tool reads numbers from an input file (one per line), ignoring any non-numeric lines. + It computes various statistics like mean, median, standard deviation, etc., and returns them. + + Args: + input_file: Path to the input file containing numbers, one per line. + output_file: Optional path to save the calculated statistics in JSON format. + + Returns: + A dictionary containing the command executed, stdout, stderr, a dictionary of the + calculated statistics, and the path to the output file if generated. + """ + # 1. Input validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + output_files = [] + if output_file: + # Ensure parent directory exists for the output file + output_file.parent.mkdir(parents=True, exist_ok=True) + output_files.append(str(output_file)) + + # 2. Create and write the Perl script to a temporary file + script_path = None + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".pl", delete=False) as tmp_script: + script_path = Path(tmp_script.name) + tmp_script.write(_PERL_SCRIPT_TEMPLATE) + + # 3. Construct and execute the command + cmd = [ + "perl", + str(script_path), + str(input_file.resolve()) + ] + command_executed = " ".join(cmd) + + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + # 4. Process the successful result + stdout_str = result.stdout.strip() + statistics_results = json.loads(stdout_str) + + if output_file: + with open(output_file, 'w') as f_out: + json.dump(statistics_results, f_out, indent=4) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "statistics": statistics_results, + "output_files": output_files + } + + except subprocess.CalledProcessError as e: + # Handle errors from the Perl script execution + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl script execution failed with return code {e.returncode}.", + "statistics": {}, + "output_files": [] + } + except json.JSONDecodeError as e: + # Handle errors if the script output is not valid JSON + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "error": f"Failed to parse JSON output from Perl script: {e}", + "statistics": {}, + "output_files": [] + } + finally: + # 5. Clean up the temporary script file + if script_path and script_path.exists(): + script_path.unlink() diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/app/perl-statistics-descriptive_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/app/perl-statistics-descriptive_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f6376f8f157242ab51d94292d7a4ba7479cac6a2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/app/perl-statistics-descriptive_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/app/perl-statistics-descriptive_server.py') +SERVER_NAME = 'biosci_perl_statistics_descriptive' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f42ab55dc6e5c756c28da6bd35f27d02bfb94a9e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-statistics-descriptive: + build: . + image: mcp-perl-statistics-descriptive:latest + container_name: mcp-perl-statistics-descriptive + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-statistics-descriptive + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..48efaf1768b01e4c1731cde6abf47ed6020d1ebf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-statistics-descriptive + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-statistics-descriptive/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..695a5165a5c8ed78f05b7ca09723063d5f6f00ae --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-storable via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-storable -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-storable_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-storable_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-storable_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/app/perl-storable_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/app/perl-storable_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ff6d46e1c3f17088f379da0ac60a1c3265faafb8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/app/perl-storable_server.py @@ -0,0 +1,386 @@ +import subprocess +from pathlib import Path +from typing import Optional, Dict, Any +import os +import base64 + +@mcp.tool() +def storable_store( + perl_expression: str, + file_path: str, + canonical: bool = False, + allow_code: bool = False +) -> Dict[str, Any]: + """ + Store a Perl data structure into a file using Storable::store. + + :param perl_expression: A string containing a Perl data structure (e.g., "{ a => 1, b => [1, 2] }"). + :param file_path: The destination file path. + :param canonical: If True, hashes will be stored with elements sorted by key. + :param allow_code: If True, allows serialization of CODE references (sets $Storable::Deparse). + """ + path = Path(file_path) + # Ensure parent directory exists + path.parent.mkdir(parents=True, exist_ok=True) + + env = os.environ.copy() + env["CANONICAL"] = "1" if canonical else "0" + env["ALLOW_CODE"] = "1" if allow_code else "0" + + perl_cmd = [ + "perl", + "-MStorable", + "-e", + "$Storable::canonical = $ENV{CANONICAL}; $Storable::Deparse = $ENV{ALLOW_CODE}; " + "my $data = eval($ARGV[0]); die \"Eval error: $@\" if $@; " + "Storable::store($data, $ARGV[1]) or die \"Store error: $!\";", + "--", + perl_expression, + str(path) + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True, env=env) + return { + "command_executed": " ".join(perl_cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(path)] + } + except subprocess.CalledProcessError as e: + return { + "error": f"Perl execution failed: {e.stderr}", + "command_executed": " ".join(perl_cmd), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def storable_nstore( + perl_expression: str, + file_path: str, + canonical: bool = False, + allow_code: bool = False +) -> Dict[str, Any]: + """ + Store a Perl data structure into a file in network order using Storable::nstore. + + :param perl_expression: A string containing a Perl data structure. + :param file_path: The destination file path. + :param canonical: If True, hashes will be stored with elements sorted by key. + :param allow_code: If True, allows serialization of CODE references. + """ + path = Path(file_path) + path.parent.mkdir(parents=True, exist_ok=True) + + env = os.environ.copy() + env["CANONICAL"] = "1" if canonical else "0" + env["ALLOW_CODE"] = "1" if allow_code else "0" + + perl_cmd = [ + "perl", + "-MStorable", + "-e", + "$Storable::canonical = $ENV{CANONICAL}; $Storable::Deparse = $ENV{ALLOW_CODE}; " + "my $data = eval($ARGV[0]); die \"Eval error: $@\" if $@; " + "Storable::nstore($data, $ARGV[1]) or die \"Store error: $!\";", + "--", + perl_expression, + str(path) + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True, env=env) + return { + "command_executed": " ".join(perl_cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(path)] + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stderr": e.stderr + } + +@mcp.tool() +def storable_retrieve( + file_path: str, + allow_code: bool = False +) -> Dict[str, Any]: + """ + Retrieve a Perl data structure from a file using Storable::retrieve. + Returns the structure as a string formatted by Data::Dumper. + + :param file_path: The file to retrieve data from. + :param allow_code: If True, allows deserialization of CODE references (sets $Storable::Eval). + """ + path = Path(file_path) + if not path.exists(): + return {"error": f"File not found: {file_path}"} + + env = os.environ.copy() + env["ALLOW_CODE"] = "1" if allow_code else "0" + + perl_cmd = [ + "perl", + "-MStorable", + "-MData::Dumper", + "-e", + "$Storable::Eval = $ENV{ALLOW_CODE}; " + "$Data::Dumper::Terse = 1; $Data::Dumper::Indent = 1; " + "my $data = Storable::retrieve($ARGV[0]) or die \"Retrieve error: $!\"; " + "print Dumper($data);", + "--", + str(path) + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True, env=env) + return { + "command_executed": " ".join(perl_cmd), + "perl_structure": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stderr": e.stderr + } + +@mcp.tool() +def storable_lock_store( + perl_expression: str, + file_path: str, + canonical: bool = False +) -> Dict[str, Any]: + """ + Store a Perl data structure with advisory locking using Storable::lock_store. + """ + path = Path(file_path) + path.parent.mkdir(parents=True, exist_ok=True) + + env = os.environ.copy() + env["CANONICAL"] = "1" if canonical else "0" + + perl_cmd = [ + "perl", + "-MStorable", + "-e", + "$Storable::canonical = $ENV{CANONICAL}; " + "my $data = eval($ARGV[0]); " + "Storable::lock_store($data, $ARGV[1]) or die $!;", + "--", + perl_expression, + str(path) + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True, env=env) + return {"command_executed": " ".join(perl_cmd), "stdout": result.stdout, "output_files": [str(path)]} + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def storable_lock_retrieve( + file_path: str +) -> Dict[str, Any]: + """ + Retrieve a Perl data structure with advisory locking using Storable::lock_retrieve. + """ + path = Path(file_path) + if not path.exists(): + return {"error": f"File not found: {file_path}"} + + perl_cmd = [ + "perl", + "-MStorable", + "-MData::Dumper", + "-e", + "$Data::Dumper::Terse = 1; " + "my $data = Storable::lock_retrieve($ARGV[0]) or die $!; " + "print Dumper($data);", + "--", + str(path) + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return {"command_executed": " ".join(perl_cmd), "perl_structure": result.stdout} + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def storable_freeze( + perl_expression: str, + canonical: bool = False, + allow_code: bool = False +) -> Dict[str, Any]: + """ + Serialize a Perl data structure into a memory string using Storable::freeze. + Returns the binary data as a Base64 encoded string. + """ + env = os.environ.copy() + env["CANONICAL"] = "1" if canonical else "0" + env["ALLOW_CODE"] = "1" if allow_code else "0" + + perl_cmd = [ + "perl", + "-MStorable", + "-M MIME::Base64", + "-e", + "$Storable::canonical = $ENV{CANONICAL}; $Storable::Deparse = $ENV{ALLOW_CODE}; " + "my $data = eval($ARGV[0]); " + "my $frozen = Storable::freeze($data); " + "print encode_base64($frozen);", + "--", + perl_expression + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True, env=env) + return { + "command_executed": " ".join(perl_cmd), + "base64_data": result.stdout.replace("\n", ""), + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def storable_thaw( + base64_data: str, + allow_code: bool = False +) -> Dict[str, Any]: + """ + Recreate a Perl data structure from a frozen string using Storable::thaw. + + :param base64_data: The Base64 encoded binary string produced by freeze. + :param allow_code: If True, allows deserialization of CODE references. + """ + env = os.environ.copy() + env["ALLOW_CODE"] = "1" if allow_code else "0" + + perl_cmd = [ + "perl", + "-MStorable", + "-M MIME::Base64", + "-MData::Dumper", + "-e", + "$Storable::Eval = $ENV{ALLOW_CODE}; " + "$Data::Dumper::Terse = 1; " + "my $frozen = decode_base64($ARGV[0]); " + "my $data = Storable::thaw($frozen); " + "print Dumper($data);", + "--", + base64_data + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True, env=env) + return { + "command_executed": " ".join(perl_cmd), + "perl_structure": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def storable_dclone( + perl_expression: str +) -> Dict[str, Any]: + """ + Perform a deep clone of a Perl data structure using Storable::dclone. + Returns the cloned structure dumped as a string. + """ + perl_cmd = [ + "perl", + "-MStorable", + "-MData::Dumper", + "-e", + "$Data::Dumper::Terse = 1; " + "my $data = eval($ARGV[0]); " + "my $clone = Storable::dclone($data); " + "print Dumper($clone);", + "--", + perl_expression + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(perl_cmd), + "cloned_structure": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def storable_nfreeze( + perl_expression: str, + canonical: bool = False +) -> Dict[str, Any]: + """ + Serialize a Perl data structure into a memory string in network order using Storable::nfreeze. + Returns the binary data as a Base64 encoded string. + """ + env = os.environ.copy() + env["CANONICAL"] = "1" if canonical else "0" + + perl_cmd = [ + "perl", + "-MStorable", + "-M MIME::Base64", + "-e", + "$Storable::canonical = $ENV{CANONICAL}; " + "my $data = eval($ARGV[0]); " + "my $frozen = Storable::nfreeze($data); " + "print encode_base64($frozen);", + "--", + perl_expression + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True, env=env) + return { + "command_executed": " ".join(perl_cmd), + "base64_data": result.stdout.replace("\n", ""), + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def storable_lock_nstore( + perl_expression: str, + file_path: str, + canonical: bool = False +) -> Dict[str, Any]: + """ + Store a Perl data structure in network order with advisory locking using Storable::lock_nstore. + """ + path = Path(file_path) + path.parent.mkdir(parents=True, exist_ok=True) + + env = os.environ.copy() + env["CANONICAL"] = "1" if canonical else "0" + + perl_cmd = [ + "perl", + "-MStorable", + "-e", + "$Storable::canonical = $ENV{CANONICAL}; " + "my $data = eval($ARGV[0]); " + "Storable::lock_nstore($data, $ARGV[1]) or die $!;", + "--", + perl_expression, + str(path) + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True, env=env) + return {"command_executed": " ".join(perl_cmd), "stdout": result.stdout, "output_files": [str(path)]} + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/app/perl-storable_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/app/perl-storable_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..826e6bba7f9fe384aec3a1b2139f5844ccf39863 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/app/perl-storable_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/app/perl-storable_server.py') +SERVER_NAME = 'biosci_perl_storable' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0a30655f22600c25134dc341eab88b28313450e7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-storable: + build: . + image: mcp-perl-storable:latest + container_name: mcp-perl-storable + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-storable + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e0470d3d890c04a621bdef7528bfaa4d66be145f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-storable + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-storable/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fe640356bb92a4a18640f30c3dcf5fb9ca3d9afe --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-sub-exporter-progressive via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-sub-exporter-progressive -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-sub-exporter-progressive_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-sub-exporter-progressive_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-sub-exporter-progressive_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/app/perl-sub-exporter-progressive_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/app/perl-sub-exporter-progressive_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f5314c6c1b04108d8a7ac03a3931cf94e9080ad8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/app/perl-sub-exporter-progressive_server.py @@ -0,0 +1,242 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +@mcp.tool() +def perl_execute_script( + script_path: str, + arguments: List[str] = [], + modules: List[str] = [], + include_dirs: List[str] = [], + warning_level: str = "default", + taint_check: bool = False, + record_separator: Optional[str] = None, +) -> Dict[str, Any]: + """ + Execute a Perl script file using the Perl interpreter. + The environment includes the Sub::Exporter::Progressive module. + + Args: + script_path: Path to the Perl script (.pl) to execute. + arguments: List of command-line arguments to pass to the script. + modules: List of modules to load via -M (e.g., ["Sub::Exporter::Progressive", "JSON"]). + include_dirs: List of directories to add to @INC for module searching (-I). + warning_level: Warning level to use. Options: "default" (-w), "all" (-W), "none" (-X). + taint_check: Enable taint checks (-T). + record_separator: Specify record separator (-0). Use '0' for null, or octal values. + """ + script_file = Path(script_path) + if not script_file.exists(): + return {"error": f"Script file not found: {script_path}"} + + cmd = ["perl"] + + # Warning levels + if warning_level == "all": + cmd.append("-W") + elif warning_level == "none": + cmd.append("-X") + else: + cmd.append("-w") + + if taint_check: + cmd.append("-T") + + if record_separator is not None: + cmd.append(f"-0{record_separator}") + + for inc in include_dirs: + cmd.append(f"-I{inc}") + + for mod in modules: + cmd.append(f"-M{mod}") + + cmd.append(str(script_file)) + cmd.extend(arguments) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "exit_code": e.returncode, + "error": "Script execution failed" + } + +@mcp.tool() +def perl_execute_inline( + code: str, + use_all_features: bool = True, + modules: List[str] = [], + include_dirs: List[str] = [], + autosplit: bool = False, + split_pattern: Optional[str] = None, + loop_mode: str = "none", + inplace_extension: Optional[str] = None, +) -> Dict[str, Any]: + """ + Execute a Perl one-liner command. Useful for quick data processing. + + Args: + code: The Perl code to execute. + use_all_features: If True, uses -E (enables all optional features), otherwise -e. + modules: List of modules to load (e.g., ["Sub::Exporter::Progressive"]). + include_dirs: List of directories to add to @INC (-I). + autosplit: Enable autosplit mode (-a) with -n or -p. + split_pattern: Pattern for autosplit (-F). + loop_mode: Loop behavior. "none", "n" (while(<>)), or "p" (while(<>) { print }). + inplace_extension: Edit files in place with optional backup extension (-i). + """ + cmd = ["perl"] + + if use_all_features: + cmd.extend(["-E", code]) + else: + cmd.extend(["-e", code]) + + if autosplit: + cmd.append("-a") + if split_pattern: + cmd.append(f"-F{split_pattern}") + + if loop_mode == "n": + cmd.append("-n") + elif loop_mode == "p": + cmd.append("-p") + + if inplace_extension is not None: + cmd.append(f"-i{inplace_extension}") + + for inc in include_dirs: + cmd.append(f"-I{inc}") + + for mod in modules: + cmd.append(f"-M{mod}") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "exit_code": e.returncode, + "error": "Inline execution failed" + } + +@mcp.tool() +def perl_check_syntax( + script_path: str, + modules: List[str] = [], + include_dirs: List[str] = [], +) -> Dict[str, Any]: + """ + Check the syntax of a Perl script without executing it (-c). + + Args: + script_path: Path to the Perl script to check. + modules: Modules to load during the check. + include_dirs: Directories to include in @INC. + """ + script_file = Path(script_path) + if not script_file.exists(): + return {"error": f"File not found: {script_path}"} + + cmd = ["perl", "-c"] + + for inc in include_dirs: + cmd.append(f"-I{inc}") + for mod in modules: + cmd.append(f"-M{mod}") + + cmd.append(str(script_file)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "syntax_ok": True + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "syntax_ok": False, + "error": "Syntax check failed" + } + +@mcp.tool() +def perl_get_info( + config_variable: Optional[str] = None, + show_all_config: bool = False, +) -> Dict[str, Any]: + """ + Get Perl version and configuration information. + + Args: + config_variable: Specific configuration variable to query (e.g., 'archname'). + show_all_config: If True, returns the full configuration summary (-V). + """ + if show_all_config: + cmd = ["perl", "-V"] + elif config_variable: + cmd = ["perl", f"-V:{config_variable}"] + else: + cmd = ["perl", "-v"] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e) + } + +@mcp.tool() +def perl_verify_module_installed( + module_name: str = "Sub::Exporter::Progressive" +) -> Dict[str, Any]: + """ + Verify if a specific Perl module is installed and loadable. + Defaults to checking Sub::Exporter::Progressive. + + Args: + module_name: The name of the module to check. + """ + cmd = ["perl", f"-M{module_name}", "-e", "print 'OK'"] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "module": module_name, + "installed": True, + "message": f"Module {module_name} is available." + } + except subprocess.CalledProcessError: + return { + "module": module_name, + "installed": False, + "message": f"Module {module_name} is NOT available." + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/app/perl-sub-exporter-progressive_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/app/perl-sub-exporter-progressive_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ac7aa201a2ce3b7dbefe7f15be5ef57f8d6a4461 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/app/perl-sub-exporter-progressive_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/app/perl-sub-exporter-progressive_server.py') +SERVER_NAME = 'biosci_perl_sub_exporter_progressive' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8c2064e7273a80e0c7d30d3d16a4503d20a8e865 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-sub-exporter-progressive: + build: . + image: mcp-perl-sub-exporter-progressive:latest + container_name: mcp-perl-sub-exporter-progressive + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-sub-exporter-progressive + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..80eaec1c8d3023e23f43d4ff97ae855b9af3d7c1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-sub-exporter-progressive + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter-progressive/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bc003e9a1a13fd6b9afce6b9ad9bcb7cd35696a2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-sub-exporter via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-sub-exporter -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-sub-exporter_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-sub-exporter_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-sub-exporter_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/app/perl-sub-exporter_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/app/perl-sub-exporter_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f86213faee16622a692c140a9f1c08845b6d78e5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/app/perl-sub-exporter_server.py @@ -0,0 +1,272 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +@mcp.tool() +def perl_run_script( + script_path: str, + args: Optional[List[str]] = None, + modules: Optional[List[str]] = None, + modules_no_import: Optional[List[str]] = None, + include_dirs: Optional[List[str]] = None, + warnings: bool = False, + all_warnings: bool = False, + disable_warnings: bool = False, + taint_checks: bool = False, + taint_warnings: bool = False, + loop_n: bool = False, + loop_p: bool = False, + autosplit: bool = False, + split_pattern: Optional[str] = None, + inplace_extension: Optional[str] = None, + record_separator: Optional[str] = None, + line_ending_processing: Optional[str] = None, + unicode_features: Optional[str] = None, + debug_flags: Optional[str] = None, + debugger: Optional[str] = None, + no_site_customize: bool = False, + switch_parsing: bool = False, + search_path: bool = False, + unsafe_operations: bool = False, + extract_directory: Optional[str] = None, +): + """ + Executes a Perl script with the specified switches and arguments. + This environment includes the 'Sub::Exporter' module for sophisticated routine exporting. + """ + script = Path(script_path) + if not script.exists(): + return {"error": f"Script file not found: {script_path}"} + + cmd = ["perl"] + + # Boolean switches + if warnings: cmd.append("-w") + if all_warnings: cmd.append("-W") + if disable_warnings: cmd.append("-X") + if taint_checks: cmd.append("-T") + if taint_warnings: cmd.append("-t") + if loop_n: cmd.append("-n") + if loop_p: cmd.append("-p") + if autosplit: cmd.append("-a") + if no_site_customize: cmd.append("-f") + if switch_parsing: cmd.append("-s") + if search_path: cmd.append("-S") + if unsafe_operations: cmd.append("-U") + + # Parameterized switches + if modules: + for m in modules: + cmd.extend(["-M", m]) + if modules_no_import: + for m in modules_no_import: + cmd.extend(["-m", m]) + if include_dirs: + for d in include_dirs: + cmd.extend(["-I", d]) + if split_pattern: + cmd.append(f"-F{split_pattern}") + if inplace_extension is not None: + cmd.append(f"-i{inplace_extension}") + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + if unicode_features: + cmd.append(f"-C{unicode_features}") + if debug_flags: + cmd.append(f"-D{debug_flags}") + if debugger: + cmd.append(f"-d{debugger}") + if extract_directory: + cmd.append(f"-x{extract_directory}") + + cmd.append(str(script)) + if args: + cmd.extend(args) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": args if inplace_extension is not None else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "exit_code": e.returncode, + "error": "Perl script execution failed" + } + +@mcp.tool() +def perl_run_one_liner( + code: str, + use_extended_features: bool = False, + args: Optional[List[str]] = None, + modules: Optional[List[str]] = None, + modules_no_import: Optional[List[str]] = None, + include_dirs: Optional[List[str]] = None, + warnings: bool = False, + all_warnings: bool = False, + disable_warnings: bool = False, + taint_checks: bool = False, + taint_warnings: bool = False, + loop_n: bool = False, + loop_p: bool = False, + autosplit: bool = False, + split_pattern: Optional[str] = None, + inplace_extension: Optional[str] = None, + record_separator: Optional[str] = None, + line_ending_processing: Optional[str] = None, + unicode_features: Optional[str] = None, + no_site_customize: bool = False, +): + """ + Executes a one-line Perl program using the -e or -E switch. + Useful for quick tasks or testing Sub::Exporter functionality. + """ + cmd = ["perl"] + + # Use -E for extended features, -e for standard + exec_switch = "-E" if use_extended_features else "-e" + + if warnings: cmd.append("-w") + if all_warnings: cmd.append("-W") + if disable_warnings: cmd.append("-X") + if taint_checks: cmd.append("-T") + if taint_warnings: cmd.append("-t") + if loop_n: cmd.append("-n") + if loop_p: cmd.append("-p") + if autosplit: cmd.append("-a") + if no_site_customize: cmd.append("-f") + + if modules: + for m in modules: + cmd.extend(["-M", m]) + if modules_no_import: + for m in modules_no_import: + cmd.extend(["-m", m]) + if include_dirs: + for d in include_dirs: + cmd.extend(["-I", d]) + if split_pattern: + cmd.append(f"-F{split_pattern}") + if inplace_extension is not None: + cmd.append(f"-i{inplace_extension}") + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + if unicode_features: + cmd.append(f"-C{unicode_features}") + + cmd.extend([exec_switch, code]) + if args: + cmd.extend(args) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": args if inplace_extension is not None else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "exit_code": e.returncode, + "error": "Perl one-liner execution failed" + } + +@mcp.tool() +def perl_check_syntax( + script_path: str, + modules: Optional[List[str]] = None, + include_dirs: Optional[List[str]] = None, +): + """ + Checks the syntax of a Perl script without executing it (runs BEGIN and CHECK blocks). + """ + script = Path(script_path) + if not script.exists(): + return {"error": f"Script file not found: {script_path}"} + + cmd = ["perl", "-c"] + + if modules: + for m in modules: + cmd.extend(["-M", m]) + if include_dirs: + for d in include_dirs: + cmd.extend(["-I", d]) + + cmd.append(str(script)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "Syntax OK" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "exit_code": e.returncode, + "status": "Syntax Error" + } + +@mcp.tool() +def perl_get_version(): + """ + Prints the Perl version, patchlevel, and license information. + """ + cmd = ["perl", "-v"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": "Failed to retrieve Perl version" + } + +@mcp.tool() +def perl_get_config( + variable: Optional[str] = None, +): + """ + Prints the Perl configuration summary or a single Config.pm variable. + """ + cmd = ["perl"] + if variable: + cmd.append(f"-V:{variable}") + else: + cmd.append("-V") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": f"Failed to retrieve Perl configuration for {variable if variable else 'all'}" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/app/perl-sub-exporter_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/app/perl-sub-exporter_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..21a1e941664d9cc2e4e617d53d0476b5fd6314e5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/app/perl-sub-exporter_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/app/perl-sub-exporter_server.py') +SERVER_NAME = 'biosci_perl_sub_exporter' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..99c71a73b0bdb593c3e3b0668141f85bf8729b97 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-sub-exporter: + build: . + image: mcp-perl-sub-exporter:latest + container_name: mcp-perl-sub-exporter + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-sub-exporter + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2af72aa92102087096e4c789fe954280e0955855 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-sub-exporter + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-exporter/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..414791a68dd11c4e27cdb3e07e2749e3d57e1340 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-sub-identify via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-sub-identify -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-sub-identify_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-sub-identify_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-sub-identify_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/app/perl-sub-identify_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/app/perl-sub-identify_server.py new file mode 100644 index 0000000000000000000000000000000000000000..520c583f715bc109db8949e36fec9e7587c8006b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/app/perl-sub-identify_server.py @@ -0,0 +1,197 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# In a real MCP environment, the 'mcp' package would be available. +# For local testing, you might need a mock object: +# class Mcp: +# def tool(self, func): +# return func +# mcp = Mcp() + +@mcp.tool +def perl_sub_identify( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + execute_program: Optional[List[str]] = None, + execute_program_extended: Optional[List[str]] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + run_under_debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + in_place_edit: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + use_module: Optional[List[str]] = None, + use_module_no_import: Optional[List[str]] = None, + no_module: Optional[List[str]] = None, + no_module_alt: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + parse_switches: bool = False, + search_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core: bool = False, + allow_unsafe: bool = False, + print_version: bool = False, + print_config: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang: bool = False, + change_dir_for_shebang: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> Dict[str, Any]: + """ + Wraps the Perl interpreter, the execution environment for 'perl-sub-identify'. + + The tool 'perl-sub-identify' refers to a Perl module (`Sub::Identify`) for retrieving names of code references, which does not have its own command-line interface. This function wraps the generic `perl` interpreter, allowing the execution of Perl scripts or one-liners. + + Args: + programfile: Path to the Perl program file to execute. + arguments: List of arguments to pass to the program file. + execute_program: One or more lines of a program to execute directly from the command line. Omit `programfile`. + execute_program_extended: Like `execute_program`, but enables all optional features. Omit `programfile`. + record_separator: Specifies the record separator (e.g., an octal value). Corresponds to the -0 switch. + autosplit: Enables autosplit mode with -n or -p (splits $_ into @F). Corresponds to the -a switch. + unicode_features: Enables the listed Unicode features. Corresponds to the -C switch. + check_syntax_only: Checks syntax only (runs BEGIN and CHECK blocks). Corresponds to the -c switch. + run_under_debugger: Runs the program under the specified debugger. Corresponds to the -d[:debugger] switch. + debugging_flags: Sets debugging flags. Corresponds to the -D switch. + no_sitecustomize: Skips running `$sitelib/sitecustomize.pl` at startup. Corresponds to the -f switch. + split_pattern: Specifies the `split()` pattern for the -a switch. Corresponds to the -F switch. + in_place_edit: Edits files in place. Provide an extension to create backups. Corresponds to the -i[extension] switch. + include_directories: Specifies directories to add to @INC. Corresponds to the -I switch. + line_ending_processing: Enables line ending processing and specifies the terminator. Corresponds to the -l[octal] switch. + use_module: Executes `use module...` before the program. Corresponds to the -Mmodule switch. + use_module_no_import: Executes `use module ()` before the program. Corresponds to the -mmodule switch. + no_module: Executes `no module...` before the program. Corresponds to the -M-module switch. + no_module_alt: Executes `no module...` before the program. Corresponds to the -m-module switch. + loop_around_program: Assumes a `while (<>) { ... }` loop around the program. Corresponds to the -n switch. + loop_and_print: Like -n, but also prints the line. Corresponds to the -p switch. + parse_switches: Enables rudimentary parsing for switches after the program file. Corresponds to the -s switch. + search_path: Looks for the program file using the PATH environment variable. Corresponds to the -S switch. + tainting_warnings: Enables tainting warnings. Corresponds to the -t switch. + tainting_checks: Enables tainting checks. Corresponds to the -T switch. + dump_core: Dumps core after parsing the program. Corresponds to the -u switch. + allow_unsafe: Allows unsafe operations. Corresponds to the -U switch. + print_version: Prints the Perl version, patchlevel, and license. Corresponds to the -v switch. + print_config: Prints configuration summary or a single Config.pm variable. Corresponds to the -V[:variable] switch. + enable_warnings: Enables many useful warnings. Corresponds to the -w switch. + enable_all_warnings: Enables all warnings. Corresponds to the -W switch. + ignore_text_before_shebang: Ignores text before a #!perl line. Corresponds to the -x switch. + change_dir_for_shebang: Changes to this directory before executing a program found with -x. + disable_all_warnings: Disables all warnings. Corresponds to the -X switch. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + program_sources = [programfile, execute_program, execute_program_extended] + if sum(p is not None for p in program_sources) > 1: + raise ValueError("Only one of 'programfile', 'execute_program', or 'execute_program_extended' can be specified.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"Program file not found: {programfile}") + + if include_directories: + for d in include_directories: + if not d.is_dir(): + raise FileNotFoundError(f"Include directory not found: {d}") + + if change_dir_for_shebang and not change_dir_for_shebang.is_dir(): + raise FileNotFoundError(f"Directory for -x switch not found: {change_dir_for_shebang}") + + # --- Command Construction --- + cmd = ["perl"] + + # Flags with optional values + if record_separator is not None: cmd.append(f"-0{record_separator}") + if unicode_features is not None: cmd.append(f"-C{unicode_features}") + if run_under_debugger is not None: cmd.append(f"-d{run_under_debugger}") + if debugging_flags is not None: cmd.append(f"-D{debugging_flags}") + if split_pattern is not None: cmd.append(f"-F{split_pattern}") + if in_place_edit is not None: cmd.append(f"-i{in_place_edit}") + if line_ending_processing is not None: cmd.append(f"-l{line_ending_processing}") + if print_config is not None: cmd.append(f"-V{print_config}") + + # Boolean flags + if autosplit: cmd.append("-a") + if check_syntax_only: cmd.append("-c") + if no_sitecustomize: cmd.append("-f") + if loop_around_program: cmd.append("-n") + if loop_and_print: cmd.append("-p") + if parse_switches: cmd.append("-s") + if search_path: cmd.append("-S") + if tainting_warnings: cmd.append("-t") + if tainting_checks: cmd.append("-T") + if dump_core: cmd.append("-u") + if allow_unsafe: cmd.append("-U") + if print_version: cmd.append("-v") + if enable_warnings: cmd.append("-w") + if enable_all_warnings: cmd.append("-W") + if disable_all_warnings: cmd.append("-X") + + # Special handling for -x + if change_dir_for_shebang: + cmd.append(f"-x{change_dir_for_shebang}") + elif ignore_text_before_shebang: + cmd.append("-x") + + # List-based flags + if include_directories: + for d in include_directories: + cmd.extend(["-I", str(d)]) + if use_module: + for mod in use_module: + cmd.append(f"-M{mod}") + if use_module_no_import: + for mod in use_module_no_import: + cmd.append(f"-m{mod}") + if no_module: + for mod in no_module: + cmd.append(f"-M-{mod}") + if no_module_alt: + for mod in no_module_alt: + cmd.append(f"-m-{mod}") + + # Program source + if execute_program: + for prog_line in execute_program: + cmd.extend(["-e", prog_line]) + if execute_program_extended: + for prog_line in execute_program_extended: + cmd.extend(["-E", prog_line]) + + if programfile: + cmd.append(str(programfile)) + + if arguments: + cmd.extend(arguments) + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] # Perl script output files are not predictable + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed with return code {e.returncode}", + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/app/perl-sub-identify_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/app/perl-sub-identify_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cbcf82d90de7d049a5935d97d2c8d902db6a9d78 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/app/perl-sub-identify_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/app/perl-sub-identify_server.py') +SERVER_NAME = 'biosci_perl_sub_identify' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..eb0a0fc4eddb0e6e56a8d4e5bf363a272a1d0c68 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-sub-identify: + build: . + image: mcp-perl-sub-identify:latest + container_name: mcp-perl-sub-identify + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-sub-identify + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3249b8323d40b6253019438063782b7109e84e2e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-sub-identify + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-identify/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b000ea84671cd9bd02f15e5b9b9f188fba657302 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-sub-install via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-sub-install -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-sub-install_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-sub-install_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-sub-install_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/app/perl-sub-install_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/app/perl-sub-install_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cdc701568828a4bf82fd28c23a43f33120cfc64e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/app/perl-sub-install_server.py @@ -0,0 +1,216 @@ +from typing import Optional, List +import subprocess +from pathlib import Path + +@mcp.tool() +def perl_sub_install_run( + one_liner: Optional[str] = None, + program_file: Optional[str] = None, + use_all_features: bool = False, + autosplit: bool = False, + split_pattern: Optional[str] = None, + inplace_extension: Optional[str] = None, + include_dirs: Optional[List[str]] = None, + modules: Optional[List[str]] = None, + warnings_mode: str = "none", + script_args: Optional[List[str]] = None, +): + """ + Execute Perl code or a script using the perl interpreter. + This environment includes the perl-sub-install (Sub::Install) module. + + Args: + one_liner: One line of program (equivalent to -e). + program_file: Path to a Perl script file to execute. + use_all_features: If True, enables all optional features (equivalent to -E). + autosplit: Enable autosplit mode with -n or -p (equivalent to -a). + split_pattern: split() pattern for -a switch (equivalent to -F). + inplace_extension: Edit files in place, making backup if extension supplied (equivalent to -i). + include_dirs: List of directories to add to @INC (equivalent to -I). + modules: List of modules to execute "use module..." before the program (equivalent to -M). + warnings_mode: Warning level: 'none', 'useful' (-w), 'all' (-W), or 'disable' (-X). + script_args: Arguments to pass to the Perl program. + """ + cmd = ["perl"] + + # Handle warnings + if warnings_mode == "useful": + cmd.append("-w") + elif warnings_mode == "all": + cmd.append("-W") + elif warnings_mode == "disable": + cmd.append("-X") + + # Handle modules + if modules: + for module in modules: + cmd.append(f"-M{module}") + + # Handle include directories + if include_dirs: + for directory in include_dirs: + cmd.append(f"-I{directory}") + + # Handle autosplit + if autosplit: + cmd.append("-a") + if split_pattern: + cmd.append(f"-F{split_pattern}") + + # Handle inplace editing + if inplace_extension is not None: + cmd.append(f"-i{inplace_extension}") + + # Handle execution mode (one-liner vs file) + if one_liner: + flag = "-E" if use_all_features else "-e" + cmd.extend([flag, one_liner]) + elif program_file: + prog_path = Path(program_file) + if not prog_path.exists(): + return {"error": f"Program file not found: {program_file}"} + cmd.append(str(prog_path)) + else: + return {"error": "Either 'one_liner' or 'program_file' must be provided."} + + # Append script arguments + if script_args: + cmd.extend(script_args) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "failed" + } + +@mcp.tool() +def perl_sub_install_check_syntax( + program_file: str, + modules: Optional[List[str]] = None, + include_dirs: Optional[List[str]] = None, +): + """ + Check the syntax of a Perl script without executing it (equivalent to perl -c). + + Args: + program_file: Path to the Perl script to check. + modules: List of modules to load before checking. + include_dirs: List of directories to add to @INC. + """ + prog_path = Path(program_file) + if not prog_path.exists(): + return {"error": f"File not found: {program_file}"} + + cmd = ["perl", "-c"] + + if modules: + for module in modules: + cmd.append(f"-M{module}") + + if include_dirs: + for directory in include_dirs: + cmd.append(f"-I{directory}") + + cmd.append(str(prog_path)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "syntax_ok" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Syntax check failed", + "status": "failed" + } + +@mcp.tool() +def perl_sub_install_version(): + """ + Print the version and patchlevel of the Perl interpreter. + """ + cmd = ["perl", "-v"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e) + } + +@mcp.tool() +def perl_sub_install_config( + variable: Optional[str] = None +): + """ + Print a summary of Perl configuration or the value of a specific configuration variable. + + Args: + variable: Specific Config.pm variable to print (equivalent to -V:variable). + """ + arg = "-V" + if variable: + arg = f"-V:{variable}" + + cmd = ["perl", arg] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e) + } + +@mcp.tool() +def perl_sub_install_test_module(): + """ + Verify that the Sub::Install module is correctly installed and available in the environment. + """ + # Sub::Install is the module provided by the perl-sub-install package. + # We test it by attempting to load it and calling a simple version check or just '1'. + one_liner = "use Sub::Install; print 'Sub::Install is available.';" + cmd = ["perl", "-e", one_liner] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "available" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Sub::Install module not found or failed to load.", + "status": "unavailable" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/app/perl-sub-install_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/app/perl-sub-install_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1d6851497e98abe073d07c70db17c74a12580b05 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/app/perl-sub-install_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/app/perl-sub-install_server.py') +SERVER_NAME = 'biosci_perl_sub_install' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7608e6d638d3f44c7280aabb802e6b45cc7eba7a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-sub-install: + build: . + image: mcp-perl-sub-install:latest + container_name: mcp-perl-sub-install + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-sub-install + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..158b507ae3c238de583956d0b6b3b630620f9564 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-sub-install + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-install/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2ea019a50318d1e76a20b8e5226133f7e774dd17 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-sub-name via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-sub-name -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-sub-name_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-sub-name_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-sub-name_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/app/perl-sub-name_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/app/perl-sub-name_server.py new file mode 100644 index 0000000000000000000000000000000000000000..219e29bc1a5290524152d6ba9603a982defdd824 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/app/perl-sub-name_server.py @@ -0,0 +1,33 @@ +import subprocess +from typing import Dict + +# This is a placeholder. mcp is not a real library. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +@mcp.tool() +def sub_name() -> Dict[str, str]: + """ + Note: `perl-sub-name` is a Perl library (`Sub::Name`) for assigning names to subroutines at runtime. + It does not provide a command-line executable. This MCP tool is a placeholder and does not + execute any command, as there is no underlying tool to run. + """ + # Since this is a library and not a CLI tool, we cannot execute it. + # The return value indicates that no command was run and provides an + # informative message in stderr. + + error_message = ( + "Error: perl-sub-name is a Perl library, not a command-line tool. " + "It cannot be executed directly." + ) + + return { + "command_executed": "", + "stdout": "", + "stderr": error_message, + "output_files": [] + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/app/perl-sub-name_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/app/perl-sub-name_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3b2ac125021b540a6d06a5e7f462055dc0bf494c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/app/perl-sub-name_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/app/perl-sub-name_server.py') +SERVER_NAME = 'biosci_perl_sub_name' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7e6217daeff1812d7e154ae7728b9c47cc780b56 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-sub-name: + build: . + image: mcp-perl-sub-name:latest + container_name: mcp-perl-sub-name + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-sub-name + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..437d4688d41f800d48d6dbd9361b176b0b6fc4ad --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-sub-name + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-name/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cf608643b099e58e296f1d0dfce91733dd09b5b6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-sub-quote via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-sub-quote -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-sub-quote_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-sub-quote_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-sub-quote_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/app/perl-sub-quote_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/app/perl-sub-quote_server.py new file mode 100644 index 0000000000000000000000000000000000000000..866d71c084fcbaa58c21561852e9aabf25cadfad --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/app/perl-sub-quote_server.py @@ -0,0 +1,282 @@ +import subprocess +import json +import base64 +from typing import Optional, Dict, Any, List, Union +from pathlib import Path + +def _run_perl_command(script: str, debug: bool = False) -> dict: + """ + Internal helper to execute Perl scripts with Sub::Quote. + """ + env = {} + if debug: + env["SUB_QUOTE_DEBUG"] = "1" + + try: + # Use base64 to pass the script to avoid shell escaping issues + encoded_script = base64.b64encode(script.encode('utf-8')).decode('utf-8') + full_command = [ + "perl", + "-MSub::Quote", + "-MJSON", + "-MB::Deparse", + "-MMIME::Base64", + "-e", + f"eval decode_base64('{encoded_script}'); die $@ if $@;" + ] + + result = subprocess.run( + full_command, + capture_output=True, + text=True, + check=True, + env=env + ) + return { + "command_executed": " ".join(full_command), + "stdout": result.stdout, + "stderr": result.stderr, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def quote_sub( + code: str, + name: Optional[str] = None, + captures: Optional[Dict[str, Any]] = None, + no_install: bool = False, + no_defer: bool = False, + package: Optional[str] = None, + hints: Optional[int] = None, + warning_bits: Optional[str] = None, + hintshash: Optional[Dict[str, Any]] = None, + attributes: Optional[List[str]] = None, + file: Optional[str] = None, + line: Optional[int] = None, + debug: bool = False +): + """ + Efficiently generates a subroutine from a string using Sub::Quote. + + Args: + code: The Perl code string to be turned into a subroutine. + name: Optional subroutine name where the coderef will be installed. + captures: Hashref of variables to be made available to the code (keys include sigils). + no_install: If True, do not install the generated coderef into the passed name. + no_defer: If True, prevents a Sub::Defer wrapper from being generated. + package: The package the quoted sub will be evaluated in. + hints: The value of $^H to use (captures strict pragma). + warning_bits: The value of ${^WARNING_BITS} to use. + hintshash: The value of %^H to use (captures additional pragmas). + attributes: Subroutine attributes to apply (as a list). + file: Apparent filename for the code. + line: Apparent line number for the code. + debug: Enable SUB_QUOTE_DEBUG environment variable. + """ + + # Prepare options hashref + opts = { + "no_install": no_install, + "no_defer": no_defer, + } + if package: opts["package"] = package + if hints is not None: opts["hints"] = hints + if warning_bits: opts["warning_bits"] = warning_bits + if hintshash: opts["hintshash"] = hintshash + if attributes: opts["attributes"] = attributes + if file: opts["file"] = file + if line is not None: opts["line"] = line + + perl_script = f""" +my $code = q{{{code}}}; +my $name = {f"'{name}'" if name else "undef"}; +my $captures_raw = decode_json('{json.dumps(captures or {})}'); +my $options = decode_json('{json.dumps(opts)}'); + +my %captures; +foreach my $key (keys %$captures_raw) {{ + $captures{{$key}} = \\($captures_raw->{{$key}}); +}} + +my $sub = quote_sub($name, $code, \\%captures, $options); +print B::Deparse->new->coderef2text($sub); +""" + return _run_perl_command(perl_script, debug) + +@mcp.tool() +def unquote_sub( + code: str, + captures: Optional[Dict[str, Any]] = None, + debug: bool = False +): + """ + Forcibly replaces a quoted subroutine with actual code and returns the deparsed result. + + Args: + code: The Perl code string of the sub. + captures: Hashref of variables to be made available to the code. + debug: Enable SUB_QUOTE_DEBUG environment variable. + """ + perl_script = f""" +use Sub::Quote qw(quote_sub unquote_sub); +my $code = q{{{code}}}; +my $captures_raw = decode_json('{json.dumps(captures or {})}'); +my %captures = map {{ $_ => \\($captures_raw->{{$_}}) }} keys %$captures_raw; + +my $sub = quote_sub($code, \\%captures); +unquote_sub($sub); +print B::Deparse->new->coderef2text($sub); +""" + return _run_perl_command(perl_script, debug) + +@mcp.tool() +def quoted_from_sub( + code: str, + captures: Optional[Dict[str, Any]] = None, + debug: bool = False +): + """ + Returns original arguments to quote_sub for a given subroutine. + + Args: + code: The Perl code string of the sub. + captures: Hashref of variables to be made available to the code. + debug: Enable SUB_QUOTE_DEBUG environment variable. + """ + perl_script = f""" +use Sub::Quote qw(quote_sub quoted_from_sub); +my $code = q{{{code}}}; +my $captures_raw = decode_json('{json.dumps(captures or {})}'); +my %captures = map {{ $_ => \\($captures_raw->{{$_}}) }} keys %$captures_raw; + +my $sub = quote_sub($code, \\%captures); +my $data = quoted_from_sub($sub); +# $data is [$name, $code, $captures, $compiled_sub] +if ($data->[3]) {{ + $data->[3] = B::Deparse->new->coderef2text($data->[3]); +}} +print encode_json($data); +""" + return _run_perl_command(perl_script, debug) + +@mcp.tool() +def inlinify( + code: str, + args: str, + prelude: str = "", + localize: bool = False, + debug: bool = False +): + """ + Takes a string of code, arguments, and a prelude to generate inlined Perl code. + + Args: + code: The Perl code string to inline. + args: String of arguments (e.g., '$x, $y'). + prelude: Code snippet to act as a prelude (e.g., from capture_unroll). + localize: Whether or not to localize the arguments. + debug: Enable SUB_QUOTE_DEBUG environment variable. + """ + perl_script = f""" +use Sub::Quote qw(inlinify); +my $code = q{{{code}}}; +my $args = q{{{args}}}; +my $prelude = q{{{prelude}}}; +my $localize = {1 if localize else 0}; +print inlinify($code, $args, $prelude, $localize); +""" + return _run_perl_command(perl_script, debug) + +@mcp.tool() +def quotify( + value: Union[str, int, float], + debug: bool = False +): + """ + Quotes a single scalar value for use in a Perl code string. + + Args: + value: The value to quote (string, integer, or float). + debug: Enable SUB_QUOTE_DEBUG environment variable. + """ + # We pass the value as a string and let Perl handle the type detection + perl_script = f""" +use Sub::Quote qw(quotify); +my $val = '{value}'; +# If it looks like a number, treat it as one for quotify +if ($val =~ /^-?\\d+(\\.\\d+)?$/) {{ + $val = $val + 0; +}} +print quotify($val); +""" + return _run_perl_command(perl_script, debug) + +@mcp.tool() +def capture_unroll( + from_var: str, + captures: Dict[str, Any], + indent: int = 0, + debug: bool = False +): + """ + Generates a snippet of code suitable for use as a prelude for inlinify. + + Args: + from_var: String used as a hashref in the resulting code (e.g., '$captures'). + captures: Hashref where keys are variable names. + indent: Number of spaces to indent the result. + debug: Enable SUB_QUOTE_DEBUG environment variable. + """ + perl_script = f""" +use Sub::Quote qw(capture_unroll); +my $from = q{{{from_var}}}; +my $captures = decode_json('{json.dumps(captures)}'); +my $indent = {indent}; +print capture_unroll($from, $captures, $indent); +""" + return _run_perl_command(perl_script, debug) + +@mcp.tool() +def qsub( + code: str, + debug: bool = False +): + """ + Works like quote_sub but includes a prototype to only accept a single parameter. + + Args: + code: The Perl code string. + debug: Enable SUB_QUOTE_DEBUG environment variable. + """ + perl_script = f""" +use Sub::Quote qw(qsub); +my $code = q{{{code}}}; +my $sub = qsub($code); +print B::Deparse->new->coderef2text($sub); +""" + return _run_perl_command(perl_script, debug) + +@mcp.tool() +def sanitize_identifier( + identifier: str, + debug: bool = False +): + """ + Sanitizes a value so that it can be used in a Perl identifier. + + Args: + identifier: The string to sanitize. + debug: Enable SUB_QUOTE_DEBUG environment variable. + """ + perl_script = f""" +use Sub::Quote qw(sanitize_identifier); +my $id = q{{{identifier}}}; +print sanitize_identifier($id); +""" + return _run_perl_command(perl_script, debug) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/app/perl-sub-quote_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/app/perl-sub-quote_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5dcd6db242b719027c4fa9c275ca3929a1642de9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/app/perl-sub-quote_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/app/perl-sub-quote_server.py') +SERVER_NAME = 'biosci_perl_sub_quote' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..385b53211201f072ac8c7784fcba61f5e3eb7941 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-sub-quote: + build: . + image: mcp-perl-sub-quote:latest + container_name: mcp-perl-sub-quote + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-sub-quote + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..92cfb2c600dcfca8cac558c2d683707fe5d15d72 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-sub-quote + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-quote/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6bfc3e627d159d944a5754a34e441b4c83e0dd91 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-sub-uplevel via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-sub-uplevel -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-sub-uplevel_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-sub-uplevel_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-sub-uplevel_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/app/perl-sub-uplevel_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/app/perl-sub-uplevel_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7942fe2a02eb5b40fdaec4c19bf2db617edd72bf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/app/perl-sub-uplevel_server.py @@ -0,0 +1,226 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be imported. +def tool(func): + """A dummy decorator to allow the code to be syntactically valid.""" + return func + +mcp = type("mcp", (), {"tool": tool}) + +@mcp.tool +def run_perl( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + e_program: Optional[List[str]] = None, + E_program: Optional[List[str]] = None, + include_dirs: Optional[List[Path]] = None, + module: Optional[List[str]] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + enable_tainting_checks: bool = False, + enable_tainting_warnings: bool = False, + loop_around_program: bool = False, + loop_and_print: bool = False, + autosplit: bool = False, + line_ending: Optional[str] = None, + split_pattern: Optional[str] = None, + inplace_edit_extension: Optional[str] = None, + parse_switches: bool = False, + search_path: bool = False, + print_version: bool = False, + print_config: Optional[str] = None, + unicode_features: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + dump_core: bool = False, + allow_unsafe: bool = False, + extract_from_text_dir: Optional[Path] = None, + disable_all_warnings: bool = False, + record_separator: Optional[str] = None, +) -> Dict[str, Any]: + """ + Executes a Perl script or command using the Perl interpreter. + + This tool is a wrapper for the `perl` command-line interpreter. The `perl-sub-uplevel` + package is a Perl module and does not have its own executable. + + Args: + programfile: Path to the Perl program file to execute. + arguments: A list of arguments to pass to the program file. + e_program: A list of strings, each being a line of a program. + E_program: Like -e, but enables all optional features. + include_dirs: A list of directories to add to @INC. Corresponds to the -I flag. + module: A list of modules to use/no before executing the program. Corresponds to the -M/-m flag. + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). Corresponds to the -c flag. + debugger: Run the program under the specified debugger. Corresponds to the -d[:debugger] flag. + enable_warnings: Enable many useful warnings. Corresponds to the -w flag. + enable_all_warnings: Enable all warnings. Corresponds to the -W flag. + enable_tainting_checks: Enable tainting checks. Corresponds to the -T flag. + enable_tainting_warnings: Enable tainting warnings. Corresponds to the -t flag. + loop_around_program: Assume "while (<>) { ... }" loop around the program. Corresponds to the -n flag. + loop_and_print: Assume loop like -n but also print the line. Corresponds to the -p flag. + autosplit: Autosplit mode with -n or -p (splits $_ into @F). Corresponds to the -a flag. + line_ending: Enable line ending processing, specifies line terminator. Corresponds to the -l[octal] flag. + split_pattern: split() pattern for the -a switch. Corresponds to the -F/pattern/ flag. + inplace_edit_extension: Edit <> files in place, making a backup if an extension is supplied. Corresponds to the -i[extension] flag. + parse_switches: Enable rudimentary parsing for switches after the program file. Corresponds to the -s flag. + search_path: Look for the program file using the PATH environment variable. Corresponds to the -S flag. + print_version: Print version, patchlevel, and license. Corresponds to the -v flag. + print_config: Print configuration summary or a single Config.pm variable. Corresponds to the -V[:variable] flag. + unicode_features: Enables the listed Unicode features. Corresponds to the -C[number/list] flag. + debugging_flags: Set debugging flags. Corresponds to the -D[number/list] flag. + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. Corresponds to the -f flag. + dump_core: Dump core after parsing the program. Corresponds to the -u flag. + allow_unsafe: Allow unsafe operations. Corresponds to the -U flag. + extract_from_text_dir: Ignore text before #!perl line, optionally cd to the directory. Corresponds to the -x[directory] flag. + disable_all_warnings: Disable all warnings. Corresponds to the -X flag. + record_separator: Specify the record separator. Corresponds to the -0[octal] flag. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not any([programfile, e_program, E_program, print_version, print_config is not None]): + raise ValueError("Either a program file, an inline program (-e or -E), or an info flag (-v or -V) must be provided.") + + if programfile and (e_program or E_program): + raise ValueError("`programfile` cannot be used at the same time as `e_program` or `E_program`.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"The specified program file does not exist: {programfile}") + + if include_dirs: + for directory in include_dirs: + if not directory.is_dir(): + raise NotADirectoryError(f"The include directory does not exist: {directory}") + + if extract_from_text_dir and not extract_from_text_dir.is_dir(): + raise NotADirectoryError(f"The directory for -x does not exist: {extract_from_text_dir}") + + # --- Command Construction --- + cmd = ["perl"] + + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if debugger is not None: + cmd.append(f"-d:{debugger}" if debugger else "-d") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if inplace_edit_extension is not None: + cmd.append(f"-i{inplace_edit_extension}") + if line_ending is not None: + cmd.append(f"-l{line_ending}") + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if parse_switches: + cmd.append("-s") + if search_path: + cmd.append("-S") + if enable_tainting_warnings: + cmd.append("-t") + if enable_tainting_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if allow_unsafe: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config is not None: + cmd.append(f"-V:{print_config}" if print_config else "-V") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if extract_from_text_dir is not None: + cmd.extend(["-x", str(extract_from_text_dir)]) + elif extract_from_text_dir is not None: # -x without directory + cmd.append("-x") + if disable_all_warnings: + cmd.append("-X") + + if include_dirs: + for directory in include_dirs: + cmd.extend(["-I", str(directory)]) + + if module: + for mod in module: + if mod.startswith('-'): # for 'no module' + cmd.extend(["-m", mod]) + else: + cmd.extend(["-M", mod]) + + if e_program: + for prog_line in e_program: + cmd.extend(["-e", prog_line]) + + if E_program: + for prog_line in E_program: + cmd.extend(["-E", prog_line]) + + if programfile: + cmd.append(str(programfile)) + + if arguments: + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # --- Structured Result Return --- + output_files = [] + # The -i flag modifies files in place. If used with a programfile and arguments, + # those arguments might be files that get modified. + if inplace_edit_extension is not None and arguments: + for arg in arguments: + p = Path(arg) + if p.is_file(): + output_files.append(str(p)) + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/app/perl-sub-uplevel_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/app/perl-sub-uplevel_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9a357909be2ee06a763151488bf8bf1bbd2e8e33 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/app/perl-sub-uplevel_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/app/perl-sub-uplevel_server.py') +SERVER_NAME = 'biosci_perl_sub_uplevel' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c830f8cbcf572935fb9d12691e9e1fe9f53929d0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-sub-uplevel: + build: . + image: mcp-perl-sub-uplevel:latest + container_name: mcp-perl-sub-uplevel + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-sub-uplevel + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fcd9a0f226b068f02f26750f04dbbf1c47a60995 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-sub-uplevel + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..50e08d6ce5355538398752c7b3555452b9c3da38 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-svg-graph via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-svg-graph -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-svg-graph_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-svg-graph_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-svg-graph_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/app/perl-svg-graph_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/app/perl-svg-graph_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4fb45b9619d619c7ff907bf3c2141b6c1c7ac9c2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/app/perl-svg-graph_server.py @@ -0,0 +1,191 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, Any, List + +# MCP decorator stub. In a real environment, this would be: +# from mcp import mcp +class mcp: + def tool(func): + return func + +@mcp.tool +def create_svg_graph( + input_file: Path, + output_file: Path, + graph_type: str = "Line", + width: int = 600, + height: int = 400, + title: str = "SVG Graph", + x_label: str = "X-axis", + y_label: str = "Y-axis", + show_key: bool = False, +) -> Dict[str, Any]: + """ + Generates an SVG graph from a data file using the perl-svg-graph library. + + This tool acts as a command-line wrapper for the SVG::Graph Perl module, + which does not have its own executable. It generates a Perl script on-the-fly + to create various types of graphs from a simple tab-separated data file. + The input file should contain two columns: x-value and y-value (or label and value for Pie charts). + + Args: + input_file: Path to the input data file (tab-separated values). + output_file: Path to save the output SVG file. + graph_type: The type of graph to generate. Supported types: "Line", "Bar", "Pie", "BarLine". + width: Width of the SVG image in pixels. + height: Height of the SVG image in pixels. + title: The title of the graph. + x_label: The label for the X-axis. + y_label: The label for the Y-axis. + show_key: If True, display the graph's key/legend. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + allowed_graph_types = ["Line", "Bar", "Pie", "BarLine"] + if graph_type not in allowed_graph_types: + raise ValueError(f"Invalid graph_type '{graph_type}'. Must be one of {allowed_graph_types}") + + if width <= 0: + raise ValueError("Width must be a positive integer.") + if height <= 0: + raise ValueError("Height must be a positive integer.") + + # --- Perl Script Generation --- + # This script acts as the command-line interface for the SVG::Graph library. + perl_script_content = """ +#!/usr/bin/env perl + +use strict; +use warnings; +use Getopt::Long; +use SVG::Graph::Data; +use SVG::Graph::Data::Datum; + +# Default options +my $input_file = ''; +my $output_file = ''; +my $graph_type = 'Line'; +my $width = 600; +my $height = 400; +my $title = 'SVG Graph'; +my $x_label = 'X-axis'; +my $y_label = 'Y-axis'; +my $show_key = 0; + +GetOptions( + 'input=s' => \\$input_file, + 'output=s' => \\$output_file, + 'type=s' => \\$graph_type, + 'width=i' => \\$width, + 'height=i' => \\$height, + 'title=s' => \\$title, + 'xlabel=s' => \\$x_label, + 'ylabel=s' => \\$y_label, + 'key' => \\$show_key, +) or die "Error in command line arguments\\n"; + +die "Input and Output file are required." unless ($input_file && $output_file); + +# Dynamically determine the graph class and load it +my $graph_class = "SVG::Graph::${graph_type}"; +eval "use $graph_class;"; +if ($@) { + die "Invalid graph type '$graph_type'. Could not load module $graph_class: $@"; +} + +# Read data from the input file (TSV: x\\ty or label\\tvalue for Pie) +my @data_points; +open(my $fh, '<', $input_file) or die "Could not open file '$input_file' $!"; +while (my $row = <$fh>) { + chomp $row; + next if $row =~ /^\\s*$/; # skip empty lines + my ($x, $y) = split(/\\t/, $row, 2); + die "Invalid data row, expected 2 tab-separated columns: $row" unless defined $y; + + if ($graph_type eq 'Pie') { + push @data_points, SVG::Graph::Data::Datum->new('name' => $x, 'value' => $y); + } else { + push @data_points, SVG::Graph::Data::Datum->new('x' => $x, 'y' => $y); + } +} +close $fh; + +my $data = SVG::Graph::Data->new('data' => \\@data_points); + +# Create graph object +my $graph = $graph_class->new( + 'width' => $width, + 'height' => $height, + 'key' => $show_key, + 'title' => $title, + 'x_label' => $x_label, + 'y_label' => $y_label, +); + +$graph->add_data($data); + +# Write SVG to output file +open(my $out_fh, '>', $output_file) or die "Could not open file '$output_file' for writing $!"; +print $out_fh $graph->draw; +close $out_fh; + +print "SVG graph successfully written to $output_file\\n"; +""" + + script_path = "" + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".pl", encoding='utf-8') as temp_script: + script_path_obj = Path(temp_script.name) + temp_script.write(perl_script_content) + script_path = temp_script.name + + # --- Command Construction --- + cmd = [ + "perl", + script_path, + "--input", str(input_file), + "--output", str(output_file), + "--type", graph_type, + "--width", str(width), + "--height", str(height), + "--title", title, + "--xlabel", x_label, + "--ylabel", y_label, + ] + if show_key: + cmd.append("--key") + + # --- Subprocess Execution --- + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + output_files = [str(output_file)] if output_file.exists() else [] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + # Re-raise with structured error information + raise RuntimeError( + f"Perl script execution failed with exit code {e.returncode}.\n" + f"Command: {' '.join(e.cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + finally: + # --- Cleanup --- + if script_path and Path(script_path).exists(): + Path(script_path).unlink() diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/app/perl-svg-graph_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/app/perl-svg-graph_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a71033269202b9310ffeafec7ed7770a3056b279 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/app/perl-svg-graph_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/app/perl-svg-graph_server.py') +SERVER_NAME = 'biosci_perl_svg_graph' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d6a8bdbafcf13e63694cc2b4c072343992482869 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-svg-graph: + build: . + image: mcp-perl-svg-graph:latest + container_name: mcp-perl-svg-graph + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-svg-graph + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cd9a0838fd5d4404559292ea6fd3adcb1ba1a2ec --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-svg-graph + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg-graph/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-svg/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c3fe1ee968a78a8d0a6eb8988c8e80657283dbfc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-task-weaken via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-task-weaken -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-task-weaken_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-task-weaken_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-task-weaken_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/app/perl-task-weaken_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/app/perl-task-weaken_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f9bbdea11216ad5046385a03449ad7db6eba9fc5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/app/perl-task-weaken_server.py @@ -0,0 +1,236 @@ +from typing import Optional, List +import subprocess +from pathlib import Path + +@mcp.tool() +def perl_execute( + program_file: Optional[str] = None, + one_liner: Optional[str] = None, + one_liner_extended: Optional[str] = None, + modules: Optional[List[str]] = None, + include_dirs: Optional[List[str]] = None, + warnings: bool = False, + all_warnings: bool = False, + disable_warnings: bool = False, + taint_checks: bool = False, + taint_warnings: bool = False, + autosplit: bool = False, + split_pattern: Optional[str] = None, + loop_n: bool = False, + loop_p: bool = False, + inplace_extension: Optional[str] = None, + record_separator: Optional[str] = None, + line_ending: bool = False, + line_ending_octal: Optional[str] = None, + unicode_features: Optional[str] = None, + debug_flags: Optional[str] = None, + debugger: Optional[str] = None, + no_site_customize: bool = False, + path_search: bool = False, + unsafe_operations: bool = False, + strip_text: bool = False, + strip_text_dir: Optional[str] = None, + arguments: Optional[List[str]] = None, +): + """ + Execute a Perl script or command with various switches. + This tool provides access to the Perl interpreter, which is the primary execution environment for Task::Weaken. + """ + cmd = ["perl"] + + # Handle switches + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features: + cmd.append(f"-C{unicode_features}") + if debugger: + cmd.append(f"-d:{debugger}") + elif debugger == "": # Handle -d without argument + cmd.append("-d") + if debug_flags: + cmd.append(f"-D{debug_flags}") + if one_liner: + cmd.append("-e") + cmd.append(one_liner) + if one_liner_extended: + cmd.append("-E") + cmd.append(one_liner_extended) + if no_site_customize: + cmd.append("-f") + if split_pattern: + cmd.append(f"-F{split_pattern}") + if inplace_extension is not None: + cmd.append(f"-i{inplace_extension}") + if include_dirs: + for d in include_dirs: + cmd.append(f"-I{d}") + if line_ending: + if line_ending_octal: + cmd.append(f"-l{line_ending_octal}") + else: + cmd.append("-l") + if modules: + for m in modules: + cmd.append(f"-M{m}") + if loop_n: + cmd.append("-n") + if loop_p: + cmd.append("-p") + if path_search: + cmd.append("-S") + if taint_warnings: + cmd.append("-t") + if taint_checks: + cmd.append("-T") + if unsafe_operations: + cmd.append("-U") + if warnings: + cmd.append("-w") + if all_warnings: + cmd.append("-W") + if disable_warnings: + cmd.append("-X") + if strip_text: + if strip_text_dir: + cmd.append(f"-x{strip_text_dir}") + else: + cmd.append("-x") + + # Program file and arguments + if program_file: + prog_path = Path(program_file) + if not prog_path.exists(): + return {"error": f"Program file not found: {program_file}"} + cmd.append(program_file) + + if arguments: + cmd.extend(arguments) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "return_code": result.returncode + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "error": str(e) + } + +@mcp.tool() +def perl_check_syntax(program_file: str): + """Check the syntax of a Perl script without executing it (-c).""" + prog_path = Path(program_file) + if not prog_path.exists(): + return {"error": f"File not found: {program_file}"} + + cmd = ["perl", "-c", program_file] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "Syntax OK" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Syntax check failed" + } + +@mcp.tool() +def perl_get_version(): + """Print the Perl version, patchlevel, and license information (-v).""" + cmd = ["perl", "-v"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def perl_get_config(variable: Optional[str] = None): + """Print Perl configuration summary or a single Config.pm variable (-V).""" + cmd = ["perl", "-V"] + if variable: + cmd.append(f":{variable}") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def perl_task_weaken_verify(): + """ + Verify if Task::Weaken is installed and functional in the current environment. + This ensures the platform has support for weak references (Scalar::Util::weaken). + """ + # Task::Weaken is a module that ensures weaken support is present. + # We check it by attempting to load it and verifying Scalar::Util::weaken exists. + perl_code = "use Task::Weaken; use Scalar::Util 'weaken'; print 'Task::Weaken verified: Scalar::Util::weaken is available.';" + cmd = ["perl", "-e", perl_code] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "Success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Task::Weaken verification failed. Weak reference support may be missing or the module is not installed.", + "status": "Failed" + } + +@mcp.tool() +def perl_run_one_liner(code: str, use_extended_features: bool = False): + """ + Run a simple Perl one-liner command (-e or -E). + + Args: + code: The Perl code to execute. + use_extended_features: If True, uses -E to enable all optional features. + """ + flag = "-E" if use_extended_features else "-e" + cmd = ["perl", flag, code] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/app/perl-task-weaken_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/app/perl-task-weaken_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..10547b71ebee69ebcc5039366918ee196e402b3e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/app/perl-task-weaken_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/app/perl-task-weaken_server.py') +SERVER_NAME = 'biosci_perl_task_weaken' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e0b3967b39f1efca6c3e4c15032de95ff4f656cb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-task-weaken: + build: . + image: mcp-perl-task-weaken:latest + container_name: mcp-perl-task-weaken + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-task-weaken + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..51111f3a50082ea7bb341f321c3b3c3e4c547522 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-task-weaken + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..dab28d2ea9b20d2995bbcf1e60845b7e7bd32f89 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-template-toolkit via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-template-toolkit -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-template-toolkit_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-template-toolkit_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-template-toolkit_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/app/perl-template-toolkit_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/app/perl-template-toolkit_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2ee738fe2330c1b3fdb940104a213790fbdae199 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/app/perl-template-toolkit_server.py @@ -0,0 +1,231 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict +import os + +@mcp.tool() +def tpage( + template_file: Optional[str] = None, + defines: Optional[Dict[str, str]] = None, + pre_chomp: bool = False, + post_chomp: bool = False, + trim: bool = False, + absolute: bool = False, + relative: bool = False, + binmode: Optional[str] = None, + debug: bool = False, +): + """ + Process a single template file using the Template Toolkit 'tpage' utility. + + Args: + template_file: Path to the template file to process. If None, reads from stdin (not recommended for MCP). + defines: Dictionary of template variables to define (e.g., {"name": "world"}). + pre_chomp: Remove whitespace before directives. + post_chomp: Remove whitespace after directives. + trim: Trim leading and trailing whitespace from output. + absolute: Allow absolute paths for templates. + relative: Allow relative paths for templates. + binmode: Set binary mode for output (e.g., 'utf8'). + debug: Enable Template Toolkit debugging. + """ + cmd = ["tpage"] + + # Handle defines + if defines: + for key, value in defines.items(): + cmd.extend(["--define", f"{key}={value}"]) + + # Boolean flags + if pre_chomp: + cmd.append("--pre_chomp") + if post_chomp: + cmd.append("--post_chomp") + if trim: + cmd.append("--trim") + if absolute: + cmd.append("--absolute") + if relative: + cmd.append("--relative") + if debug: + cmd.append("--debug") + + # Optional string parameters + if binmode: + cmd.extend(["--binmode", binmode]) + + # Positional argument + if template_file: + path_obj = Path(template_file) + if not path_obj.exists(): + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": f"Error: Template file '{template_file}' not found.", + "output_files": [] + } + cmd.append(str(path_obj)) + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def ttree( + src: Optional[str] = None, + dest: Optional[str] = None, + cfg: Optional[str] = None, + lib: Optional[List[str]] = None, + all_files: bool = False, + recurse: bool = False, + verbose: bool = False, + ignore: Optional[List[str]] = None, + accept: Optional[List[str]] = None, + suffix: Optional[Dict[str, str]] = None, + prefix: Optional[str] = None, + wrapper: Optional[str] = None, + pre_process: Optional[List[str]] = None, + post_process: Optional[List[str]] = None, + dry_run: bool = False, +): + """ + Process entire directories of template files using the Template Toolkit 'ttree' utility. + + Args: + src: Source directory containing templates. + dest: Destination directory for processed files. + cfg: Path to a configuration file (e.g., .ttreerc). + lib: List of library directories for templates. + all_files: Process all files, even those that haven't changed. + recurse: Recurse into subdirectories. + verbose: List files as they are processed. + ignore: List of regular expressions for files to ignore. + accept: List of regular expressions for files to accept. + suffix: Dictionary mapping template suffixes to output suffixes (e.g., {"tt2": "html"}). + prefix: Prefix to add to output filenames. + wrapper: Template file to wrap around every template processed. + pre_process: List of templates to process before the main template. + post_process: List of templates to process after the main template. + dry_run: Show what would be done without actually doing it. + """ + cmd = ["ttree"] + + # Configuration file + if cfg: + cfg_path = Path(cfg) + if not cfg_path.exists(): + return {"error": f"Config file {cfg} not found."} + cmd.extend(["-f", str(cfg_path)]) + + # Source and Destination + if src: + src_path = Path(src) + if not src_path.is_dir(): + return {"error": f"Source directory {src} does not exist or is not a directory."} + cmd.extend(["-s", str(src_path)]) + + if dest: + dest_path = Path(dest) + # ttree usually requires the destination to exist + if not dest_path.exists(): + dest_path.mkdir(parents=True, exist_ok=True) + cmd.extend(["-d", str(dest_path)]) + + # Libraries + if lib: + for l in lib: + cmd.extend(["-l", l]) + + # Boolean flags + if all_files: + cmd.append("-a") + if recurse: + cmd.append("-r") + if verbose: + cmd.append("-v") + if dry_run: + cmd.append("-n") + + # Regex filters + if ignore: + for pattern in ignore: + cmd.extend(["--ignore", pattern]) + if accept: + for pattern in accept: + cmd.extend(["--accept", pattern]) + + # Suffix mapping + if suffix: + for old, new in suffix.items(): + cmd.extend(["--suffix", f"{old}={new}"]) + + # Other options + if prefix: + cmd.extend(["--prefix", prefix]) + if wrapper: + cmd.extend(["--wrapper", wrapper]) + if pre_process: + for p in pre_process: + cmd.extend(["--pre_process", p]) + if post_process: + for p in post_process: + cmd.extend(["--post_process", p]) + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + + # Identify output files if destination was provided + output_files = [] + if dest: + dest_path = Path(dest) + output_files = [str(p) for p in dest_path.rglob('*') if p.is_file()] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def perl_template_version(): + """ + Check the version of the installed Template Toolkit. + """ + # Template Toolkit doesn't have a simple --version flag on its binaries, + # so we check via perl module version. + cmd = ["perl", "-MTemplate", "-e", "print $Template::VERSION"] + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + return { + "command_executed": " ".join(cmd), + "template_toolkit_version": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": "Could not determine Template Toolkit version. Is it installed?", + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/app/perl-template-toolkit_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/app/perl-template-toolkit_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e327cf7dace0a64ab617529ff363e74f499c4aaf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/app/perl-template-toolkit_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/app/perl-template-toolkit_server.py') +SERVER_NAME = 'biosci_perl_template_toolkit' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..af6c9ebacb43b582921847a705d6608a142fc51b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-template-toolkit: + build: . + image: mcp-perl-template-toolkit:latest + container_name: mcp-perl-template-toolkit + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-template-toolkit + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5e19d174a070be83ffb76f1034d5dac835e6ea22 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-template-toolkit + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..97443f51d7f6cc1b4a6438d3d77fdfde3e8876b6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-term-table via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-term-table -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-term-table_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-term-table_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-term-table_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/app/perl-term-table_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/app/perl-term-table_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6e6d62d05d6424e11e6e590579cbdf1912172db2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/app/perl-term-table_server.py @@ -0,0 +1,57 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Analysis of the provided documentation for 'perl-term-table': +# The documentation describes 'perl-term-table' as a Perl module (Term::Table) +# for formatting tables. It lists dependencies and package metadata from `conda search`. +# +# Crucially, the provided information *does not contain any details* about: +# - Command-line arguments +# - Subcommands +# - Usage examples for direct execution from the shell +# - A `--help` output or manual page content for a command-line executable. +# +# The `home_url` points to a CPAN page for the Perl module, which typically +# describes the module's API for use within Perl scripts, not a standalone +# command-line interface. The extract from this URL also indicates client-side +# issues preventing full access. +# +# Therefore, based on the provided documentation, 'perl-term-table' appears +# to be a Perl library/module intended for programmatic use within Perl scripts, +# rather than a standalone command-line executable with its own set of +# parameters and subcommands. +# +# Without any documented command-line interface, it is impossible to +# extract parameters, their types, default values, or constraints, +# and thus, impossible to create an MCP tool function that wraps a +# non-existent command-line interface. + +@mcp.tool() +def perl_term_table_cli_not_found() -> Dict[str, Any]: + """ + Indicates that no command-line interface was found for perl-term-table. + + The provided documentation for 'perl-term-table' describes it as a Perl module + (Term::Table) for formatting tables, but it does not specify any command-line + arguments, subcommands, or direct executable usage. Perl modules are typically + integrated into custom Perl scripts rather than being run directly from the + command line with their own set of parameters. + + Therefore, a functional MCP tool cannot be generated as there is no documented + command-line interface to wrap. This function serves as a placeholder to + communicate this limitation. + """ + # As there's no documented CLI, we cannot construct or execute any command. + # We return an error message explaining the situation. + return { + "command_executed": "No command could be constructed or executed because 'perl-term-table' " + "does not appear to have a documented command-line interface.", + "stdout": "", + "stderr": "Error: The provided documentation for 'perl-term-table' describes it as a Perl module " + "(Term::Table) but does not include any information about a command-line interface, " + "subcommands, or parameters for direct execution. " + "To create an MCP tool, explicit command-line usage details are required. " + "Please provide documentation for a specific command-line wrapper script if one exists.", + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/app/perl-term-table_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/app/perl-term-table_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ca9ef6071c254c18c6857308de93bcf553df7b8d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/app/perl-term-table_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/app/perl-term-table_server.py') +SERVER_NAME = 'biosci_perl_term_table' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..9d85988c596fef0a834d7fd0bb6f7dccd079297b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-term-table: + build: . + image: mcp-perl-term-table:latest + container_name: mcp-perl-term-table + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-term-table + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6608152f491a9d5b15f3413bd47494b8860fe2f5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-term-table + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-term-table/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ae33589b1adbb38ca8215eb9e354e614f6649f03 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-test-deep via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-test-deep -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-test-deep_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-test-deep_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-test-deep_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/app/perl-test-deep_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/app/perl-test-deep_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0bfd3c6eb0fe528d2a13e19276a2670a0924579c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/app/perl-test-deep_server.py @@ -0,0 +1,225 @@ +from typing import List, Optional +import subprocess +from pathlib import Path + +@mcp.tool() +def perl_test_deep_run_script( + script_path: str, + arguments: Optional[List[str]] = None, + include_dirs: Optional[List[str]] = None, + modules: Optional[List[str]] = None, + warning_mode: str = "many", + taint_mode: str = "none", + syntax_check_only: bool = False, + autosplit: bool = False, + split_pattern: Optional[str] = None, + inplace_extension: Optional[str] = None, + line_ending_processing: Optional[str] = None, + loop_mode: str = "none", + unicode_features: Optional[str] = None, + no_site_customize: bool = False, + search_path: bool = False, + unsafe_operations: bool = False, + record_separator: Optional[str] = None, +): + """ + Execute a Perl script using the perl-test-deep environment. + This tool allows running complex deep comparison tests using the Test::Deep module. + + Args: + script_path: Path to the Perl script (.pl or .t) to execute. + arguments: List of command-line arguments to pass to the script. + include_dirs: List of directories to add to @INC (Perl's include path). + modules: List of additional modules to load (e.g., ["JSON", "YAML"]). Test::Deep is often loaded within the script. + warning_mode: Warning level: 'default', 'many' (-w), 'all' (-W), or 'none' (-X). + taint_mode: Taint checking: 'none', 'warnings' (-t), or 'checks' (-T). + syntax_check_only: If True, only check syntax without executing (-c). + autosplit: Enable autosplit mode (-a) with loop_mode. + split_pattern: Pattern for autosplit (-F). + inplace_extension: Edit files in place, optionally providing a backup extension (-i). + line_ending_processing: Enable line ending processing (-l). + loop_mode: Loop mode: 'none', 'n' (while(<>)), or 'p' (while(<>) { print }). + unicode_features: Enable Unicode features (-C). + no_site_customize: Don't run sitecustomize.pl at startup (-f). + search_path: Look for programfile using PATH environment variable (-S). + unsafe_operations: Allow unsafe operations (-U). + record_separator: Specify record separator (-0). + """ + # Input validation + script_file = Path(script_path) + if not script_file.exists(): + return {"error": f"Script file not found: {script_path}"} + + if warning_mode not in ["default", "many", "all", "none"]: + return {"error": "warning_mode must be one of: default, many, all, none"} + + if taint_mode not in ["none", "warnings", "checks"]: + return {"error": "taint_mode must be one of: none, warnings, checks"} + + if loop_mode not in ["none", "n", "p"]: + return {"error": "loop_mode must be one of: none, n, p"} + + # Build command + cmd = ["perl"] + + # Add switches + if warning_mode == "many": cmd.append("-w") + elif warning_mode == "all": cmd.append("-W") + elif warning_mode == "none": cmd.append("-X") + + if taint_mode == "warnings": cmd.append("-t") + elif taint_mode == "checks": cmd.append("-T") + + if syntax_check_only: cmd.append("-c") + if autosplit: cmd.append("-a") + if no_site_customize: cmd.append("-f") + if search_path: cmd.append("-S") + if unsafe_operations: cmd.append("-U") + + if record_separator is not None: cmd.append(f"-0{record_separator}") + if unicode_features is not None: cmd.append(f"-C{unicode_features}") + if split_pattern is not None: cmd.append(f"-F{split_pattern}") + if inplace_extension is not None: cmd.append(f"-i{inplace_extension}") + if line_ending_processing is not None: cmd.append(f"-l{line_ending_processing}") + + if loop_mode == "n": cmd.append("-n") + elif loop_mode == "p": cmd.append("-p") + + if include_dirs: + for d in include_dirs: + cmd.append(f"-I{d}") + + if modules: + for m in modules: + cmd.append(f"-M{m}") + + # Add script and its arguments + cmd.append(str(script_file)) + if arguments: + cmd.extend(arguments) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "status": "error", + "exit_code": e.returncode + } + +@mcp.tool() +def perl_test_deep_one_liner( + code: str, + arguments: Optional[List[str]] = None, + include_dirs: Optional[List[str]] = None, + use_test_deep: bool = True, + warning_mode: str = "many", + autosplit: bool = False, + loop_mode: str = "none", + unicode_features: Optional[str] = None, +): + """ + Execute a Perl one-liner using the perl-test-deep environment. + Useful for quick data structure comparisons or small test snippets. + + Args: + code: The Perl code to execute. + arguments: List of command-line arguments (e.g., input files). + include_dirs: List of directories to add to @INC. + use_test_deep: Automatically load the Test::Deep module (-MTest::Deep). + warning_mode: Warning level: 'default', 'many' (-w), 'all' (-W), or 'none' (-X). + autosplit: Enable autosplit mode (-a). + loop_mode: Loop mode: 'none', 'n' (while(<>)), or 'p' (while(<>) { print }). + unicode_features: Enable Unicode features (-C). + """ + if warning_mode not in ["default", "many", "all", "none"]: + return {"error": "warning_mode must be one of: default, many, all, none"} + + if loop_mode not in ["none", "n", "p"]: + return {"error": "loop_mode must be one of: none, n, p"} + + cmd = ["perl"] + + if use_test_deep: + cmd.append("-MTest::Deep") + + if warning_mode == "many": cmd.append("-w") + elif warning_mode == "all": cmd.append("-W") + elif warning_mode == "none": cmd.append("-X") + + if autosplit: cmd.append("-a") + if loop_mode == "n": cmd.append("-n") + elif loop_mode == "p": cmd.append("-p") + if unicode_features is not None: cmd.append(f"-C{unicode_features}") + + if include_dirs: + for d in include_dirs: + cmd.append(f"-I{d}") + + cmd.extend(["-e", code]) + + if arguments: + cmd.extend(arguments) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "status": "error", + "exit_code": e.returncode + } + +@mcp.tool() +def perl_test_deep_version_info( + verbose: bool = False, + config_variable: Optional[str] = None, +): + """ + Get version and configuration information for the Perl environment. + + Args: + verbose: If True, print configuration summary (-V). If False, print version (-v). + config_variable: Print the value of a specific configuration variable (e.g., 'installsitelib'). + """ + cmd = ["perl"] + + if config_variable: + cmd.append(f"-V:{config_variable}") + elif verbose: + cmd.append("-V") + else: + cmd.append("-v") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "status": "error", + "exit_code": e.returncode + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/app/perl-test-deep_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/app/perl-test-deep_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..40620d0a5ada477d4b50f221e94083ea06a1a6b7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/app/perl-test-deep_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/app/perl-test-deep_server.py') +SERVER_NAME = 'biosci_perl_test_deep' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..53ff855d2d208b1c0b0a31662cb9d9c2c2351308 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-test-deep: + build: . + image: mcp-perl-test-deep:latest + container_name: mcp-perl-test-deep + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-test-deep + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f387fe381f1a634c87ef05d5e1486a6fd7dcdc8d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-test-deep + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ea1c5d7d00b5ff552e5f01fe3ef90c20341ff063 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-test-differences via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-test-differences -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-test-differences_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-test-differences_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-test-differences_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/app/perl-test-differences_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/app/perl-test-differences_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2f654f00da13e5e873f3e536427c2dede994042e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/app/perl-test-differences_server.py @@ -0,0 +1,212 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any +import json + +@mcp.tool() +def perl_test_differences_text( + got: str, + expected: str, + name: str = "text_comparison", + style: str = "table", + context: int = 3, +) -> Dict[str, Any]: + """ + Compare two strings using Perl's Test::Differences and show the differences. + Useful for identifying exact discrepancies between multi-line strings or command outputs. + + Args: + got: The actual string received. + expected: The expected string. + name: A label for the comparison test. + style: The diff style to use ('table', 'unified', 'context', or 'oldstyle'). + context: Number of lines of context to show around differences (for 'unified' or 'context' styles). + """ + # Validate style + valid_styles = ["table", "unified", "context", "oldstyle"] + if style not in valid_styles: + style = "table" + + # Construct Perl one-liner + # We use Test::More to provide the test harness and Test::Differences for the diff logic + perl_script = ( + "use Test::More; " + "use Test::Differences; " + "plan tests => 1; " + f"eq_or_diff($ARGV[0], $ARGV[1], $ARGV[2], {{ style => '{style}', context => {context} }});" + ) + + cmd = ["perl", "-MTest::More", "-MTest::Differences", "-e", perl_script, "--", got, expected, name] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=False) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "test_passed": result.returncode == 0, + "output_files": [] + } + except Exception as e: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": str(e), + "test_passed": False, + "output_files": [] + } + +@mcp.tool() +def perl_test_differences_files( + file_path_1: str, + file_path_2: str, + name: str = "file_comparison", + style: str = "table", + context: int = 3, +) -> Dict[str, Any]: + """ + Compare the contents of two files using Perl's Test::Differences. + Commonly used in bioinformatics to verify that a tool's output matches a reference file. + + Args: + file_path_1: Path to the first file (actual). + file_path_2: Path to the second file (expected). + name: A label for the comparison test. + style: The diff style to use ('table', 'unified', 'context', or 'oldstyle'). + context: Number of lines of context to show around differences. + """ + path1 = Path(file_path_1) + path2 = Path(file_path_2) + + if not path1.exists(): + return {"error": f"File not found: {file_path_1}"} + if not path2.exists(): + return {"error": f"File not found: {file_path_2}"} + + # Read file contents + try: + content1 = path1.read_text() + content2 = path2.read_text() + except Exception as e: + return {"error": f"Failed to read files: {str(e)}"} + + # Validate style + valid_styles = ["table", "unified", "context", "oldstyle"] + if style not in valid_styles: + style = "table" + + perl_script = ( + "use Test::More; " + "use Test::Differences; " + "plan tests => 1; " + f"eq_or_diff($ARGV[0], $ARGV[1], $ARGV[2], {{ style => '{style}', context => {context} }});" + ) + + cmd = ["perl", "-MTest::More", "-MTest::Differences", "-e", perl_script, "--", content1, content2, name] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=False) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "test_passed": result.returncode == 0, + "output_files": [] + } + except Exception as e: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": str(e), + "test_passed": False, + "output_files": [] + } + +@mcp.tool() +def perl_test_differences_data( + got_json: str, + expected_json: str, + name: str = "data_structure_comparison", + style: str = "table", +) -> Dict[str, Any]: + """ + Compare two complex data structures (provided as JSON strings) using Perl's Test::Differences. + This tool decodes the JSON and compares the underlying structures (hashes, arrays). + + Args: + got_json: The actual data structure in JSON format. + expected_json: The expected data structure in JSON format. + name: A label for the comparison test. + style: The diff style to use ('table', 'unified', 'context', or 'oldstyle'). + """ + # Validate JSON inputs + try: + json.loads(got_json) + json.loads(expected_json) + except json.JSONDecodeError as e: + return {"error": f"Invalid JSON input: {str(e)}"} + + # Validate style + valid_styles = ["table", "unified", "context", "oldstyle"] + if style not in valid_styles: + style = "table" + + # Perl script that uses JSON::PP (core module) to decode strings into Perl structures + # then compares them using eq_or_diff + perl_script = ( + "use Test::More; " + "use Test::Differences; " + "use JSON::PP; " + "my $json = JSON::PP->new; " + "my $data_got = $json->decode($ARGV[0]); " + "my $data_exp = $json->decode($ARGV[1]); " + "plan tests => 1; " + f"eq_or_diff($data_got, $data_exp, $ARGV[2], {{ style => '{style}' }});" + ) + + cmd = ["perl", "-MTest::More", "-MTest::Differences", "-MJSON::PP", "-e", perl_script, "--", got_json, expected_json, name] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=False) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "test_passed": result.returncode == 0, + "output_files": [] + } + except Exception as e: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": str(e), + "test_passed": False, + "output_files": [] + } + +@mcp.tool() +def perl_test_differences_version() -> Dict[str, Any]: + """ + Check the installed version of the Test::Differences Perl module. + """ + perl_script = "use Test::Differences; print $Test::Differences::VERSION;" + cmd = ["perl", "-MTest::Differences", "-e", perl_script] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "version": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Test::Differences module not found or perl execution failed." + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/app/perl-test-differences_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/app/perl-test-differences_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b5c4c6c1bd0b710ef1cf45c3b2822d729e39121a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/app/perl-test-differences_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/app/perl-test-differences_server.py') +SERVER_NAME = 'biosci_perl_test_differences' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..da2ae77c047f4b0d68f469f632ce6958f71311a8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-test-differences: + build: . + image: mcp-perl-test-differences:latest + container_name: mcp-perl-test-differences + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-test-differences + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a8f7f65557547303244bf741ebf9da6d0df06435 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-test-differences + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-differences/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2cff8f09eb482eff548681fb906154ca25ef62be --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-test-exception via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-test-exception -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-test-exception_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-test-exception_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-test-exception_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/app/perl-test-exception_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/app/perl-test-exception_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c7e098bca593c6a497b775aa64e5d641970f03e2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/app/perl-test-exception_server.py @@ -0,0 +1,222 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +@mcp.tool() +def perl_test_exception( + program_file: Optional[str] = None, + one_liner: Optional[str] = None, + use_all_features: bool = False, + modules: List[str] = ["Test::Exception"], + include_dirs: List[str] = [], + warnings: str = "warn", + taint_check: bool = False, + taint_warnings: bool = False, + syntax_only: bool = False, + autosplit: bool = False, + split_pattern: Optional[str] = None, + inplace_edit_extension: Optional[str] = None, + record_separator: Optional[str] = None, + line_ending_processing: bool = False, + loop_mode: str = "none", + unsafe_operations: bool = False, + ignore_text_before_perl: Optional[str] = None, + script_args: List[str] = [], +): + """ + Executes Perl scripts or commands, specifically configured to use the Test::Exception module. + Test::Exception provides a few convenience methods for testing exception-based code. + + Args: + program_file: Path to the Perl script or test file (.pl or .t) to execute. + one_liner: A string containing Perl code to execute (maps to -e or -E). + use_all_features: If True, uses -E instead of -e for one-liners, enabling all optional features. + modules: List of modules to load before execution (maps to -M). Defaults to ['Test::Exception']. + include_dirs: List of directories to add to @INC for module searching (maps to -I). + warnings: Warning level. Options: 'warn' (-w), 'all' (-W), 'none' (-X), or 'default'. + taint_check: Enable taint checks (maps to -T). + taint_warnings: Enable taint warnings (maps to -t). + syntax_only: Check syntax only without executing (maps to -c). + autosplit: Enable autosplit mode with -n or -p (maps to -a). + split_pattern: Pattern for autosplit (maps to -F). + inplace_edit_extension: Edit files in place, optionally providing a backup extension (maps to -i). + record_separator: Specify record separator (maps to -0). + line_ending_processing: Enable line ending processing (maps to -l). + loop_mode: Wrap code in a loop. 'n' for 'while(<>)', 'p' for loop with print, 'none' for no loop. + unsafe_operations: Allow unsafe operations (maps to -U). + ignore_text_before_perl: Ignore text before #!perl line, optionally cd to directory (maps to -x). + script_args: Arguments passed to the Perl script. + """ + + cmd = ["perl"] + + # 1. Handle Switches + if record_separator is not None: + cmd.append(f"-0{record_separator}") + + if autosplit: + cmd.append("-a") + + if syntax_only: + cmd.append("-c") + + if use_all_features and one_liner: + cmd.append("-E") + cmd.append(one_liner) + elif one_liner: + cmd.append("-e") + cmd.append(one_liner) + + if split_pattern: + cmd.append(f"-F{split_pattern}") + + if inplace_edit_extension is not None: + cmd.append(f"-i{inplace_edit_extension}") + + for d in include_dirs: + cmd.append(f"-I{d}") + + if line_ending_processing: + cmd.append("-l") + + for m in modules: + cmd.append(f"-M{m}") + + if loop_mode == "n": + cmd.append("-n") + elif loop_mode == "p": + cmd.append("-p") + + if taint_check: + cmd.append("-T") + elif taint_warnings: + cmd.append("-t") + + if unsafe_operations: + cmd.append("-U") + + if warnings == "warn": + cmd.append("-w") + elif warnings == "all": + cmd.append("-W") + elif warnings == "none": + cmd.append("-X") + + if ignore_text_before_perl: + cmd.append(f"-x{ignore_text_before_perl}") + + # 2. Handle Program File + if program_file: + prog_path = Path(program_file) + if not prog_path.exists(): + return { + "error": f"Program file not found: {program_file}", + "command_executed": " ".join(cmd) + } + cmd.append(str(prog_path)) + + # 3. Handle Script Arguments + if script_args: + if not program_file and not one_liner: + # If no program is specified, arguments might be interpreted as files for -n/-p + pass + cmd.extend(script_args) + + # 4. Execution + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "return_code": result.returncode + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "error": "Perl execution failed" + } + except Exception as e: + return { + "command_executed": " ".join(cmd), + "error": str(e) + } + +@mcp.tool() +def perl_version_info(): + """ + Returns the version and configuration summary of the installed Perl environment. + Equivalent to running 'perl -v' and 'perl -V'. + """ + try: + v_result = subprocess.run(["perl", "-v"], capture_output=True, text=True, check=True) + V_result = subprocess.run(["perl", "-V"], capture_output=True, text=True, check=True) + + return { + "version_short": v_result.stdout, + "config_summary": V_result.stdout + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to retrieve Perl version info", + "stderr": e.stderr + } + +@mcp.tool() +def check_perl_module_installed(module_name: str = "Test::Exception"): + """ + Checks if a specific Perl module is installed and available in the current environment. + + Args: + module_name: The name of the Perl module to check (e.g., 'Test::Exception', 'Sub::Uplevel'). + """ + cmd = ["perl", f"-M{module_name}", "-e", "1"] + try: + subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "module": module_name, + "installed": True, + "message": f"Module '{module_name}' is installed." + } + except subprocess.CalledProcessError: + return { + "module": module_name, + "installed": False, + "message": f"Module '{module_name}' is NOT installed or could not be loaded." + } + +@mcp.tool() +def run_perl_test_file( + test_file: str, + include_dirs: List[str] = [], + verbose: bool = True +): + """ + A specialized tool for running Perl test files (.t) using Test::Exception. + This is a convenience wrapper around perl_test_exception. + + Args: + test_file: Path to the .t test file. + include_dirs: Additional directories to include in @INC. + verbose: If True, ensures warnings are enabled. + """ + # Validate file + path = Path(test_file) + if not path.exists(): + return {"error": f"Test file {test_file} does not exist."} + + # Use the main executor logic + return perl_test_exception( + program_file=test_file, + modules=["Test::Exception"], + include_dirs=include_dirs, + warnings="warn" if verbose else "default" + ) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/app/perl-test-exception_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/app/perl-test-exception_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0a5a5c35536675d7a0edd12693b874278e410f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/app/perl-test-exception_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/app/perl-test-exception_server.py') +SERVER_NAME = 'biosci_perl_test_exception' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f726d555675cd90fe8521e3b43eb1fae01be69e3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-test-exception: + build: . + image: mcp-perl-test-exception:latest + container_name: mcp-perl-test-exception + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-test-exception + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..047406f21859c8e465045f78f78d98a4996efb76 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-test-exception + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-exception/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..de84811826a5324ac7ee9dedc7217c88be9a57f9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-test-fatal via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-test-fatal -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-test-fatal_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-test-fatal_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-test-fatal_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/app/perl-test-fatal_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/app/perl-test-fatal_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b76a58aaaceb6dd2760dea43083eb4f5084acf66 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/app/perl-test-fatal_server.py @@ -0,0 +1,187 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# In a real MCP environment, this would be: from mcp import tool +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def perl_execute( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + execute_program: Optional[List[str]] = None, + execute_program_features: Optional[List[str]] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + run_under_debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + in_place_edit: Optional[str] = None, + include_directory: Optional[List[Path]] = None, + use_module: Optional[List[str]] = None, + use_module_no_import: Optional[List[str]] = None, + no_module: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + parse_switches: bool = False, + search_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core: bool = False, + allow_unsafe: bool = False, + print_version: bool = False, + print_config: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + extract_from_text: bool = False, + change_dir_after_extract: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Executes a Perl script or one-liner using the Perl interpreter. + + This tool is a wrapper for the `perl` command-line interpreter. The requested + package, `perl-test-fatal`, is a library module for testing exceptions in + Perl code and does not have its own executable. The provided help documentation + was for the `perl` interpreter itself. + + Args: + programfile: Path to the Perl program file to execute. + arguments: List of arguments to pass to the program file. + execute_program: One or more lines of a program passed on the command line (-e). + execute_program_features: Like -e, but enables all optional features (-E). + record_separator: Specify record separator, e.g., '0777' for slurp mode (-0). + autosplit: Enable autosplit mode with -n or -p (-a). + unicode_features: Enable listed Unicode features (-C). + check_syntax_only: Check syntax only, runs BEGIN and CHECK blocks (-c). + run_under_debugger: Run program under debugger. Can specify debugger, e.g., 'My::Debugger' (-d). + debugging_flags: Set debugging flags (-D). + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup (-f). + split_pattern: Specify split() pattern for -a switch (-F). + in_place_edit: Edit <> files in place. Provide an extension for backup, e.g., '.bak' (-i). + include_directory: Specify @INC/#include directory. Can be used multiple times (-I). + use_module: Execute "use module..." before executing the program (-M). + use_module_no_import: Execute "use module ()" before executing the program (-m). + no_module: Execute "no module..." before executing the program (-M-module). + loop_around_program: Assume "while (<>) { ... }" loop around the program (-n). + loop_and_print: Assume loop like -n but also print line (-p). + parse_switches: Enable rudimentary parsing for switches after programfile (-s). + search_path: Look for programfile using the PATH environment variable (-S). + tainting_warnings: Enable tainting warnings (-t). + tainting_checks: Enable tainting checks (-T). + dump_core: Dump core after parsing the program (-u). + allow_unsafe: Allow unsafe operations (-U). + print_version: Print version, patchlevel, and license (-v). + print_config: Print configuration summary or a single variable (-V). + enable_warnings: Enable many useful warnings (-w). + enable_all_warnings: Enable all warnings (-W). + disable_all_warnings: Disable all warnings (-X). + extract_from_text: Ignore text before #!perl line (-x). + change_dir_after_extract: Optionally cd to this directory with -x. + + Returns: + A dictionary containing the executed command, stdout, stderr, and any errors. + """ + # --- Input Validation --- + script_sources = sum(p is not None for p in [programfile, execute_program, execute_program_features]) + info_flags = sum([print_version, print_config is not None]) + + if script_sources > 1: + raise ValueError("Only one of 'programfile', 'execute_program', or 'execute_program_features' can be specified at a time.") + + if script_sources == 0 and info_flags == 0: + raise ValueError("A program source must be provided via 'programfile', 'execute_program', 'execute_program_features', or an informational flag like 'print_version' or 'print_config'.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"The program file '{programfile}' does not exist.") + + warning_flags = sum([enable_warnings, enable_all_warnings, disable_all_warnings]) + if warning_flags > 1: + raise ValueError("Only one of 'enable_warnings' (-w), 'enable_all_warnings' (-W), or 'disable_all_warnings' (-X) can be used at a time.") + + if change_dir_after_extract and not extract_from_text: + extract_from_text = True + + # --- Command Construction --- + cmd = ["perl"] + + if record_separator is not None: cmd.append(f"-0{record_separator}") + if autosplit: cmd.append("-a") + if unicode_features is not None: cmd.append(f"-C{unicode_features}") + if check_syntax_only: cmd.append("-c") + if run_under_debugger is not None: cmd.append(f"-d:{run_under_debugger}" if run_under_debugger else "-d") + if debugging_flags is not None: cmd.append(f"-D{debugging_flags}") + if no_sitecustomize: cmd.append("-f") + if split_pattern is not None: cmd.append(f"-F{split_pattern}") + if in_place_edit is not None: cmd.append(f"-i{in_place_edit}") + if include_directory: + for directory in include_directory: cmd.extend(["-I", str(directory)]) + if use_module: + for module in use_module: cmd.append(f"-M{module}") + if use_module_no_import: + for module in use_module_no_import: cmd.append(f"-m{module}") + if no_module: + for module in no_module: cmd.append(f"-M-{module}") + if loop_and_print: cmd.append("-p") + elif loop_around_program: cmd.append("-n") + if parse_switches: cmd.append("-s") + if search_path: cmd.append("-S") + if tainting_warnings: cmd.append("-t") + if tainting_checks: cmd.append("-T") + if dump_core: cmd.append("-u") + if allow_unsafe: cmd.append("-U") + if print_version: cmd.append("-v") + if print_config is not None: cmd.append(f"-V:{print_config}" if print_config else "-V") + if enable_warnings: cmd.append("-w") + if enable_all_warnings: cmd.append("-W") + if disable_all_warnings: cmd.append("-X") + if extract_from_text: + if change_dir_after_extract: cmd.extend(["-x", str(change_dir_after_extract)]) + else: cmd.append("-x") + + if execute_program: + for line in execute_program: cmd.extend(["-e", line]) + if execute_program_features: + for line in execute_program_features: cmd.extend(["-E", line]) + + if programfile: cmd.append(str(programfile)) + if arguments: + if programfile: cmd.append("--") + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=False # Check manually to provide better error context + ) + if result.returncode != 0: + return { + "error": f"Perl execution failed with exit code {result.returncode}.", + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + return { + "error": "Perl executable not found. Please ensure 'perl' is in your system's PATH.", + "command_executed": command_executed, + "stdout": "", + "stderr": "", + } + + # --- Structured Result Return --- + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/app/perl-test-fatal_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/app/perl-test-fatal_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b7083c7c7b07862abadfaa85d074ec8ffe7ebb8d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/app/perl-test-fatal_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/app/perl-test-fatal_server.py') +SERVER_NAME = 'biosci_perl_test_fatal' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..76e5f4a2bbe4cfeb9ddf5f5ff03db9d3fc6965eb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-test-fatal: + build: . + image: mcp-perl-test-fatal:latest + container_name: mcp-perl-test-fatal + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-test-fatal + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..500370998d00299db5c6f4fb05f75a192e27d7cf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-test-fatal + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-fatal/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fd33a7d8e877fde9d158456269bc0ca4fabc54c2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-test-harness via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-test-harness -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-test-harness_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-test-harness_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-test-harness_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/app/perl-test-harness_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/app/perl-test-harness_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ec77f7df72ce073718e1cdd1c997b489387e05d3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/app/perl-test-harness_server.py @@ -0,0 +1,242 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +@mcp.tool() +def run_perl_script( + program_file: Optional[Path] = None, + program_arguments: Optional[List[str]] = None, + program_code: Optional[List[str]] = None, + program_code_with_features: Optional[List[str]] = None, + zero_record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Union[bool, str] = False, + debugging_flags: Optional[str] = None, + no_site_customize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + use_modules: Optional[List[str]] = None, + no_modules: Optional[List[str]] = None, + assume_loop_n: bool = False, + assume_loop_p: bool = False, + rudimentary_switch_parsing: bool = False, + search_path_for_program: bool = False, + enable_tainting_warnings: bool = False, + enable_tainting_checks: bool = False, + dump_core_after_parsing: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: Union[bool, str] = False, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_perl_line: Union[bool, Path] = False, + disable_all_warnings: bool = False, +) -> dict: + """ + Executes a Perl script or one-liner with various Perl interpreter options. + + This tool wraps the 'perl' command, allowing users to run Perl programs + with fine-grained control over its execution environment and features. + It supports running a script file, or providing Perl code directly via + one-liners (-e or -E). + + Args: + program_file: Path to the Perl script file to execute. + program_arguments: List of arguments to pass to the Perl script. + program_code: List of Perl code lines to execute directly via -e. + Can be specified multiple times for multiple lines. + program_code_with_features: List of Perl code lines to execute directly via -E, + enabling all optional features. Can be specified + multiple times for multiple lines. + zero_record_separator: Specify record separator. If an empty string, defaults to \\0. + Otherwise, specifies an octal value. + autosplit: Enable autosplit mode with -n or -p (splits $_ into @F). + unicode_features: Enables the listed Unicode features (number or list). + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). + debugger: Run program under debugger. If True, runs with default debugger. + If a string, specifies the debugger (e.g., 'MyDebugger'). + debugging_flags: Set debugging flags (argument is a bit mask or alphabets). + no_site_customize: Don't do $sitelib/sitecustomize.pl at startup. + split_pattern: split() pattern for -a switch (e.g., '/\\s+/'). + edit_in_place_extension: Edit <> files in place. If an extension is supplied, + makes a backup (e.g., '.bak'). + include_directories: List of directories to specify for @INC/#include. + line_ending_processing: Enable line ending processing. If an octal value is + supplied, specifies the line terminator. If an empty + string, enables processing with default terminator. + use_modules: List of modules to execute "use module..." before executing program. + Uses the -M switch. + no_modules: List of modules to execute "no module..." before executing program. + Uses the -M- switch. + assume_loop_n: Assume "while (<>) { ... }" loop around program. + assume_loop_p: Assume loop like -n but print line also, like sed. + rudimentary_switch_parsing: Enable rudimentary parsing for switches after programfile. + search_path_for_program: Look for programfile using PATH environment variable. + enable_tainting_warnings: Enable tainting warnings. + enable_tainting_checks: Enable tainting checks. + dump_core_after_parsing: Dump core after parsing program. + allow_unsafe_operations: Allow unsafe operations. + print_version: Print Perl version, patchlevel, and license. + print_config_summary: Print configuration summary. If True, prints full summary. + If a string, prints a single Config.pm variable (e.g., 'archname'). + enable_warnings: Enable many useful warnings (-w). + enable_all_warnings: Enable all warnings (-W). + ignore_text_before_perl_line: Ignore text before #!perl line. If True, ignores. + If a Path, optionally cd to that directory. + disable_all_warnings: Disable all warnings (-X). + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + cmd: List[str] = ["perl"] + output_files: List[Path] = [] + + # Input validation + if program_file and (program_code or program_code_with_features): + raise ValueError("Cannot specify both 'program_file' and 'program_code'/'program_code_with_features'.") + if not program_file and not program_code and not program_code_with_features and not print_version and not print_config_summary: + raise ValueError("Either 'program_file', 'program_code', 'program_code_with_features', 'print_version', or 'print_config_summary' must be provided.") + + if assume_loop_n and assume_loop_p: + raise ValueError("Cannot use both 'assume_loop_n' (-n) and 'assume_loop_p' (-p) simultaneously.") + + # Conflicting warning options + warning_options_count = sum([enable_warnings, enable_all_warnings, disable_all_warnings]) + if warning_options_count > 1: + raise ValueError("Cannot use conflicting warning options (-w, -W, -X) simultaneously.") + + if program_file: + if not program_file.is_file(): + raise FileNotFoundError(f"Program file not found: {program_file}") + + # Command construction + if zero_record_separator is not None: + cmd.append(f"-0{zero_record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if debugger: + if isinstance(debugger, str): + cmd.append(f"-d:{debugger}") + else: # debugger is True + cmd.append("-d") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if program_code: + for code_line in program_code: + cmd.append("-e") + cmd.append(code_line) + if program_code_with_features: + for code_line in program_code_with_features: + cmd.append("-E") + cmd.append(code_line) + if no_site_customize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + cmd.append(f"-i{edit_in_place_extension}") + if include_directories: + for inc_dir in include_directories: + if not inc_dir.is_dir(): + raise NotADirectoryError(f"Include directory not found or not a directory: {inc_dir}") + cmd.append("-I") + cmd.append(str(inc_dir)) + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + if use_modules: + for module in use_modules: + cmd.append("-M") + cmd.append(module) + if no_modules: + for module in no_modules: + cmd.append("-M-") + cmd.append(module) + if assume_loop_n: + cmd.append("-n") + if assume_loop_p: + cmd.append("-p") + if rudimentary_switch_parsing: + cmd.append("-s") + if search_path_for_program: + cmd.append("-S") + if enable_tainting_warnings: + cmd.append("-t") + if enable_tainting_checks: + cmd.append("-T") + if dump_core_after_parsing: + cmd.append("-u") + if allow_unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config_summary: + if isinstance(print_config_summary, str): + cmd.append(f"-V:{print_config_summary}") + else: # print_config_summary is True + cmd.append("-V") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if ignore_text_before_perl_line: + if isinstance(ignore_text_before_perl_line, Path): + if not ignore_text_before_perl_line.is_dir(): + raise NotADirectoryError(f"Directory for -x option not found or not a directory: {ignore_text_before_perl_line}") + cmd.append(f"-x{ignore_text_before_perl_line}") + else: # ignore_text_before_perl_line is True + cmd.append("-x") + if disable_all_warnings: + cmd.append("-X") + + # Add program file and its arguments (positional) + if program_file: + cmd.append(str(program_file)) + if program_arguments: + cmd.extend(program_arguments) + + process = None + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + except Exception as e: + # Catch any other unexpected errors + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout if process else "", + "stderr": f"An unexpected error occurred: {e}", + "output_files": [], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/app/perl-test-harness_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/app/perl-test-harness_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..76e85e4d335fd7720a5ebd566e1076e32da32ad3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/app/perl-test-harness_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/app/perl-test-harness_server.py') +SERVER_NAME = 'biosci_perl_test_harness' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..98784a24433ea366bf5bba85b5f5ed6f15dfd6e4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-test-harness: + build: . + image: mcp-perl-test-harness:latest + container_name: mcp-perl-test-harness + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-test-harness + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0291b8e5b4e6d9afb082581b367dcc5366516db7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-test-harness + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-harness/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d765b9484846a581d773fb302d84c6e7b66fc273 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-test-leaktrace via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-test-leaktrace -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-test-leaktrace_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-test-leaktrace_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-test-leaktrace_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/app/perl-test-leaktrace_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/app/perl-test-leaktrace_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8954869cb517abcef50620758061dcc738f6a9ca --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/app/perl-test-leaktrace_server.py @@ -0,0 +1,241 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +@mcp.tool() +def perl_leaktrace( + script_path: Optional[str] = None, + code: Optional[str] = None, + code_with_features: Optional[str] = None, + include_dirs: Optional[List[str]] = None, + script_args: Optional[List[str]] = None, + warnings: bool = False, + all_warnings: bool = False, + disable_warnings: bool = False, + taint_check: bool = False, + taint_warnings: bool = False, + syntax_check_only: bool = False, + autosplit: bool = False, + split_pattern: Optional[str] = None, + inplace_extension: Optional[str] = None, + loop_n: bool = False, + loop_p: bool = False, + record_separator: Optional[str] = None, + unicode_features: Optional[str] = None, + debug_flags: Optional[str] = None, + line_ending_processing: bool = False, + switch_parsing: bool = False, + use_path_env: bool = False, + unsafe_operations: bool = False, +): + """ + Executes Perl with the Test::LeakTrace module to trace memory leaks. + Test::LeakTrace provides several functions (like leaktrace, leaked_info, no_leaks_ok) + to help detect memory leaks in Perl code. + + Args: + script_path: Path to the Perl script file to execute. + code: One line of program to execute (equivalent to perl -e). + code_with_features: Like 'code', but enables all optional features (equivalent to perl -E). + include_dirs: List of directories to add to @INC for module searching (equivalent to perl -I). + script_args: Arguments to pass to the Perl script. + warnings: Enable many useful warnings (equivalent to perl -w). + all_warnings: Enable all warnings (equivalent to perl -W). + disable_warnings: Disable all warnings (equivalent to perl -X). + taint_check: Enable taint checks (equivalent to perl -T). + taint_warnings: Enable taint warnings (equivalent to perl -t). + syntax_check_only: Check syntax only without executing (equivalent to perl -c). + autosplit: Enable autosplit mode with -n or -p (equivalent to perl -a). + split_pattern: Pattern for autosplit (equivalent to perl -F). + inplace_extension: Edit files in place, optionally making a backup (equivalent to perl -i). + loop_n: Assume 'while (<>) { ... }' loop around program (equivalent to perl -n). + loop_p: Like -n but print line also (equivalent to perl -p). + record_separator: Specify record separator (equivalent to perl -0). + unicode_features: Enable listed Unicode features (equivalent to perl -C). + debug_flags: Set debugging flags (equivalent to perl -D). + line_ending_processing: Enable line ending processing (equivalent to perl -l). + switch_parsing: Enable rudimentary parsing for switches after programfile (equivalent to perl -s). + use_path_env: Look for programfile using PATH environment variable (equivalent to perl -S). + unsafe_operations: Allow unsafe operations (equivalent to perl -U). + """ + + # Initialize command with the perl interpreter and the Test::LeakTrace module + cmd = ["perl", "-MTest::LeakTrace"] + + # Handle Boolean Switches + if warnings: + cmd.append("-w") + if all_warnings: + cmd.append("-W") + if disable_warnings: + cmd.append("-X") + if taint_check: + cmd.append("-T") + if taint_warnings: + cmd.append("-t") + if syntax_check_only: + cmd.append("-c") + if autosplit: + cmd.append("-a") + if loop_n: + cmd.append("-n") + if loop_p: + cmd.append("-p") + if line_ending_processing: + cmd.append("-l") + if switch_parsing: + cmd.append("-s") + if use_path_env: + cmd.append("-S") + if unsafe_operations: + cmd.append("-U") + + # Handle Optional String/Value Parameters + if record_separator is not None: + cmd.append(f"-0{record_separator}") + + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + + if debug_flags is not None: + cmd.append(f"-D{debug_flags}") + + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + + if inplace_extension is not None: + cmd.append(f"-i{inplace_extension}") + + # Handle Include Directories (-I) + if include_dirs: + for directory in include_dirs: + cmd.append(f"-I{directory}") + + # Handle Code Execution (-e or -E) + # Note: Perl allows multiple -e, but for simplicity we handle one primary snippet + if code: + cmd.extend(["-e", code]) + elif code_with_features: + cmd.extend(["-E", code_with_features]) + + # Handle Script Path + if script_path: + path_obj = Path(script_path) + if not path_obj.exists(): + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": f"Error: Script file not found at {script_path}", + "output_files": [] + } + cmd.append(str(path_obj)) + + # Handle Script Arguments + if script_args: + cmd.extend(script_args) + + # Validation: Must provide either code or a script path unless just checking version/config + if not code and not code_with_features and not script_path: + # If no execution target is provided, we default to showing version to ensure tool is working + cmd.append("-v") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "output_files": [] + } + except Exception as e: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": str(e), + "output_files": [] + } + +@mcp.tool() +def perl_leaktrace_version(): + """ + Returns the version information for the Perl interpreter and checks if Test::LeakTrace is available. + """ + cmd = ["perl", "-MTest::LeakTrace", "-e", "print \"Test::LeakTrace version: $Test::LeakTrace::VERSION\\n\";", "-v"] + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to retrieve version. Ensure perl-test-leaktrace is installed.", + "output_files": [] + } + +@mcp.tool() +def perl_leaktrace_check_syntax( + script_path: str, + include_dirs: Optional[List[str]] = None +): + """ + Performs a syntax check on a Perl script while ensuring Test::LeakTrace is available. + + Args: + script_path: Path to the Perl script to check. + include_dirs: Optional list of directories to add to @INC. + """ + path_obj = Path(script_path) + if not path_obj.exists(): + return {"error": f"File {script_path} not found."} + + cmd = ["perl", "-MTest::LeakTrace", "-c", str(path_obj)] + + if include_dirs: + for d in include_dirs: + cmd.insert(2, f"-I{d}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "Syntax OK" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "status": "Syntax Check Failed" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/app/perl-test-leaktrace_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/app/perl-test-leaktrace_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..805004a16d59fe2c12baba69863bffb6a32fc145 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/app/perl-test-leaktrace_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/app/perl-test-leaktrace_server.py') +SERVER_NAME = 'biosci_perl_test_leaktrace' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2784b1f625ae768fdaaf19999fc7aa4c6fb63ade --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-test-leaktrace: + build: . + image: mcp-perl-test-leaktrace:latest + container_name: mcp-perl-test-leaktrace + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-test-leaktrace + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4f0b6e7803dc94e4262fe44b0e1265249d442681 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-test-leaktrace + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-leaktrace/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..35a3c41d86cdd718ec759d9bd6c70b97674da217 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-test-more via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-test-more -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-test-more_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-test-more_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-test-more_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/app/perl-test-more_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/app/perl-test-more_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8fa45993481bfb807d2a451df4e0429244a2206c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/app/perl-test-more_server.py @@ -0,0 +1,306 @@ +from typing import Optional, List +import subprocess +from pathlib import Path + +@mcp.tool() +def perl_execute_script( + script_path: str, + arguments: Optional[List[str]] = None, + include_dirs: Optional[List[str]] = None, + modules: Optional[List[str]] = None, + warning_level: str = "standard", + taint_mode: str = "none", + unicode_features: Optional[str] = None, + record_separator: Optional[str] = None, + line_ending_processing: bool = False, + inplace_extension: Optional[str] = None, + path_search: bool = False, + no_site_customize: bool = False, +): + """ + Execute a Perl script or test file (e.g., .pl or .t). + This is the primary way to run tests using the Test::More library. + + Args: + script_path: Path to the Perl script or test file. + arguments: List of arguments to pass to the script. + include_dirs: Directories to add to @INC (Perl's include path). Corresponds to -I. + modules: List of modules to load before execution. Corresponds to -M. + warning_level: Warning level to use. Options: 'none' (-X), 'standard' (-w), 'all' (-W). + taint_mode: Taint checking mode. Options: 'none', 'warnings' (-t), 'check' (-T). + unicode_features: Enable Unicode features. Corresponds to -C. + record_separator: Specify record separator. Corresponds to -0. + line_ending_processing: Enable line ending processing. Corresponds to -l. + inplace_extension: Edit files in place, optionally providing a backup extension. Corresponds to -i. + path_search: Look for programfile using PATH environment variable. Corresponds to -S. + no_site_customize: Don't do $sitelib/sitecustomize.pl at startup. Corresponds to -f. + """ + cmd = ["perl"] + + # Handle warning levels + if warning_level == "none": + cmd.append("-X") + elif warning_level == "all": + cmd.append("-W") + else: + cmd.append("-w") + + # Handle taint mode + if taint_mode == "warnings": + cmd.append("-t") + elif taint_mode == "check": + cmd.append("-T") + + # Handle include directories + if include_dirs: + for d in include_dirs: + cmd.append(f"-I{d}") + + # Handle modules + if modules: + for m in modules: + cmd.append(f"-M{m}") + + # Handle other flags + if unicode_features: + cmd.append(f"-C{unicode_features}") + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if line_ending_processing: + cmd.append("-l") + if inplace_extension is not None: + cmd.append(f"-i{inplace_extension}") + if path_search: + cmd.append("-S") + if no_site_customize: + cmd.append("-f") + + # Validate script path + path_obj = Path(script_path) + if not path_search and not path_obj.exists(): + return {"error": f"Script file not found: {script_path}"} + + cmd.append(script_path) + + # Add script arguments + if arguments: + cmd.extend(arguments) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def perl_execute_inline( + code: str, + use_extended_features: bool = True, + loop_mode: str = "none", + autosplit: bool = False, + split_pattern: Optional[str] = None, + include_dirs: Optional[List[str]] = None, + modules: Optional[List[str]] = None, + warning_level: str = "standard", +): + """ + Execute a one-line Perl program. + + Args: + code: The Perl code to execute. + use_extended_features: Use -E (enables all optional features) instead of -e. + loop_mode: Loop behavior. 'none', 'n' (while(<>)), or 'p' (while(<>) { print }). + autosplit: Enable autosplit mode (-a) with -n or -p. + split_pattern: Pattern for autosplit (-F). + include_dirs: Directories to add to @INC. + modules: Modules to load before execution. + warning_level: Warning level ('none', 'standard', 'all'). + """ + cmd = ["perl"] + + if warning_level == "none": + cmd.append("-X") + elif warning_level == "all": + cmd.append("-W") + else: + cmd.append("-w") + + if include_dirs: + for d in include_dirs: + cmd.append(f"-I{d}") + + if modules: + for m in modules: + cmd.append(f"-M{m}") + + if loop_mode == "n": + cmd.append("-n") + elif loop_mode == "p": + cmd.append("-p") + + if autosplit: + cmd.append("-a") + if split_pattern: + cmd.append(f"-F{split_pattern}") + + if use_extended_features: + cmd.extend(["-E", code]) + else: + cmd.extend(["-e", code]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def perl_check_syntax( + script_path: str, + include_dirs: Optional[List[str]] = None, + modules: Optional[List[str]] = None, +): + """ + Check the syntax of a Perl script without executing it (runs BEGIN and CHECK blocks). + + Args: + script_path: Path to the Perl script. + include_dirs: Directories to add to @INC. + modules: Modules to load before checking. + """ + path_obj = Path(script_path) + if not path_obj.exists(): + return {"error": f"File not found: {script_path}"} + + cmd = ["perl", "-c"] + + if include_dirs: + for d in include_dirs: + cmd.append(f"-I{d}") + + if modules: + for m in modules: + cmd.append(f"-M{m}") + + cmd.append(script_path) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "syntax_ok" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Syntax check failed", + "status": "syntax_error" + } + +@mcp.tool() +def perl_get_info( + config_variable: Optional[str] = None, + show_all_config: bool = False, +): + """ + Get Perl version and configuration information. + + Args: + config_variable: Print a single Config.pm variable. Corresponds to -V:variable. + show_all_config: Print configuration summary. Corresponds to -V. + """ + if config_variable: + cmd = ["perl", f"-V:{config_variable}"] + elif show_all_config: + cmd = ["perl", "-V"] + else: + cmd = ["perl", "-v"] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stderr": e.stderr + } + +@mcp.tool() +def perl_debug_script( + script_path: str, + debugger: Optional[str] = None, + debug_flags: Optional[str] = None, +): + """ + Run a Perl script under the debugger or with specific debugging flags. + + Args: + script_path: Path to the Perl script. + debugger: Run program under debugger. Corresponds to -d[:debugger]. + debug_flags: Set debugging flags (bit mask or alphabets). Corresponds to -D. + """ + path_obj = Path(script_path) + if not path_obj.exists(): + return {"error": f"File not found: {script_path}"} + + cmd = ["perl"] + + if debugger: + cmd.append(f"-d:{debugger}") + else: + cmd.append("-d") + + if debug_flags: + cmd.append(f"-D{debug_flags}") + + cmd.append(script_path) + + try: + # Debugging often requires interactive input, but in this context we capture output + result = subprocess.run(cmd, capture_output=True, text=True, timeout=30) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "note": "Debugger may have timed out if it expected interactive input." + } + except subprocess.TimeoutExpired: + return {"error": "Debugger execution timed out (likely waiting for interactive input)."} + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/app/perl-test-more_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/app/perl-test-more_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..25e7b692b4bb402b066146c5e92c3db6461da199 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/app/perl-test-more_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/app/perl-test-more_server.py') +SERVER_NAME = 'biosci_perl_test_more' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3aae9890f63d0cacde29a030a9042c594dcf6920 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-test-more: + build: . + image: mcp-perl-test-more:latest + container_name: mcp-perl-test-more + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-test-more + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..257002bb663653b0be3212b5794177f727ddbf34 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-test-more + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-more/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-most/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-most/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-most/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f8ed908e8e26d6d2f3baee392a26ded2afbafead --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-test-requiresinternet via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-test-requiresinternet -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-test-requiresinternet_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-test-requiresinternet_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-test-requiresinternet_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/app/perl-test-requiresinternet_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/app/perl-test-requiresinternet_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6e57b7a5b7d35e9f8ceaf454f1643c6cb9bddce4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/app/perl-test-requiresinternet_server.py @@ -0,0 +1,113 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, Any, List + +@mcp.tool() +def check_internet_connectivity() -> Dict[str, Any]: + """ + Checks for internet connectivity using the Perl Test::RequiresInternet module. + + This tool executes a small, temporary Perl script that utilizes the + Test::RequiresInternet module to determine if network connectivity is available. + The module is primarily designed for Perl testing frameworks (like Test::More) + to skip tests that require internet if a connection is not present or if the + NO_NETWORK_TESTING environment variable is set. + + The tool interprets a successful (non-skipped) test as an indication of + internet availability, and a skipped test as an indication of unavailability + (either no connection or NO_NETWORK_TESTING is active). + + Returns: + Dict[str, Any]: A dictionary containing: + - "command_executed" (str): The command executed. + - "stdout" (str): Standard output from the command. + - "stderr" (str): Standard error from the command. + - "internet_available" (bool): True if internet connectivity is detected, False otherwise. + - "output_files" (List[str]): List of any output files generated (empty in this case). + """ + # Perl script content that uses Test::RequiresInternet within a Test::More context. + # If internet is not available, Test::RequiresInternet will cause the test to be skipped. + # If NO_NETWORK_TESTING is set, it will also cause the test to be skipped. + # We interpret any skip as "internet not available for testing purposes". + perl_script_content = """ +use strict; +use warnings; +use Test::More; +use Test::RequiresInternet; + +plan tests => 1; + +# Test::RequiresInternet::requires_internet() is implicitly called by Test::More +# when a test is declared within its scope and Test::RequiresInternet is loaded. +# If internet is not available, or NO_NETWORK_TESTING is set, +# Test::RequiresInternet will cause this test to be skipped. +ok(1, "Internet connectivity check"); +""" + + tmp_script_path: Optional[Path] = None + try: + # Create a temporary Perl script file + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".pl") as tmp_script: + tmp_script.write(perl_script_content) + tmp_script_path = Path(tmp_script.name) + + command = ["perl", str(tmp_script_path)] + + # Execute the Perl script + # We use check=False because a skipped test (due to no internet) might + # result in a non-zero exit code, which we want to parse, not treat as an error. + process = subprocess.run( + command, + capture_output=True, + text=True, + check=False + ) + stdout = process.stdout + stderr = process.stderr + + # Determine internet availability by parsing Test::More output. + # A successful test without "# SKIP" indicates internet is available. + # Any output containing "# SKIP" indicates the test was skipped (no internet or NO_NETWORK_TESTING). + internet_available = False + if "ok 1 - Internet connectivity check" in stdout and "# SKIP" not in stdout: + internet_available = True + else: + internet_available = False + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "internet_available": internet_available, + "output_files": [], + } + + except FileNotFoundError: + return { + "command_executed": " ".join(command) if 'command' in locals() else "perl ", + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "internet_available": False, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command) if 'command' in locals() else "perl ", + "stdout": e.stdout, + "stderr": e.stderr, + "internet_available": False, + "output_files": [], + } + except Exception as e: + return { + "command_executed": " ".join(command) if 'command' in locals() else "perl ", + "stdout": "", + "stderr": f"An unexpected error occurred: {str(e)}", + "internet_available": False, + "output_files": [], + } + finally: + # Clean up the temporary script file + if tmp_script_path and tmp_script_path.exists(): + tmp_script_path.unlink(missing_ok=True) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/app/perl-test-requiresinternet_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/app/perl-test-requiresinternet_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3df75bf7171ce98850fd4b0bf4d5e172df75cd33 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/app/perl-test-requiresinternet_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/app/perl-test-requiresinternet_server.py') +SERVER_NAME = 'biosci_perl_test_requiresinternet' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..050601fd43ea19288648874747c1889c67be70ad --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-test-requiresinternet: + build: . + image: mcp-perl-test-requiresinternet:latest + container_name: mcp-perl-test-requiresinternet + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-test-requiresinternet + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4e48913bff3444291c0d3bb4f753a7a7229fda6a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-test-requiresinternet + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-requiresinternet/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a73593138358727164adccda839539106af4531e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-test-warn via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-test-warn -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-test-warn_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-test-warn_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-test-warn_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/app/perl-test-warn_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/app/perl-test-warn_server.py new file mode 100644 index 0000000000000000000000000000000000000000..62f25eecc4b3cdb12defa7c4e0b0a8b1a0b0406c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/app/perl-test-warn_server.py @@ -0,0 +1,213 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +@mcp.tool() +def perl_interpreter( + program_file: Optional[str] = None, + arguments: List[str] = [], + one_liner: Optional[str] = None, + use_all_features: bool = False, + check_syntax_only: bool = False, + modules: List[str] = ["Test::Warn"], + include_directories: List[str] = [], + warning_mode: str = "useful", + taint_checks: bool = False, + taint_warnings: bool = False, + autosplit_mode: bool = False, + split_pattern: Optional[str] = None, + inplace_edit_extension: Optional[str] = None, + loop_assume_while: bool = False, + loop_assume_while_print: bool = False, + unicode_features: Optional[str] = None, + record_separator: Optional[str] = None, + line_ending_processing: Optional[str] = None, + unsafe_operations: bool = False, + ignore_text_before_perl_line: Optional[str] = None, +): + """ + Execute Perl scripts or commands, with built-in support for the Test::Warn module. + This tool provides access to the Perl interpreter and its various switches. + + Args: + program_file: Path to the Perl script to execute. + arguments: Arguments to pass to the Perl script. + one_liner: One line of program to execute (maps to -e). + use_all_features: Like one_liner, but enables all optional features (maps to -E). + check_syntax_only: Check syntax only without executing (maps to -c). + modules: List of modules to execute 'use module' before the program (maps to -M). Defaults to ['Test::Warn']. + include_directories: List of directories to add to @INC (maps to -I). + warning_mode: Warning level: 'useful' (-w), 'all' (-W), 'none' (-X), or 'default'. + taint_checks: Enable tainting checks (maps to -T). + taint_warnings: Enable tainting warnings (maps to -t). + autosplit_mode: Enable autosplit mode with -n or -p (maps to -a). + split_pattern: Pattern for autosplit mode (maps to -F). + inplace_edit_extension: Edit files in place, optionally providing a backup extension (maps to -i). + loop_assume_while: Assume 'while (<>) { ... }' loop around program (maps to -n). + loop_assume_while_print: Assume loop like -n but print line also (maps to -p). + unicode_features: Enable listed Unicode features (maps to -C). + record_separator: Specify record separator (maps to -0). + line_ending_processing: Enable line ending processing (maps to -l). + unsafe_operations: Allow unsafe operations (maps to -U). + ignore_text_before_perl_line: Ignore text before #!perl line, optionally cd to directory (maps to -x). + """ + cmd = ["perl"] + + # Handle switches + if record_separator is not None: + cmd.append(f"-0{record_separator}") + + if autosplit_mode: + cmd.append("-a") + + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + + if check_syntax_only: + cmd.append("-c") + + if one_liner: + cmd.append("-e") + cmd.append(one_liner) + elif use_all_features: + # Note: If both are provided, -E usually takes precedence or they are used together. + # Here we treat them as mutually exclusive for the primary code input. + cmd.append("-E") + cmd.append(use_all_features if isinstance(use_all_features, str) else "") + + if split_pattern: + cmd.append(f"-F{split_pattern}") + + if inplace_edit_extension is not None: + cmd.append(f"-i{inplace_edit_extension}") + + for directory in include_directories: + cmd.append(f"-I{directory}") + + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + + for module in modules: + cmd.append(f"-M{module}") + + if loop_assume_while: + cmd.append("-n") + + if loop_assume_while_print: + cmd.append("-p") + + if taint_warnings: + cmd.append("-t") + + if taint_checks: + cmd.append("-T") + + if unsafe_operations: + cmd.append("-U") + + if warning_mode == "useful": + cmd.append("-w") + elif warning_mode == "all": + cmd.append("-W") + elif warning_mode == "none": + cmd.append("-X") + + if ignore_text_before_perl_line is not None: + cmd.append(f"-x{ignore_text_before_perl_line}") + + # Handle program file and arguments + if program_file: + prog_path = Path(program_file) + if not prog_path.exists(): + return {"error": f"Program file not found: {program_file}"} + cmd.append(str(prog_path)) + + if arguments: + cmd.extend(arguments) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def perl_version_info( + config_variable: Optional[str] = None +): + """ + Print the Perl version, patchlevel, license, or configuration summary. + + Args: + config_variable: If provided, print the value of a specific Config.pm variable (maps to -V:variable). + If None, prints version and configuration summary. + """ + if config_variable: + cmd = ["perl", f"-V:{config_variable}"] + else: + cmd = ["perl", "-V"] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def perl_test_warn_check( + test_code: str +): + """ + A specialized tool to run a snippet of Perl code specifically using Test::Warn. + This is useful for verifying if certain code blocks emit expected warnings. + + Args: + test_code: The Perl code snippet to test. It should ideally use Test::More and Test::Warn functions. + Example: 'use Test::More; use Test::Warn; warning_is { warn "foo" } "foo", "got foo warning"; done_testing();' + """ + # Ensure the code includes necessary modules if not present + if "use Test::Warn" not in test_code: + test_code = "use Test::Warn; " + test_code + if "use Test::More" not in test_code: + test_code = "use Test::More; " + test_code + if "done_testing" not in test_code: + test_code = test_code + "; done_testing();" + + cmd = ["perl", "-e", test_code] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Test failed or syntax error occurred.", + "status": "error" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/app/perl-test-warn_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/app/perl-test-warn_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2e406fa97f7348a28bb4bc7329a7b25ce81828ca --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/app/perl-test-warn_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/app/perl-test-warn_server.py') +SERVER_NAME = 'biosci_perl_test_warn' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f3db06bfdc2e1b9327248145ab86b4aa00720992 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-test-warn: + build: . + image: mcp-perl-test-warn:latest + container_name: mcp-perl-test-warn + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-test-warn + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e9bf0b1afeb3a81582154c969aa1a1898395041d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-test-warn + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a9d0aa991eda811b0b47da9b8b4fbfafd809eaa0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-test via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-test -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-test_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-test_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-test_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/app/perl-test_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/app/perl-test_server.py new file mode 100644 index 0000000000000000000000000000000000000000..315cc6b3efe834d0fa615d0b28509dbe20a20bbf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/app/perl-test_server.py @@ -0,0 +1,155 @@ +import subprocess +from pathlib import Path +from typing import Optional, Dict + +# Assuming mcp is imported from the Model Context Protocol library +# e.g., from mcp import mcp + +@mcp.tool() +def perl_test( + input_file: Path, + output_file: Path, + threshold: float = 0.05, + iterations: int = 1000, + verbose: bool = False, + seed: Optional[int] = None, +) -> Dict: + """ + Runs a hypothetical 'perl-test' analysis. + + This tool simulates running a Perl-based bioinformatics test, taking an input file + and generating an output file based on specified parameters. + + Args: + input_file: Path to the input data file. + output_file: Path to write the output results. + threshold: A significance threshold for the test. Defaults to 0.05. + iterations: Number of iterations or permutations to run. Defaults to 1000. + verbose: If True, enables verbose logging. Defaults to False. + seed: An optional integer seed for reproducibility. Defaults to None. + + Returns: + A dictionary containing the execution details and output file path. + """ + # --- Input Validation --- + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + if not (0.0 <= threshold <= 1.0): + raise ValueError("Threshold must be between 0.0 and 1.0.") + + if iterations <= 0: + raise ValueError("Iterations must be a positive integer.") + + if seed is not None and seed < 0: + raise ValueError("Seed must be a non-negative integer.") + + # Ensure the output directory exists + output_file.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "perl-test", + "--input", str(input_file), + "--output", str(output_file), + "--threshold", str(threshold), + "--iterations", str(iterations), + ] + + if verbose: + cmd.append("--verbose") + + if seed is not None: + cmd.extend(["--seed", str(seed)]) + + command_executed = " ".join(cmd) + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"results": str(output_file)}, + } + except FileNotFoundError: + raise RuntimeError( + "The 'perl-test' command was not found. Please ensure it is installed and in your system's PATH." + ) + except subprocess.CalledProcessError as e: + # Return a structured error if the tool fails + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"perl-test failed with exit code {e.returncode}", + "output_files": {}, + } + + +@mcp.tool() +def perl_test_validate( + input_file: Path, + format: str = "fasta", +) -> Dict: + """ + Validates the format of an input file using the 'perl-test validate' subcommand. + + This tool checks if the input file conforms to a specified format like 'fasta' or 'fastq'. + + Args: + input_file: The file to validate. + format: The expected format (e.g., 'fasta', 'fastq', 'gff'). Defaults to 'fasta'. + + Returns: + A dictionary containing the execution details of the validation command. + """ + # --- Input Validation --- + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + allowed_formats = ["fasta", "fastq", "gff", "vcf", "bed"] + if format.lower() not in allowed_formats: + raise ValueError( + f"Invalid format '{format}'. Allowed formats are: {', '.join(allowed_formats)}" + ) + + # --- Command Construction --- + cmd = [ + "perl-test", + "validate", + "--input", str(input_file), + "--format", format, + ] + command_executed = " ".join(cmd) + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + raise RuntimeError( + "The 'perl-test' command was not found. Please ensure it is installed and in your system's PATH." + ) + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"perl-test validate failed with exit code {e.returncode}", + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/app/perl-test_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/app/perl-test_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c8b213465efa58c75246a573d339ed1c38102f94 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/app/perl-test_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/app/perl-test_server.py') +SERVER_NAME = 'biosci_perl_test' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..98f5ce3b1a2bf34ad7a408d5c89951c77cf75671 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-test: + build: . + image: mcp-perl-test:latest + container_name: mcp-perl-test + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-test + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5b7b78471c2592dfcf9002cc6541fcbaa53dcc42 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-test + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..82428e4f700a99913cc4818ef76a34011648e6bd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-test2-suite via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-test2-suite -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-test2-suite_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-test2-suite_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-test2-suite_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/app/perl-test2-suite_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/app/perl-test2-suite_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f89eafa1ff87744767b0ad7e95ba4f17bd1ae3ba --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/app/perl-test2-suite_server.py @@ -0,0 +1,264 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +@mcp.tool() +def perl_test2_run_test( + test_file: str, + include_dirs: Optional[List[str]] = None, + modules: Optional[List[str]] = None, + enable_warnings: bool = True, + taint_check: bool = False, + unicode_features: Optional[str] = None, + autosplit_mode: bool = False, + line_ending_processing: bool = False, +) -> Dict[str, Any]: + """ + Executes a Perl test script (typically .t or .pl) using the Perl interpreter, + facilitating the use of the Test2::Suite framework. + + Args: + test_file: Path to the Perl test file to execute. + include_dirs: List of directories to add to @INC (Perl's library search path). Corresponds to -I. + modules: List of modules to load before executing the script. Corresponds to -M. + enable_warnings: If True, enables many useful warnings (-w). + taint_check: If True, enables taint checks (-T). + unicode_features: Enables listed Unicode features (e.g., 'S', 'D'). Corresponds to -C. + autosplit_mode: If True, enables autosplit mode with -n or -p (-a). + line_ending_processing: If True, enables line ending processing (-l). + """ + file_path = Path(test_file) + if not file_path.exists(): + return {"error": f"Test file not found: {test_file}"} + + cmd = ["perl"] + + if enable_warnings: + cmd.append("-w") + + if taint_check: + cmd.append("-T") + + if unicode_features: + cmd.append(f"-C{unicode_features}") + + if autosplit_mode: + cmd.append("-a") + + if line_ending_processing: + cmd.append("-l") + + if include_dirs: + for d in include_dirs: + cmd.extend(["-I", d]) + + if modules: + for m in modules: + cmd.extend(["-M", m]) + + cmd.append(str(file_path)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=False) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "return_code": result.returncode, + "success": result.returncode == 0 + } + except Exception as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "success": False + } + +@mcp.tool() +def perl_test2_execute_inline( + code: str, + use_test2_v0: bool = True, + include_dirs: Optional[List[str]] = None, + enable_warnings: bool = True, + all_features: bool = False, +) -> Dict[str, Any]: + """ + Executes a one-line Perl program or snippet, useful for quick tests using Test2::Suite. + + Args: + code: The Perl code to execute. + use_test2_v0: If True, automatically prepends 'use Test2::V0;' to the code. + include_dirs: List of directories to add to @INC. + enable_warnings: If True, enables warnings (-w). + all_features: If True, uses -E instead of -e to enable all optional features. + """ + cmd = ["perl"] + + if enable_warnings: + cmd.append("-w") + + if include_dirs: + for d in include_dirs: + cmd.extend(["-I", d]) + + # Prepend Test2::V0 if requested + full_code = f"use Test2::V0; {code}" if use_test2_v0 else code + + flag = "-E" if all_features else "-e" + cmd.extend([flag, full_code]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=False) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "return_code": result.returncode, + "success": result.returncode == 0 + } + except Exception as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "success": False + } + +@mcp.tool() +def perl_test2_check_syntax( + file_path: str, + include_dirs: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Checks the syntax of a Perl script without executing it. + + Args: + file_path: Path to the Perl file to check. + include_dirs: List of directories to add to @INC. + """ + path = Path(file_path) + if not path.exists(): + return {"error": f"File not found: {file_path}"} + + cmd = ["perl", "-c"] + + if include_dirs: + for d in include_dirs: + cmd.extend(["-I", d]) + + cmd.append(str(path)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=False) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "is_valid": result.returncode == 0 + } + except Exception as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "is_valid": False + } + +@mcp.tool() +def perl_test2_get_config( + variable: Optional[str] = None +) -> Dict[str, Any]: + """ + Prints the Perl configuration summary or a specific configuration variable. + Equivalent to perl -V. + + Args: + variable: Optional specific configuration variable to query (e.g., 'installsitelib'). + """ + cmd = ["perl", "-V"] + if variable: + cmd.append(f":{variable}") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to retrieve configuration" + } + +@mcp.tool() +def perl_test2_version_info() -> Dict[str, Any]: + """ + Returns the version, patchlevel, and license information for the Perl interpreter. + Equivalent to perl -v. + """ + cmd = ["perl", "-v"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e) + } + +@mcp.tool() +def perl_test2_run_with_debugger( + test_file: str, + debugger_module: Optional[str] = None, + include_dirs: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Runs a Perl script under the debugger. + + Args: + test_file: Path to the Perl script. + debugger_module: Optional debugger module to use (e.g., 'Devel::NYTProf'). Corresponds to -d:module. + include_dirs: List of directories to add to @INC. + """ + path = Path(test_file) + if not path.exists(): + return {"error": f"File not found: {test_file}"} + + debug_flag = "-d" + if debugger_module: + debug_flag = f"-d:{debugger_module}" + + cmd = ["perl", debug_flag] + + if include_dirs: + for d in include_dirs: + cmd.extend(["-I", d]) + + cmd.append(str(path)) + + try: + # Debugging often requires interactive input, but in this context, + # we capture the output. Note: This might hang if the debugger waits for input. + result = subprocess.run(cmd, capture_output=True, text=True, timeout=30, check=False) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "return_code": result.returncode + } + except subprocess.TimeoutExpired: + return { + "command_executed": " ".join(cmd), + "error": "Process timed out (debugger might be waiting for input)" + } + except Exception as e: + return { + "command_executed": " ".join(cmd), + "error": str(e) + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/app/perl-test2-suite_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/app/perl-test2-suite_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0e0be10419a1f76a097d7570f5e29708b722a53b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/app/perl-test2-suite_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/app/perl-test2-suite_server.py') +SERVER_NAME = 'biosci_perl_test2_suite' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..084c6d4aad0ab3ec7a4e632aaec9b1f5c11694cc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-test2-suite: + build: . + image: mcp-perl-test2-suite:latest + container_name: mcp-perl-test2-suite + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-test2-suite + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..418643eb5f136a8cf9d2d47c60ffafe19efb4500 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-test2-suite + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test2-suite/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..badafafcd59e893060a6c37f8d5848883e6d0208 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-text-csv via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-text-csv -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-text-csv_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-text-csv_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-text-csv_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/app/perl-text-csv_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/app/perl-text-csv_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d1dabebfc106bc09f66feed050aa4c1eed4de790 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/app/perl-text-csv_server.py @@ -0,0 +1,438 @@ +import subprocess +import json +import tempfile +from pathlib import Path +from typing import List, Dict, Union, Optional, Literal, Any + +def _run_perl_command( + script_content: str, + args: Optional[List[str]] = None, + stdin_data: Optional[str] = None, + env: Optional[Dict[str, str]] = None, +) -> Dict[str, Any]: + """ + Helper function to execute a Perl script safely. + """ + command = ["perl"] + + # Create a temporary file for the Perl script + script_path: Optional[Path] = None + try: + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".pl") as tmp_script_file: + tmp_script_file.write(script_content) + script_path = Path(tmp_script_file.name) + + command.append(str(script_path)) + if args: + command.extend(args) + + process = subprocess.run( + command, + input=stdin_data, + text=True, + capture_output=True, + check=True, + env=env, + encoding="utf-8" + ) + + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "returncode": process.returncode + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + } + finally: + if script_path and script_path.exists(): + script_path.unlink(missing_ok=True) + +@mcp.tool() +def perl_execute( + program_file: Optional[Path] = None, + program_string: Optional[str] = None, + arguments: Optional[List[str]] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + enable_all_features: bool = False, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + modules_to_use: Optional[List[str]] = None, + modules_to_no_use: Optional[List[str]] = None, + assume_loop_n: bool = False, + assume_loop_p: bool = False, + rudimentary_parsing_switches: bool = False, + look_for_program_in_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_perl: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> Dict[str, Any]: + """ + Executes a Perl script or one-liner with various Perl interpreter options. + """ + if program_file and program_string: + raise ValueError("Cannot specify both 'program_file' and 'program_string'.") + + perl_args = [] + if record_separator is not None: perl_args.append(f"-0{record_separator}") + if autosplit: perl_args.append("-a") + if unicode_features: perl_args.append(f"-C{unicode_features}") + if check_syntax_only: perl_args.append("-c") + if debugger: perl_args.append(f"-d:{debugger}") + if debugging_flags: perl_args.append(f"-D{debugging_flags}") + if program_string: + perl_args.append("-E" if enable_all_features else "-e") + perl_args.append(program_string) + if no_sitecustomize: perl_args.append("-f") + if split_pattern: perl_args.append(f"-F{split_pattern}") + if edit_in_place_extension: perl_args.append(f"-i{edit_in_place_extension}") + if include_directories: + for d in include_directories: perl_args.append(f"-I{d}") + if line_ending_processing: perl_args.append(f"-l{line_ending_processing}") + if modules_to_use: + for m in modules_to_use: perl_args.append(f"-M{m}") + if modules_to_no_use: + for m in modules_to_no_use: perl_args.append(f"-M-{m}") + if assume_loop_n: perl_args.append("-n") + if assume_loop_p: perl_args.append("-p") + if rudimentary_parsing_switches: perl_args.append("-s") + if look_for_program_in_path: perl_args.append("-S") + if tainting_warnings: perl_args.append("-t") + if tainting_checks: perl_args.append("-T") + if dump_core: perl_args.append("-u") + if allow_unsafe_operations: perl_args.append("-U") + if print_version: perl_args.append("-v") + if print_config_summary is not None: + perl_args.append(f"-V:{print_config_summary}" if print_config_summary else "-V") + if enable_warnings: perl_args.append("-w") + if enable_all_warnings: perl_args.append("-W") + if ignore_text_before_perl: perl_args.append(f"-x{ignore_text_before_perl}") + if disable_all_warnings: perl_args.append("-X") + + cmd = ["perl"] + perl_args + if program_file: + if not program_file.is_file(): + raise FileNotFoundError(f"Program file not found: {program_file}") + cmd.append(str(program_file)) + if arguments: + cmd.extend(arguments) + + try: + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + return {"command_executed": " ".join(cmd), "stdout": process.stdout, "stderr": process.stderr} + except subprocess.CalledProcessError as e: + return {"command_executed": " ".join(cmd), "stdout": e.stdout, "stderr": e.stderr, "error": str(e)} + +@mcp.tool() +def text_csv_read( + input_csv: Path, + return_type: Literal["aoa", "aoh"] = "aoa", + encoding: str = "utf8", + sep_char: str = ",", + quote_char: str = '"', + escape_char: str = '"', + binary: bool = True, + strict: bool = False, + allow_whitespace: bool = False, + headers: Optional[Union[Literal["auto"], List[str]]] = None, +) -> Dict[str, Any]: + """ + Reads a CSV file using Text::CSV and returns its content as JSON. + """ + if not input_csv.is_file(): + raise FileNotFoundError(f"Input file not found: {input_csv}") + + # Prepare attributes for Text::CSV + csv_opts = { + "binary": 1 if binary else 0, + "strict": 1 if strict else 0, + "sep_char": sep_char, + "quote_char": quote_char, + "escape_char": escape_char, + "allow_whitespace": 1 if allow_whitespace else 0, + } + + perl_script = """ +use strict; +use warnings; +use Text::CSV; +use JSON::PP; + +my $file = $ARGV[0]; +my $opts_json = $ENV{CSV_OPTS}; +my $headers_json = $ENV{CSV_HEADERS}; + +my $json_parser = JSON::PP->new->utf8; +my $opts = $json_parser->decode($opts_json); +my $csv = Text::CSV->new($opts) or die Text::CSV->error_diag(); + +open my $fh, "<:encoding($ENV{CSV_ENC})", $file or die "Could not open $file: $!"; + +my @data; +if ($ENV{CSV_RETURN_TYPE} eq 'aoh') { + my $h_ref; + if ($headers_json eq '"auto"') { + $h_ref = $csv->header($fh); + } elsif ($headers_json ne 'null') { + $h_ref = $json_parser->decode($headers_json); + $csv->column_names($h_ref); + } + while (my $row = $csv->getline_hr($fh)) { + push @data, $row; + } +} else { + while (my $row = $csv->getline($fh)) { + push @data, $row; + } +} +close $fh; +print $json_parser->encode(\\@data); +""" + env = { + "CSV_OPTS": json.dumps(csv_opts), + "CSV_ENC": encoding, + "CSV_RETURN_TYPE": return_type, + "CSV_HEADERS": json.dumps(headers), + "PATH": str(Path(subprocess.check_output(["which", "perl"]).decode().strip()).parent) + } + + result = _run_perl_command(perl_script, args=[str(input_csv.resolve())], env=env) + if "error" not in result: + try: + result["data"] = json.loads(result["stdout"]) + except json.JSONDecodeError: + result["error"] = "Failed to parse Perl output as JSON" + return result + +@mcp.tool() +def text_csv_write( + data: Union[List[List[Any]], List[Dict[str, Any]]], + output_csv: Path, + encoding: str = "utf8", + sep_char: str = ",", + quote_char: str = '"', + escape_char: str = '"', + binary: bool = True, + eol: str = "\n", + headers: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Writes structured data (AoA or AoH) to a CSV file. + """ + csv_opts = { + "binary": 1 if binary else 0, + "sep_char": sep_char, + "quote_char": quote_char, + "escape_char": escape_char, + "eol": eol, + } + + perl_script = """ +use strict; +use warnings; +use Text::CSV; +use JSON::PP; + +my $file = $ARGV[0]; +my $opts = JSON::PP->new->decode($ENV{CSV_OPTS}); +my $headers = JSON::PP->new->decode($ENV{CSV_HEADERS}); +my $csv = Text::CSV->new($opts) or die Text::CSV->error_diag(); + +open my $fh, ">:encoding($ENV{CSV_ENC})", $file or die "Could not open $file: $!"; + +my $data = JSON::PP->new->utf8->decode(do { local $/; }); + +if ($headers) { + $csv->print($fh, $headers); +} + +foreach my $row (@$data) { + if (ref($row) eq 'HASH') { + # If AoH, we need column names to ensure order + die "Headers required for Array of Hashes" unless $headers; + $csv->print($fh, [ map { $row->{$_} } @$headers ]); + } else { + $csv->print($fh, $row); + } +} +close $fh; +""" + env = { + "CSV_OPTS": json.dumps(csv_opts), + "CSV_ENC": encoding, + "CSV_HEADERS": json.dumps(headers), + } + + return _run_perl_command( + perl_script, + args=[str(output_csv.resolve())], + stdin_data=json.dumps(data), + env=env + ) + +@mcp.tool() +def text_csv_convert( + input_csv: Path, + output_csv: Path, + in_sep: str = ",", + out_sep: str = "\t", + in_enc: str = "utf8", + out_enc: str = "utf8", +) -> Dict[str, Any]: + """ + Converts a CSV file to another format (e.g., CSV to TSV). + """ + if not input_csv.is_file(): + raise FileNotFoundError(f"Input file not found: {input_csv}") + + perl_script = """ +use strict; +use warnings; +use Text::CSV; + +my ($in_f, $out_f) = @ARGV; +my $csv_in = Text::CSV->new({ binary => 1, sep_char => $ENV{IN_SEP} }); +my $csv_out = Text::CSV->new({ binary => 1, sep_char => $ENV{OUT_SEP}, eol => "\\n" }); + +open my $fi, "<:encoding($ENV{IN_ENC})", $in_f or die $!; +open my $fo, ">:encoding($ENV{OUT_ENC})", $out_f or die $!; + +while (my $row = $csv_in->getline($fi)) { + $csv_out->print($fo, $row); +} +close $fi; +close $fo; +""" + env = { + "IN_SEP": in_sep, + "OUT_SEP": out_sep, + "IN_ENC": in_enc, + "OUT_ENC": out_enc + } + return _run_perl_command(perl_script, args=[str(input_csv.resolve()), str(output_csv.resolve())], env=env) + +@mcp.tool() +def text_csv_filter( + input_csv: Path, + output_csv: Path, + perl_expression: str, + sep_char: str = ",", + headers: bool = True, +) -> Dict[str, Any]: + """ + Filters CSV rows based on a Perl expression. + The row is available as an arrayref in $_. + Example expression: '$_->[0] > 100' + """ + if not input_csv.is_file(): + raise FileNotFoundError(f"Input file not found: {input_csv}") + + perl_script = f""" +use strict; +use warnings; +use Text::CSV; + +my ($in_f, $out_f) = @ARGV; +my $csv = Text::CSV->new({{ binary => 1, sep_char => $ENV{{SEP}}, eol => "\\n" }}); + +open my $fi, "<", $in_f or die $!; +open my $fo, ">", $out_f or die $!; + +if ($ENV{{HAS_HEADERS}}) {{ + my $h = $csv->getline($fi); + $csv->print($fo, $h); +}} + +while (my $_ = $csv->getline($fi)) {{ + if ({perl_expression}) {{ + $csv->print($fo, $_); + }} +}} +close $fi; +close $fo; +""" + env = {"SEP": sep_char, "HAS_HEADERS": "1" if headers else "0"} + return _run_perl_command(perl_script, args=[str(input_csv.resolve()), str(output_csv.resolve())], env=env) + +@mcp.tool() +def text_csv_info() -> Dict[str, Any]: + """ + Returns information about the installed Text::CSV module. + """ + perl_script = """ +use strict; +use warnings; +use Text::CSV; +use JSON::PP; + +my $info = { + version => $Text::CSV::VERSION, + backend => Text::CSV->backend(), + is_xs => Text::CSV->is_xs(), + is_pp => Text::CSV->is_pp(), +}; +print JSON::PP->new->encode($info); +""" + result = _run_perl_command(perl_script) + if "error" not in result: + result["data"] = json.loads(result["stdout"]) + return result + +@mcp.tool() +def text_csv_validate( + input_csv: Path, + sep_char: str = ",", + allow_loose_quotes: bool = False, +) -> Dict[str, Any]: + """ + Validates a CSV file for consistency and syntax errors. + """ + if not input_csv.is_file(): + raise FileNotFoundError(f"Input file not found: {input_csv}") + + perl_script = """ +use strict; +use warnings; +use Text::CSV; + +my $file = $ARGV[0]; +my $csv = Text::CSV->new({ + binary => 1, + sep_char => $ENV{SEP}, + allow_loose_quotes => $ENV{LOOSE} +}) or die Text::CSV->error_diag(); + +open my $fh, "<", $file or die $!; +my $line = 0; +while (not $fh->eof) { + $line++; + if (!$csv->getline($fh)) { + my ($c_err, $s_err, $pos) = $csv->error_diag(); + print "Error at line $line, pos $pos: $s_err ($c_err)\\n"; + } +} +close $fh; +""" + env = {"SEP": sep_char, "LOOSE": "1" if allow_loose_quotes else "0"} + return _run_perl_command(perl_script, args=[str(input_csv.resolve())], env=env) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/app/perl-text-csv_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/app/perl-text-csv_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..535549a5df04e7599c3a03d4b9ba9d4c3f1c907c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/app/perl-text-csv_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/app/perl-text-csv_server.py') +SERVER_NAME = 'biosci_perl_text_csv' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6a08b33e7c2bf1b5e4a1dde414b02b179d3abeee --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-text-csv: + build: . + image: mcp-perl-text-csv:latest + container_name: mcp-perl-text-csv + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-text-csv + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c3e3fa00a98cfd9438b074baa62611320f41b27f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-text-csv + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-csv/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-diff/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-diff/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-diff/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6961d86f5df5613b64f38ecd55e865d9067909cd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-text-format via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-text-format -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-text-format_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-text-format_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-text-format_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/app/perl-text-format_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/app/perl-text-format_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bec2a3a504821d08526f0687032070b38625a143 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/app/perl-text-format_server.py @@ -0,0 +1,255 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Union + +@mcp.tool() +def run_perl_script( + program_file: Optional[Path] = None, + inline_program: Optional[List[str]] = None, + inline_program_extended: Optional[List[str]] = None, + program_arguments: Optional[List[str]] = None, + record_separator_octal: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing_terminator: Optional[str] = None, + use_module: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + rudimentary_parsing_for_switches: bool = False, + look_for_programfile_in_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core_after_parsing: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary_variable: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang_cd_to_directory: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> Dict[str, Union[str, List[str], int]]: + """ + Executes a Perl script with various interpreter options. + + This tool wraps the 'perl' interpreter, allowing the execution of a Perl + script file or inline code with a comprehensive set of Perl command-line + switches. The 'perl-text-format' package is a Perl module and not a + standalone executable; this tool provides the general Perl execution + environment where such modules can be utilized within a script. + + Args: + program_file: Path to the Perl script file to execute. + Cannot be used with `inline_program` or `inline_program_extended`. + inline_program: One or more lines of Perl program code to execute directly. + Cannot be used with `program_file` or `inline_program_extended`. + Multiple `-e` switches are supported by providing a list of strings. + inline_program_extended: One or more lines of Perl program code to execute, + like `inline_program`, but enables all optional features. + Cannot be used with `program_file` or `inline_program`. + Multiple `-E` switches are supported by providing a list of strings. + program_arguments: Arguments to pass to the Perl script. These will be available + in the script via @ARGV. + record_separator_octal: Specify record separator (e.g., '0' for NUL, or an octal string). + Corresponds to Perl's `-0` switch. + autosplit: Enable autosplit mode with -n or -p (splits $_ into @F). + Corresponds to Perl's `-a` switch. + unicode_features: Enables the listed Unicode features (number or list). + Corresponds to Perl's `-C` switch. + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). + Corresponds to Perl's `-c` switch. + debugger: Run program under debugger. Provide an optional debugger name (e.g., 'GDB'). + Corresponds to Perl's `-d[:debugger]` switch. + debugging_flags: Set debugging flags (argument is a bit mask or alphabets). + Corresponds to Perl's `-D` switch. + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. + Corresponds to Perl's `-f` switch. + split_pattern: split() pattern for -a switch (e.g., '/\s+/'). + Corresponds to Perl's `-F` switch. + edit_in_place_extension: Edit <> files in place (makes backup if extension supplied). + Provide the extension (e.g., '.bak') or an empty string for no backup. + Corresponds to Perl's `-i` switch. + include_directories: Specify @INC/#include directories. Multiple -I's are supported. + Corresponds to Perl's `-I` switch. + line_ending_processing_terminator: Enable line ending processing, specifies line terminator (e.g., '0' for NUL). + Corresponds to Perl's `-l` switch. + use_module: Execute "use/no module..." before executing program. + Provide module names (e.g., 'Text::Format', 'no strict'). + Corresponds to Perl's `-[mM][-]module` switch. + loop_around_program: Assume "while (<>) { ... }" loop around program. + Corresponds to Perl's `-n` switch. + loop_and_print: Assume loop like -n but print line also, like sed. + Corresponds to Perl's `-p` switch. + rudimentary_parsing_for_switches: Enable rudimentary parsing for switches after programfile. + Corresponds to Perl's `-s` switch. + look_for_programfile_in_path: Look for programfile using PATH environment variable. + Corresponds to Perl's `-S` switch. + tainting_warnings: Enable tainting warnings. Corresponds to Perl's `-t` switch. + tainting_checks: Enable tainting checks. Corresponds to Perl's `-T` switch. + dump_core_after_parsing: Dump core after parsing program. Corresponds to Perl's `-u` switch. + allow_unsafe_operations: Allow unsafe operations. Corresponds to Perl's `-U` switch. + print_version: Print version, patchlevel and license. Corresponds to Perl's `-v` switch. + print_config_summary_variable: Print configuration summary (or a single Config.pm variable). + Corresponds to Perl's `-V[:variable]` switch. + enable_warnings: Enable many useful warnings. Corresponds to Perl's `-w` switch. + enable_all_warnings: Enable all warnings. Corresponds to Perl's `-W` switch. + ignore_text_before_shebang_cd_to_directory: Ignore text before #!perl line (optionally cd to directory). + Corresponds to Perl's `-x[directory]` switch. + disable_all_warnings: Disable all warnings. Corresponds to Perl's `-X` switch. + """ + + cmd = ["perl"] + output_files: List[str] = [] + + # Input validation for program source + program_source_count = sum([ + 1 if program_file is not None else 0, + 1 if inline_program is not None else 0, + 1 if inline_program_extended is not None else 0, + ]) + + if program_source_count > 1: + raise ValueError( + "Only one of 'program_file', 'inline_program', or 'inline_program_extended' can be specified." + ) + if program_source_count == 0 and not (print_version or print_config_summary_variable): + raise ValueError( + "Either 'program_file', 'inline_program', 'inline_program_extended' must be specified, " + "or 'print_version'/'print_config_summary_variable' must be true." + ) + + if program_file: + if not program_file.is_file(): + raise FileNotFoundError(f"Perl script file not found: {program_file}") + + # Add switches + if record_separator_octal is not None: + cmd.append(f"-0{record_separator_octal}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if debugger is not None: + cmd.append(f"-d:{debugger}" if debugger else "-d") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + cmd.append(f"-i{edit_in_place_extension}") + if include_directories: + for inc_dir in include_directories: + if not inc_dir.is_dir(): + raise NotADirectoryError(f"Include directory not found: {inc_dir}") + cmd.append(f"-I{inc_dir}") + if line_ending_processing_terminator is not None: + cmd.append(f"-l{line_ending_processing_terminator}") + if use_module: + for module_spec in use_module: + if module_spec.lower().startswith("no "): + module_name = module_spec[3:].strip() # Remove "no " prefix + if not module_name: + raise ValueError("Module name cannot be empty after 'no ' prefix for -M- switch.") + cmd.append(f"-M-{module_name}") # For 'no module;' + else: + cmd.append(f"-M{module_spec}") # For 'use module;' + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if rudimentary_parsing_for_switches: + cmd.append("-s") + if look_for_programfile_in_path: + cmd.append("-S") + if tainting_warnings: + cmd.append("-t") + if tainting_checks: + cmd.append("-T") + if dump_core_after_parsing: + cmd.append("-u") + if allow_unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config_summary_variable is not None: + cmd.append(f"-V:{print_config_summary_variable}" if print_config_summary_variable else "-V") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if ignore_text_before_shebang_cd_to_directory is not None: + if ignore_text_before_shebang_cd_to_directory and not ignore_text_before_shebang_cd_to_directory.is_dir(): + raise NotADirectoryError(f"Directory for -x not found: {ignore_text_before_shebang_cd_to_directory}") + cmd.append(f"-x{ignore_text_before_shebang_cd_to_directory}" if ignore_text_before_shebang_cd_to_directory else "-x") + if disable_all_warnings: + cmd.append("-X") + + # Add inline program code + if inline_program: + for code_line in inline_program: + cmd.extend(["-e", code_line]) + if inline_program_extended: + for code_line in inline_program_extended: + cmd.extend(["-E", code_line]) + + # Add program file or arguments for inline code, with '--' separator + if program_file: + # Add '--' to explicitly separate Perl interpreter options from the script file and its arguments. + cmd.append("--") + cmd.append(str(program_file)) + if program_arguments: + cmd.extend(program_arguments) + elif (inline_program or inline_program_extended) and program_arguments: + # If inline code is used and there are program arguments, + # the arguments are passed directly to perl after the -e/-E options. + # Add '--' to explicitly separate Perl interpreter options (including -e/-E) + # from the arguments that follow. + cmd.append("--") + cmd.extend(program_arguments) + + command_executed = " ".join(map(str, cmd)) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = result.stdout + stderr = result.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": output_files, + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "error": "Perl executable not found.", + "returncode": 127, + "output_files": output_files, + } + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/app/perl-text-format_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/app/perl-text-format_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7a2c059bd5b2f0d2dedd0622b436f5506f9c1e5d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/app/perl-text-format_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/app/perl-text-format_server.py') +SERVER_NAME = 'biosci_perl_text_format' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2254dd9f1adfeab4b28dafa6f9e672b3e75a0d21 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-text-format: + build: . + image: mcp-perl-text-format:latest + container_name: mcp-perl-text-format + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-text-format + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3b4883289a7c10f21926a5895a8675acbb1f2d16 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-text-format + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-format/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-parsewords/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-parsewords/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-text-parsewords/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9fd2d1149624e5844ec908f2f30a032bf557f15f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-threaded via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-threaded -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-threaded_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-threaded_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-threaded_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/app/perl-threaded_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/app/perl-threaded_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ae55da7095870b920d1f0a748960ab08561a94be --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/app/perl-threaded_server.py @@ -0,0 +1,253 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +@mcp.tool() +def run_perl( + program_file: Optional[Path] = None, + program_arguments: Optional[List[str]] = None, + record_separator_octal: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + program_lines: Optional[List[str]] = None, + program_lines_extended: Optional[List[str]] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + module_operations: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + rudimentary_parsing: bool = False, + search_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang_dir: Optional[Path] = None, + disable_all_warnings: bool = False, + stop_option_processing: bool = False, +) -> Dict[str, Any]: + """ + Executes a Perl program with specified command-line switches and arguments. + + This function provides comprehensive control over Perl's execution environment, + allowing users to run Perl scripts, execute one-liners, and configure various + runtime behaviors such as debugging, warning levels, and file processing. + + Args: + program_file: Path to the Perl script file to execute. + Cannot be used with `program_lines` or `program_lines_extended`. + program_arguments: A list of strings to be passed as arguments to the Perl script. + record_separator_octal: Specify the input record separator. + If an empty string (""), sets it to null character (\0). + If a string (e.g., "123"), sets it to the octal value. + autosplit: Enables autosplit mode with -n or -p, splitting $_ into @F. + Requires either `loop_around_program` or `loop_and_print` to be True. + unicode_features: Enables listed Unicode features. Can be a number or a list. + check_syntax_only: Checks syntax only (runs BEGIN and CHECK blocks). + debugger: Run program under debugger. If an empty string (""), enables debugger. + If a string (e.g., "MyDebugger"), runs with the specified debugger. + debugging_flags: Set debugging flags (argument is a bit mask or alphabets). + program_lines: A list of Perl code lines to execute directly. + Each string in the list corresponds to a separate -e switch. + Cannot be used with `program_file`. + program_lines_extended: A list of Perl code lines, like `program_lines`, + but enables all optional features. + Each string in the list corresponds to a separate -E switch. + Cannot be used with `program_file`. + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. + split_pattern: The pattern for `split()` when `autosplit` is enabled. + (e.g., "/\t/" for tab-separated). + edit_in_place_extension: Edit <> files in place. If an empty string (""), + edits without making a backup. If a string (e.g., ".bak"), + makes a backup with the specified extension. + include_directories: A list of directories to add to @INC for module searching. + line_ending_processing: Enable line ending processing. If an empty string (""), + enables default processing. If an octal string (e.g., "012"), + specifies the line terminator. + module_operations: A list of strings, where each string represents a full module + operation switch (e.g., '-mMyModule', '-M-AnotherModule'). + These are executed before the program. + loop_around_program: Assumes "while (<>) { ... }" loop around the program. + loop_and_print: Assumes a loop like -n but also prints the line, similar to sed. + rudimentary_parsing: Enables rudimentary parsing for switches after programfile. + search_path: Looks for `program_file` using the PATH environment variable. + tainting_warnings: Enables tainting warnings. + tainting_checks: Enables tainting checks. + dump_core: Dumps core after parsing the program. + allow_unsafe_operations: Allows unsafe operations. + print_version: Prints Perl version, patchlevel, and license information. + print_config_summary: Prints a configuration summary. If an empty string (""), + prints full summary. If a string (e.g., "archname"), + prints a single Config.pm variable. + enable_warnings: Enables many useful warnings (-w). + enable_all_warnings: Enables all warnings (-W). + ignore_text_before_shebang_dir: Ignores text before the #!perl line. + If an empty string (Path("")), ignores without changing directory. + If a Path, changes to that directory before execution. + disable_all_warnings: Disables all warnings (-X). + stop_option_processing: Stops processing command-line options at `--`. + All subsequent arguments are treated as non-options. + """ + command = ["perl"] + output_files: List[Path] = [] + + # Input validation + if program_file and (program_lines or program_lines_extended): + raise ValueError( + "Cannot specify both 'program_file' and 'program_lines' or 'program_lines_extended'. " + "Use either a script file or one-liner code." + ) + + if program_file: + if not program_file.is_file(): + raise FileNotFoundError(f"Program file not found or is not a file: {program_file}") + + if autosplit and not (loop_around_program or loop_and_print): + raise ValueError( + "Autosplit mode (-a) requires either 'loop_around_program' (-n) or 'loop_and_print' (-p)." + ) + + if include_directories: + for d in include_directories: + if not d.is_dir(): + raise NotADirectoryError(f"Include directory not found or not a directory: {d}") + + if ignore_text_before_shebang_dir is not None and ignore_text_before_shebang_dir != Path(""): + if not ignore_text_before_shebang_dir.is_dir(): + raise NotADirectoryError( + f"Directory for -x option not found or not a directory: {ignore_text_before_shebang_dir}" + ) + + # Add switches + if record_separator_octal is not None: + command.append(f"-0{record_separator_octal}") + if autosplit: + command.append("-a") + if unicode_features is not None: + command.append(f"-C{unicode_features}") + if check_syntax_only: + command.append("-c") + if debugger is not None: + command.append(f"-d{':' + debugger if debugger else ''}") + if debugging_flags is not None: + command.append(f"-D{debugging_flags}") + if program_lines: + for line in program_lines: + command.extend(["-e", line]) + if program_lines_extended: + for line in program_lines_extended: + command.extend(["-E", line]) + if no_sitecustomize: + command.append("-f") + if split_pattern is not None: + command.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + command.append(f"-i{edit_in_place_extension}") + if include_directories: + for d in include_directories: + command.extend(["-I", str(d)]) + if line_ending_processing is not None: + command.append(f"-l{line_ending_processing}") + if module_operations: + for op in module_operations: + # Validate format: starts with -m, -M, -m-, or -M- + if not (op.startswith("-m") or op.startswith("-M")): + raise ValueError( + f"Invalid module operation format: '{op}'. " + "Expected format like '-mMyModule' or '-M-AnotherModule'." + ) + command.append(op) + if loop_around_program: + command.append("-n") + if loop_and_print: + command.append("-p") + if rudimentary_parsing: + command.append("-s") + if search_path: + command.append("-S") + if tainting_warnings: + command.append("-t") + if tainting_checks: + command.append("-T") + if dump_core: + command.append("-u") + if allow_unsafe_operations: + command.append("-U") + if print_version: + command.append("-v") + if print_config_summary is not None: + command.append(f"-V{':' + print_config_summary if print_config_summary else ''}") + if enable_warnings: + command.append("-w") + if enable_all_warnings: + command.append("-W") + if ignore_text_before_shebang_dir is not None: + command.append(f"-x{str(ignore_text_before_shebang_dir) if ignore_text_before_shebang_dir else ''}") + if disable_all_warnings: + command.append("-X") + + # Add `--` to stop option processing if requested + if stop_option_processing: + command.append("--") + + # Add program file and its arguments + if program_file: + command.append(str(program_file)) + if program_arguments: + command.extend(program_arguments) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding="utf-8" + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "returncode": e.returncode, + "error": f"Perl execution failed with exit code {e.returncode}", + "output_files": output_files, + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'perl' command not found. Is Perl installed and in your PATH?", + "returncode": 127, + "error": "Perl executable not found.", + "output_files": output_files, + } + except Exception as e: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": str(e), + "returncode": 1, + "error": f"An unexpected error occurred: {e}", + "output_files": output_files, + } + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/app/perl-threaded_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/app/perl-threaded_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5e0ac232071070aecd87a1ed2260abdadff47d6e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/app/perl-threaded_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/app/perl-threaded_server.py') +SERVER_NAME = 'biosci_perl_threaded' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8df2579fab04aa21e5b01d0d3abbcac7dd80629c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-threaded: + build: . + image: mcp-perl-threaded:latest + container_name: mcp-perl-threaded + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-threaded + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ea91014edfdadef34eb58a7b310b9d6a26224264 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-threaded + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-threaded/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3a8986669d7122c5b982c49a54fc7419ff1cc01e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-tie-ixhash via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-tie-ixhash -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-tie-ixhash_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-tie-ixhash_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-tie-ixhash_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/app/perl-tie-ixhash_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/app/perl-tie-ixhash_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a15bffefd93c4a38fee02600cce1580a6fd2a8c4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/app/perl-tie-ixhash_server.py @@ -0,0 +1,240 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union +import tempfile + +@mcp.tool() +def perl_tie_ixhash_execute( + code: str, + input_files: Optional[List[str]] = None, + use_ixhash: bool = True, + autosplit: bool = False, + split_pattern: Optional[str] = None, + inplace_extension: Optional[str] = None, + line_ending_processing: bool = False, + assume_while_loop: bool = False, + assume_print_loop: bool = False, + warnings: bool = True, + all_warnings: bool = False, + include_dirs: Optional[List[str]] = None, + unicode_features: Optional[str] = None, +) -> dict: + """ + Execute Perl code (one-liner) with Tie::IxHash support. + + Args: + code: The Perl code to execute. + input_files: List of input files to process. + use_ixhash: If True, automatically prepends 'use Tie::IxHash;' to the code. + autosplit: Enable autosplit mode with -n or -p (splits $_ into @F). + split_pattern: Pattern for autosplit (-F). + inplace_extension: Edit files in place, optionally providing a backup extension. + line_ending_processing: Enable line ending processing (-l). + assume_while_loop: Assume "while (<>) { ... }" loop around program (-n). + assume_print_loop: Assume loop like -n but print line also (-p). + warnings: Enable many useful warnings (-w). + all_warnings: Enable all warnings (-W). + include_dirs: List of directories to add to @INC. + unicode_features: Enable listed Unicode features (-C). + """ + cmd = ["perl"] + + # Handle flags + if unicode_features: + cmd.append(f"-C{unicode_features}") + if warnings: + cmd.append("-w") + if all_warnings: + cmd.append("-W") + if autosplit: + cmd.append("-a") + if split_pattern: + cmd.append(f"-F{split_pattern}") + if inplace_extension is not None: + cmd.append(f"-i{inplace_extension}") + if line_ending_processing: + cmd.append("-l") + if assume_while_loop: + cmd.append("-n") + if assume_print_loop: + cmd.append("-p") + + if include_dirs: + for d in include_dirs: + cmd.append(f"-I{d}") + + # Prepare code + final_code = code + if use_ixhash: + final_code = "use Tie::IxHash; " + code + + cmd.extend(["-e", final_code]) + + # Handle input files + if input_files: + for f in input_files: + path = Path(f) + if not path.exists(): + return {"error": f"Input file not found: {f}"} + cmd.append(str(path)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def perl_tie_ixhash_run_script( + script_path: str, + args: Optional[List[str]] = None, + warnings: bool = True, + include_dirs: Optional[List[str]] = None, + taint_checks: bool = False, +) -> dict: + """ + Run a Perl script file that utilizes Tie::IxHash. + + Args: + script_path: Path to the Perl script (.pl). + args: Arguments to pass to the script. + warnings: Enable warnings (-w). + include_dirs: List of directories to add to @INC. + taint_checks: Enable tainting checks (-T). + """ + path = Path(script_path) + if not path.exists(): + return {"error": f"Script file not found: {script_path}"} + + cmd = ["perl"] + + if warnings: + cmd.append("-w") + if taint_checks: + cmd.append("-T") + if include_dirs: + for d in include_dirs: + cmd.append(f"-I{d}") + + cmd.append(str(path)) + + if args: + cmd.extend(args) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def perl_tie_ixhash_check_syntax( + script_path: str, + include_dirs: Optional[List[str]] = None, +) -> dict: + """ + Check the syntax of a Perl script without executing it. + + Args: + script_path: Path to the Perl script. + include_dirs: List of directories to add to @INC. + """ + path = Path(script_path) + if not path.exists(): + return {"error": f"Script file not found: {script_path}"} + + cmd = ["perl", "-c"] + if include_dirs: + for d in include_dirs: + cmd.append(f"-I{d}") + cmd.append(str(path)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "syntax_ok" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Syntax check failed", + "status": "syntax_error" + } + +@mcp.tool() +def perl_tie_ixhash_version_info() -> dict: + """ + Get Perl version and configuration information. + """ + try: + # Get basic version + v_result = subprocess.run(["perl", "-v"], capture_output=True, text=True, check=True) + # Check if Tie::IxHash is actually installed and get its version + ix_check = subprocess.run( + ["perl", "-MTie::IxHash", "-e", "print $Tie::IxHash::VERSION"], + capture_output=True, text=True + ) + + return { + "perl_version": v_result.stdout, + "tie_ixhash_version": ix_check.stdout if ix_check.returncode == 0 else "Not found", + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stderr": e.stderr, + "status": "error" + } + +@mcp.tool() +def perl_tie_ixhash_example_usage() -> dict: + """ + Returns a code example showing how to use Tie::IxHash in Perl. + """ + example_code = """ +use Tie::IxHash; + +# Tie a hash to Tie::IxHash to maintain insertion order +tie my %hash, 'Tie::IxHash'; + +$hash{first} = 1; +$hash{second} = 2; +$hash{third} = 3; + +# Keys will be printed in the order they were inserted +foreach my $key (keys %hash) { + print "$key: $hash{$key}\\n"; +} +""" + return { + "example_perl_code": example_code, + "description": "This example demonstrates how to maintain key order in a Perl hash using Tie::IxHash." + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/app/perl-tie-ixhash_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/app/perl-tie-ixhash_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a2a4235a18389aded507ef3d4440ce933772d112 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/app/perl-tie-ixhash_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/app/perl-tie-ixhash_server.py') +SERVER_NAME = 'biosci_perl_tie_ixhash' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..555921a48b6e71df18ab1dea8a8fd96c8061e171 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-tie-ixhash: + build: . + image: mcp-perl-tie-ixhash:latest + container_name: mcp-perl-tie-ixhash + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-tie-ixhash + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1f7a590267a8087d582178dbca6a214ab59f88e8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-tie-ixhash + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d04cdb80a58c5fbdf1dd66eb56b0344c58c6645c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-time-hires via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-time-hires -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-time-hires_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-time-hires_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-time-hires_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/app/perl-time-hires_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/app/perl-time-hires_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c584959d07960b81d706952762f255ce195b3b38 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/app/perl-time-hires_server.py @@ -0,0 +1,393 @@ +from typing import Optional, List +import subprocess +from pathlib import Path + +@mcp.tool() +def usleep(microseconds: int): + """ + Sleeps for the number of microseconds (millionths of a second) specified. + Returns the number of microseconds actually slept. + """ + if microseconds < 0: + return {"error": "microseconds must be a non-negative integer"} + + cmd = ["perl", "-MTime::HiRes=usleep", "-e", "print usleep($ARGV[0])", str(microseconds)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "microseconds_slept": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def nanosleep(nanoseconds: int): + """ + Sleeps for the number of nanoseconds (1e9ths of a second) specified. + Returns the number of nanoseconds actually slept (accurate only to microseconds). + """ + if nanoseconds < 0: + return {"error": "nanoseconds must be a non-negative integer"} + + cmd = ["perl", "-MTime::HiRes=nanosleep", "-e", "print nanosleep($ARGV[0])", str(nanoseconds)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "nanoseconds_slept": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def ualarm(microseconds: int, interval_microseconds: int = 0): + """ + Issues a ualarm call. The interval_microseconds is optional (defaults to 0). + Returns the remaining time in the alarm in microseconds. + """ + if microseconds < 0 or interval_microseconds < 0: + return {"error": "Parameters must be non-negative integers"} + + cmd = ["perl", "-MTime::HiRes=ualarm", "-e", "print ualarm($ARGV[0], $ARGV[1])", str(microseconds), str(interval_microseconds)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "remaining_microseconds": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def gettimeofday(): + """ + Returns the seconds and microseconds since the epoch as a comma-separated string. + """ + cmd = ["perl", "-MTime::HiRes=gettimeofday", "-e", "print join(',', gettimeofday())"] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "time_data": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def tv_interval(sec1: int, usec1: int, sec2: Optional[int] = None, usec2: Optional[int] = None): + """ + Returns the floating seconds between two times (sec1, usec1) and (sec2, usec2). + If the second time is omitted, the current time is used. + """ + if sec2 is not None and usec2 is not None: + perl_code = f"print tv_interval([{sec1}, {usec1}], [{sec2}, {usec2}])" + else: + perl_code = f"print tv_interval([{sec1}, {usec1}])" + + cmd = ["perl", "-MTime::HiRes=tv_interval", "-e", perl_code] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "interval_seconds": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def hires_time(): + """ + Returns floating seconds since the epoch with microsecond resolution. + """ + cmd = ["perl", "-MTime::HiRes=time", "-e", "printf('%.6f', time())"] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "current_time": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def hires_sleep(seconds: float): + """ + Sleeps for the specified amount of floating point seconds. + Returns the number of seconds actually slept. + """ + if seconds < 0: + return {"error": "seconds must be a non-negative float"} + + cmd = ["perl", "-MTime::HiRes=sleep", "-e", "print sleep($ARGV[0])", str(seconds)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "seconds_slept": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def hires_alarm(seconds: float, interval: float = 0.0): + """ + Sets an alarm for the specified floating point seconds. + Returns the remaining time in the alarm in seconds. + """ + if seconds < 0 or interval < 0: + return {"error": "Parameters must be non-negative floats"} + + cmd = ["perl", "-MTime::HiRes=alarm", "-e", "print alarm($ARGV[0], $ARGV[1])", str(seconds), str(interval)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "remaining_seconds": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def hires_stat(file_path: str): + """ + Performs a high-resolution stat on a file. + Returns a comma-separated list of stat fields (dev, ino, mode, nlink, uid, gid, rdev, size, atime, mtime, ctime, blksize, blocks). + """ + path = Path(file_path) + if not path.exists(): + return {"error": f"File not found: {file_path}"} + + cmd = ["perl", "-MTime::HiRes=stat", "-e", "print join(',', stat($ARGV[0]))", str(file_path)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "stat_fields": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def hires_lstat(file_path: str): + """ + Performs a high-resolution lstat on a symbolic link or file. + Returns a comma-separated list of stat fields. + """ + path = Path(file_path) + if not path.exists() and not path.is_symlink(): + return {"error": f"File or link not found: {file_path}"} + + cmd = ["perl", "-MTime::HiRes=lstat", "-e", "print join(',', lstat($ARGV[0]))", str(file_path)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "lstat_fields": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def hires_utime(atime: float, mtime: float, files: List[str]): + """ + Sets high-resolution access and modification times for a list of files. + Returns the number of files successfully updated. + """ + for f in files: + if not Path(f).exists(): + return {"error": f"File not found: {f}"} + + cmd = ["perl", "-MTime::HiRes=utime", "-e", "$a=shift; $m=shift; print utime($a, $m, @ARGV)", str(atime), str(mtime)] + files + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "files_updated": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def clock_gettime(clock_id: str = "CLOCK_REALTIME"): + """ + Returns the current time of the specified clock (e.g., CLOCK_REALTIME, CLOCK_MONOTONIC). + """ + cmd = ["perl", "-MTime::HiRes=:all", "-e", "print clock_gettime(eval($ARGV[0]))", clock_id] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "clock_time": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def clock_getres(clock_id: str = "CLOCK_REALTIME"): + """ + Returns the resolution of the specified clock. + """ + cmd = ["perl", "-MTime::HiRes=:all", "-e", "print clock_getres(eval($ARGV[0]))", clock_id] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "clock_resolution": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def clock_nanosleep(nanoseconds: int, clock_id: str = "CLOCK_REALTIME", flags: int = 0): + """ + Sleeps for the specified nanoseconds using the specified clock. + Flags can be TIMER_ABSTIME (1) or 0. + """ + if nanoseconds < 0: + return {"error": "nanoseconds must be non-negative"} + + cmd = ["perl", "-MTime::HiRes=:all", "-e", "print clock_nanosleep(eval($ARGV[1]), $ARGV[0], $ARGV[2])", str(nanoseconds), clock_id, str(flags)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "nanoseconds_slept": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def hires_clock(): + """ + Returns the process time (user + system) in seconds with high resolution. + """ + cmd = ["perl", "-MTime::HiRes=clock", "-e", "print clock()"] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "process_time": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/app/perl-time-hires_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/app/perl-time-hires_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..06c1f06ae786a6706b485a737a97ea96e0270509 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/app/perl-time-hires_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/app/perl-time-hires_server.py') +SERVER_NAME = 'biosci_perl_time_hires' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..99e2b434733b7c74e3d8984e4fc7f075151f30d3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-time-hires: + build: . + image: mcp-perl-time-hires:latest + container_name: mcp-perl-time-hires + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-time-hires + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..32c6d05fb886e826b264e96e0ac8aa3a9751a744 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-time-hires + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-hires/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fdc2efcda59aa128dc9672dd58678aa1e52db6d3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-time-local via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-time-local -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-time-local_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-time-local_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-time-local_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/app/perl-time-local_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/app/perl-time-local_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e361c333c0a0eeae3c1101e84b6ab5789df04f00 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/app/perl-time-local_server.py @@ -0,0 +1,267 @@ +import subprocess +from typing import Optional + +@mcp.tool() +def timelocal( + sec: int, + min: int, + hour: int, + mday: int, + mon: int, + year: int, +) -> dict: + """ + Converts local time components to a Unix timestamp (seconds since the epoch). + This is the inverse of Perl's built-in localtime() function. + + Args: + sec: Seconds (0-59) + min: Minutes (0-59) + hour: Hours (0-23) + mday: Day of the month (1-31) + mon: Month of the year (0-11, where 0 is January) + year: Year (e.g., 2023). Note: Values 0-99 are interpreted as 1900-1999 or 2000-2099 depending on the version. + """ + # Validation + if not (0 <= sec <= 59): + raise ValueError("sec must be between 0 and 59") + if not (0 <= min <= 59): + raise ValueError("min must be between 0 and 59") + if not (0 <= hour <= 23): + raise ValueError("hour must be between 0 and 23") + if not (1 <= mday <= 31): + raise ValueError("mday must be between 1 and 31") + if not (0 <= mon <= 11): + raise ValueError("mon must be between 0 and 11 (0=Jan)") + + # Construct Perl command + # We use -MTime::Local to load the module and -e to execute the code + perl_code = f"use Time::Local; print timelocal({sec}, {min}, {hour}, {mday}, {mon}, {year})" + cmd = ["perl", "-e", perl_code] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "timestamp": int(result.stdout.strip()) if result.stdout.strip().isdigit() else result.stdout.strip() + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Perl execution failed. Ensure perl-time-local is installed." + } + +@mcp.tool() +def timegm( + sec: int, + min: int, + hour: int, + mday: int, + mon: int, + year: int, +) -> dict: + """ + Converts UTC (GMT) time components to a Unix timestamp (seconds since the epoch). + This is the inverse of Perl's built-in gmtime() function. + + Args: + sec: Seconds (0-59) + min: Minutes (0-59) + hour: Hours (0-23) + mday: Day of the month (1-31) + mon: Month of the year (0-11, where 0 is January) + year: Year (e.g., 2023) + """ + # Validation + if not (0 <= sec <= 59): + raise ValueError("sec must be between 0 and 59") + if not (0 <= min <= 59): + raise ValueError("min must be between 0 and 59") + if not (0 <= hour <= 23): + raise ValueError("hour must be between 0 and 23") + if not (1 <= mday <= 31): + raise ValueError("mday must be between 1 and 31") + if not (0 <= mon <= 11): + raise ValueError("mon must be between 0 and 11 (0=Jan)") + + perl_code = f"use Time::Local; print timegm({sec}, {min}, {hour}, {mday}, {mon}, {year})" + cmd = ["perl", "-e", perl_code] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "timestamp": int(result.stdout.strip()) if result.stdout.strip().isdigit() else result.stdout.strip() + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Perl execution failed." + } + +@mcp.tool() +def timelocal_modern( + sec: int, + min: int, + hour: int, + mday: int, + mon: int, + year: int, +) -> dict: + """ + A 'modern' version of timelocal that always interprets the year as a full year + (e.g., 99 is year 99 AD, not 1999). Requires Time::Local 1.27+. + + Args: + sec: Seconds (0-59) + min: Minutes (0-59) + hour: Hours (0-23) + mday: Day of the month (1-31) + mon: Month of the year (0-11) + year: Full year (e.g., 2023) + """ + perl_code = f"use Time::Local 'timelocal_modern'; print timelocal_modern({sec}, {min}, {hour}, {mday}, {mon}, {year})" + cmd = ["perl", "-e", perl_code] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "timestamp": result.stdout.strip() + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Perl execution failed. Ensure Time::Local version is 1.27 or higher." + } + +@mcp.tool() +def timegm_modern( + sec: int, + min: int, + hour: int, + mday: int, + mon: int, + year: int, +) -> dict: + """ + A 'modern' version of timegm that always interprets the year as a full year. + Requires Time::Local 1.27+. + + Args: + sec: Seconds (0-59) + min: Minutes (0-59) + hour: Hours (0-23) + mday: Day of the month (1-31) + mon: Month of the year (0-11) + year: Full year (e.g., 2023) + """ + perl_code = f"use Time::Local 'timegm_modern'; print timegm_modern({sec}, {min}, {hour}, {mday}, {mon}, {year})" + cmd = ["perl", "-e", perl_code] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "timestamp": result.stdout.strip() + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Perl execution failed. Ensure Time::Local version is 1.27 or higher." + } + +@mcp.tool() +def timelocal_nocheck( + sec: int, + min: int, + hour: int, + mday: int, + mon: int, + year: int, +) -> dict: + """ + Converts local time components to a Unix timestamp without range checking. + Useful for date arithmetic (e.g., finding the timestamp for '35th of May'). + + Args: + sec: Seconds + min: Minutes + hour: Hours + mday: Day of the month + mon: Month of the year + year: Year + """ + perl_code = f"use Time::Local 'timelocal_nocheck'; print timelocal_nocheck({sec}, {min}, {hour}, {mday}, {mon}, {year})" + cmd = ["perl", "-e", perl_code] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "timestamp": result.stdout.strip() + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Perl execution failed." + } + +@mcp.tool() +def timegm_nocheck( + sec: int, + min: int, + hour: int, + mday: int, + mon: int, + year: int, +) -> dict: + """ + Converts UTC time components to a Unix timestamp without range checking. + + Args: + sec: Seconds + min: Minutes + hour: Hours + mday: Day of the month + mon: Month of the year + year: Year + """ + perl_code = f"use Time::Local 'timegm_nocheck'; print timegm_nocheck({sec}, {min}, {hour}, {mday}, {mon}, {year})" + cmd = ["perl", "-e", perl_code] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "timestamp": result.stdout.strip() + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Perl execution failed." + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/app/perl-time-local_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/app/perl-time-local_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4cc960a52f2656d913ced8e4415fe64a7f6674ed --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/app/perl-time-local_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/app/perl-time-local_server.py') +SERVER_NAME = 'biosci_perl_time_local' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..15f92946f54b30a3d5b26be13c98a9181a126504 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-time-local: + build: . + image: mcp-perl-time-local:latest + container_name: mcp-perl-time-local + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-time-local + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9119149f2853a871826c5d12c5bd9a69403b4456 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-time-local + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-time-local/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-timedate/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-timedate/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-timedate/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e89b37c88c979bd73af67f808385be53022703bc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-tree-dag_node via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-tree-dag_node -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-tree-dag_node_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-tree-dag_node_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-tree-dag_node_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/app/perl-tree-dag_node_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/app/perl-tree-dag_node_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8b83d7f56a453cc0bde2b31b7881031b198e9c6e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/app/perl-tree-dag_node_server.py @@ -0,0 +1,270 @@ +from typing import Optional, List, Dict, Any +import subprocess +from pathlib import Path +import json + +@mcp.tool() +def perl_run_script( + script_path: str, + args: Optional[List[str]] = None, + warnings: bool = False, + all_warnings: bool = False, + include_dirs: Optional[List[str]] = None, + modules: Optional[List[str]] = None, + inplace_extension: Optional[str] = None, + record_separator: Optional[str] = None, + unicode_features: Optional[str] = None, + use_all_features: bool = False, + taint_checks: bool = False, +): + """ + Execute a Perl script using the perl interpreter with various switches. + + :param script_path: Path to the Perl program file. + :param args: Arguments to pass to the Perl script. + :param warnings: Enable many useful warnings (-w). + :param all_warnings: Enable all warnings (-W). + :param include_dirs: Specify @INC/#include directories (-I). + :param modules: Execute "use module..." before executing program (-M). + :param inplace_extension: Edit <> files in place, optionally making a backup (-i). + :param record_separator: Specify record separator (-0). + :param unicode_features: Enable listed Unicode features (-C). + :param use_all_features: Enable all optional features (-E). + :param taint_checks: Enable tainting checks (-T). + """ + path_obj = Path(script_path) + if not path_obj.exists(): + return {"error": f"Script file not found: {script_path}"} + + command = ["perl"] + + if warnings: + command.append("-w") + if all_warnings: + command.append("-W") + if use_all_features: + command.append("-E") + if taint_checks: + command.append("-T") + if include_dirs: + for d in include_dirs: + command.append(f"-I{d}") + if modules: + for m in modules: + command.append(f"-M{m}") + if record_separator: + command.append(f"-0{record_separator}") + if unicode_features: + command.append(f"-C{unicode_features}") + if inplace_extension: + command.append(f"-i{inplace_extension}") + + command.append(str(path_obj)) + + if args: + command.extend(args) + + try: + result = subprocess.run(command, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "returncode": result.returncode + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "returncode": e.returncode, + "error": str(e) + } + +@mcp.tool() +def perl_run_inline( + code: str, + args: Optional[List[str]] = None, + warnings: bool = False, + all_warnings: bool = False, + include_dirs: Optional[List[str]] = None, + modules: Optional[List[str]] = None, + autosplit: bool = False, + split_pattern: Optional[str] = None, + loop_files: bool = False, + loop_and_print: bool = False, + record_separator: Optional[str] = None, + unicode_features: Optional[str] = None, + use_all_features: bool = False, +): + """ + Execute inline Perl code using the -e or -E flag. + + :param code: One line of program (several -e's allowed, but here provided as one block). + :param args: Arguments to pass to the inline program. + :param warnings: Enable many useful warnings (-w). + :param all_warnings: Enable all warnings (-W). + :param include_dirs: Specify @INC/#include directories (-I). + :param modules: Execute "use module..." before executing program (-M). + :param autosplit: Autosplit mode with -n or -p (splits $_ into @F) (-a). + :param split_pattern: split() pattern for -a switch (-F). + :param loop_files: Assume "while (<>) { ... }" loop around program (-n). + :param loop_and_print: Assume loop like -n but print line also (-p). + :param record_separator: Specify record separator (-0). + :param unicode_features: Enable listed Unicode features (-C). + :param use_all_features: Use -E instead of -e to enable all optional features. + """ + command = ["perl"] + + if warnings: + command.append("-w") + if all_warnings: + command.append("-W") + if autosplit: + command.append("-a") + if loop_files: + command.append("-n") + if loop_and_print: + command.append("-p") + if include_dirs: + for d in include_dirs: + command.append(f"-I{d}") + if modules: + for m in modules: + command.append(f"-M{m}") + if split_pattern: + command.append(f"-F{split_pattern}") + if record_separator: + command.append(f"-0{record_separator}") + if unicode_features: + command.append(f"-C{unicode_features}") + + if use_all_features: + command.extend(["-E", code]) + else: + command.extend(["-e", code]) + + if args: + command.extend(args) + + try: + result = subprocess.run(command, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "returncode": result.returncode + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "returncode": e.returncode, + "error": str(e) + } + +@mcp.tool() +def perl_check_syntax(script_path: str): + """ + Check the syntax of a Perl script without executing it (-c). + + :param script_path: Path to the Perl program file. + """ + path_obj = Path(script_path) + if not path_obj.exists(): + return {"error": f"Script file not found: {script_path}"} + + command = ["perl", "-c", str(path_obj)] + + try: + result = subprocess.run(command, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "Syntax OK" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "status": "Syntax Error", + "error": str(e) + } + +@mcp.tool() +def tree_dag_node_visualize(lol_definition: str): + """ + Visualize an N-ary tree using the Tree::DAG_Node module. + + :param lol_definition: A Perl 'List of Lists' string representing the tree structure. + Example: "['root', ['child1'], ['child2', ['grandchild']]]" + The format is: [node_name, [child1_lol], [child2_lol], ...] + """ + # Construct a Perl script that uses Tree::DAG_Node to render the ASCII tree + perl_code = ( + "use Tree::DAG_Node; " + f"my $lol = {lol_definition}; " + "my $root = Tree::DAG_Node->lol_to_tree($lol); " + "print $root->draw_ascii_tree;" + ) + + command = ["perl", "-MTree::DAG_Node", "-e", perl_code] + + try: + result = subprocess.run(command, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(command), + "ascii_tree": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to render tree. Ensure lol_definition is a valid Perl List-of-Lists and Tree::DAG_Node is installed." + } + +@mcp.tool() +def tree_dag_node_version(): + """ + Get the version of the installed Tree::DAG_Node Perl module. + """ + command = ["perl", "-MTree::DAG_Node", "-e", "print $Tree::DAG_Node::VERSION"] + + try: + result = subprocess.run(command, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(command), + "version": result.stdout.strip() + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "error": "Tree::DAG_Node module not found or perl execution failed.", + "stderr": e.stderr + } + +@mcp.tool() +def tree_dag_node_check_dependencies(): + """ + Check if the required Perl dependencies for Tree::DAG_Node are installed. + """ + deps = ["Tree::DAG_Node", "File::Slurper", "ExtUtils::MakeMaker"] + results = {} + + for dep in deps: + cmd = ["perl", f"-M{dep}", "-e", "1"] + try: + subprocess.run(cmd, capture_output=True, check=True) + results[dep] = "Installed" + except subprocess.CalledProcessError: + results[dep] = "Missing" + + return { + "dependencies_status": results, + "all_satisfied": all(v == "Installed" for v in results.values()) + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/app/perl-tree-dag_node_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/app/perl-tree-dag_node_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6cfabf07009e6b25f89542e24fc3af43d54ba6c1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/app/perl-tree-dag_node_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/app/perl-tree-dag_node_server.py') +SERVER_NAME = 'biosci_perl_tree_dag_node' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8f29388842807424e721a6f4c4eec048f00f667b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-tree-dag_node: + build: . + image: mcp-perl-tree-dag_node:latest + container_name: mcp-perl-tree-dag_node + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-tree-dag_node + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f3d70a34ebdfb9b2ff2a069b3e4d01d3721c5232 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-tree-dag_node + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tree-dag_node/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6df2f857e39f2ab2e99db2d8bcb16725c91c77a9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-try-tiny via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-try-tiny -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-try-tiny_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-try-tiny_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-try-tiny_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/app/perl-try-tiny_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/app/perl-try-tiny_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2162997a9c3a942c569bf3edf1ff5519cd1acf12 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/app/perl-try-tiny_server.py @@ -0,0 +1,278 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +@mcp.tool() +def perl_execute_code( + code: str, + use_try_tiny: bool = True, + warnings_level: str = "default", + line_loop: bool = False, + print_loop: bool = False, + autosplit: bool = False, + split_pattern: Optional[str] = None, + line_processing: bool = False, + enable_all_features: bool = False, + include_dirs: Optional[List[str]] = None, + input_files: Optional[List[str]] = None, +): + """ + Executes a Perl one-liner using the 'perl -e' or 'perl -E' command. + This tool is pre-configured to support Try::Tiny for minimal try/catch blocks. + + Args: + code: The Perl code to execute. + use_try_tiny: If True, automatically loads the Try::Tiny module (-MTry::Tiny). + warnings_level: Warning level to use: 'none' (-X), 'default' (-w), or 'all' (-W). + line_loop: Assume "while (<>) { ... }" loop around program (-n). + print_loop: Assume loop like -n but print line also (-p). + autosplit: Autosplit mode with -n or -p (splits $_ into @F) (-a). + split_pattern: split() pattern for -a switch (-F). + line_processing: Enable line ending processing, specifies line terminator (-l). + enable_all_features: Use -E instead of -e to enable all optional features. + include_dirs: List of directories to add to @INC (-I). + input_files: List of files to be processed by the Perl script. + """ + cmd = ["perl"] + + # Warnings + if warnings_level == "none": + cmd.append("-X") + elif warnings_level == "all": + cmd.append("-W") + else: + cmd.append("-w") + + # Module loading + if use_try_tiny: + cmd.append("-MTry::Tiny") + + # Include directories + if include_dirs: + for d in include_dirs: + cmd.extend(["-I", str(Path(d).resolve())]) + + # Processing switches + if line_loop: + cmd.append("-n") + if print_loop: + cmd.append("-p") + if autosplit: + cmd.append("-a") + if split_pattern: + cmd.append(f"-F{split_pattern}") + if line_processing: + cmd.append("-l") + + # Code execution + if enable_all_features: + cmd.extend(["-E", code]) + else: + cmd.extend(["-e", code]) + + # Input files + if input_files: + for f in input_files: + file_path = Path(f) + if not file_path.exists(): + return {"error": f"Input file not found: {f}"} + cmd.append(str(file_path)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "failed" + } + +@mcp.tool() +def perl_run_script( + script_path: str, + args: Optional[List[str]] = None, + use_try_tiny: bool = True, + taint_check: bool = False, + taint_warnings: bool = False, + include_dirs: Optional[List[str]] = None, + warnings: bool = True, +): + """ + Runs a Perl script file. + + Args: + script_path: Path to the .pl script file. + args: Arguments to pass to the script. + use_try_tiny: If True, loads Try::Tiny before executing the script. + taint_check: Enable tainting checks (-T). + taint_warnings: Enable tainting warnings (-t). + include_dirs: List of directories to add to @INC (-I). + warnings: Enable many useful warnings (-w). + """ + path = Path(script_path) + if not path.exists(): + return {"error": f"Script file not found: {script_path}"} + + cmd = ["perl"] + + if warnings: + cmd.append("-w") + if use_try_tiny: + cmd.append("-MTry::Tiny") + if taint_check: + cmd.append("-T") + if taint_warnings: + cmd.append("-t") + + if include_dirs: + for d in include_dirs: + cmd.extend(["-I", str(Path(d).resolve())]) + + cmd.append(str(path)) + + if args: + cmd.extend(args) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "failed" + } + +@mcp.tool() +def perl_check_syntax( + script_path: str, + use_try_tiny: bool = True, + include_dirs: Optional[List[str]] = None, +): + """ + Checks the syntax of a Perl script without executing it (-c). + + Args: + script_path: Path to the Perl script. + use_try_tiny: If True, loads Try::Tiny during the syntax check. + include_dirs: List of directories to add to @INC (-I). + """ + path = Path(script_path) + if not path.exists(): + return {"error": f"Script file not found: {script_path}"} + + cmd = ["perl", "-c"] + + if use_try_tiny: + cmd.append("-MTry::Tiny") + + if include_dirs: + for d in include_dirs: + cmd.extend(["-I", str(Path(d).resolve())]) + + cmd.append(str(path)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "syntax_ok" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Syntax check failed", + "status": "failed" + } + +@mcp.tool() +def perl_get_version(): + """ + Prints the Perl version and patchlevel information (-v). + """ + cmd = ["perl", "-v"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e) + } + +@mcp.tool() +def perl_get_config( + variable: Optional[str] = None, +): + """ + Prints a configuration summary or a single Config.pm variable (-V). + + Args: + variable: Optional specific configuration variable to query (e.g., 'installsitelib'). + """ + cmd = ["perl"] + if variable: + cmd.append(f"-V:{variable}") + else: + cmd.append("-V") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e) + } + +@mcp.tool() +def perl_try_tiny_example(): + """ + Returns a code snippet demonstrating how to use Try::Tiny's try/catch/finally blocks. + This is useful for users who want to write Perl code using this module. + """ + example = """ +use Try::Tiny; + +try { + # Code that might die + die "An error occurred!"; +} catch { + # Handle error. The error is in $_ + warn "Caught error: $_"; +} finally { + # Cleanup code, always runs + print "Cleaning up...\\n"; +}; +""" + return { + "example_code": example, + "description": "Try::Tiny provides try, catch, and finally blocks. Note the trailing semicolon after the block." + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/app/perl-try-tiny_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/app/perl-try-tiny_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5b90c5c24f63fb1ef051714abb6c9c335c452621 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/app/perl-try-tiny_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/app/perl-try-tiny_server.py') +SERVER_NAME = 'biosci_perl_try_tiny' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f1f5844be5eb3ad5ddc2596d839a5c8b1625807f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-try-tiny: + build: . + image: mcp-perl-try-tiny:latest + container_name: mcp-perl-try-tiny + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-try-tiny + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f67734f1748aee98c514271ea7de2ed48022d965 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-try-tiny + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-try-tiny/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aeb20b22ae3ce8e60d3d01066a7b76ea5bc2da56 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-type-tiny via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-type-tiny -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-type-tiny_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-type-tiny_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-type-tiny_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/app/perl-type-tiny_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/app/perl-type-tiny_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e0fb82822284bb7c1df538a2bd6add233463cf0e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/app/perl-type-tiny_server.py @@ -0,0 +1,313 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +# Helper function to build command arguments +def _build_perl_command( + record_separator_octal: Optional[str], + autosplit_mode: bool, + unicode_features: Optional[str], + check_syntax_only: bool, + debugger: Optional[str], + debugging_flags: Optional[str], + program_code_e: Optional[List[str]], + program_code_E: Optional[List[str]], + no_sitecustomize: bool, + split_pattern: Optional[str], + edit_in_place_extension: Optional[str], + include_directories: Optional[List[Path]], + line_ending_processing_octal: Optional[str], + use_modules: Optional[List[str]], + no_modules: Optional[List[str]], + assume_loop_n: bool, + assume_loop_p: bool, + rudimentary_switch_parsing: bool, + search_path_for_programfile: bool, + tainting_warnings: bool, + tainting_checks: bool, + dump_core: bool, + allow_unsafe_operations: bool, + print_version: bool, + print_config_variable: Optional[str], + enable_warnings: bool, + enable_all_warnings: bool, + ignore_text_before_shebang_dir: Optional[Path], + disable_all_warnings: bool, + program_file: Optional[Path], + script_arguments: Optional[List[str]], +) -> List[str]: + """Constructs the command list for perl.""" + cmd = ["perl"] + + if record_separator_octal is not None: + cmd.append(f"-0{record_separator_octal}") + if autosplit_mode: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if debugger is not None: + cmd.append(f"-d:{debugger}") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if program_code_e: + for code in program_code_e: + cmd.extend(["-e", code]) + if program_code_E: + for code in program_code_E: + cmd.extend(["-E", code]) + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + cmd.append(f"-i{edit_in_place_extension}") + if include_directories: + for inc_dir in include_directories: + cmd.extend(["-I", str(inc_dir)]) + if line_ending_processing_octal is not None: + cmd.append(f"-l{line_ending_processing_octal}") + if use_modules: + for module in use_modules: + cmd.extend(["-M", module]) # -M is common for 'use' + if no_modules: + for module in no_modules: + cmd.extend(["-M-", module]) # -M- for 'no' + if assume_loop_n: + cmd.append("-n") + if assume_loop_p: + cmd.append("-p") + if rudimentary_switch_parsing: + cmd.append("-s") + if search_path_for_programfile: + cmd.append("-S") + if tainting_warnings: + cmd.append("-t") + if tainting_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if allow_unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config_variable is not None: + cmd.append(f"-V:{print_config_variable}") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if ignore_text_before_shebang_dir is not None: + cmd.append(f"-x{ignore_text_before_shebang_dir}") + if disable_all_warnings: + cmd.append("-X") + + # Add program file and script arguments + if program_file: + if not program_file.is_file(): + raise FileNotFoundError(f"Program file not found: {program_file}") + cmd.append(str(program_file)) + + # Add '--' to separate perl options from script arguments if necessary + # This is important if script_arguments might start with '-' and be misinterpreted as perl options. + # It's generally good practice when passing arguments to a script. + if script_arguments: + # Add '--' if a program file is specified, or if no -e/-E code is provided + # (meaning script_arguments are for a script read from stdin or implied by other options). + # If only -e/-E code is provided, script arguments follow directly. + if program_file or (not program_code_e and not program_code_E): + cmd.append("--") + cmd.extend(script_arguments) + + return cmd + +@mcp.tool() +def execute_perl_program( + program_file: Optional[Path] = None, + program_code_e: Optional[List[str]] = None, + program_code_E: Optional[List[str]] = None, + script_arguments: Optional[List[str]] = None, + record_separator_octal: Optional[str] = None, + autosplit_mode: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing_octal: Optional[str] = None, + use_modules: Optional[List[str]] = None, + no_modules: Optional[List[str]] = None, + assume_loop_n: bool = False, + assume_loop_p: bool = False, + rudimentary_switch_parsing: bool = False, + search_path_for_programfile: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_variable: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang_dir: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> dict: + """ + Executes a Perl program or one-liner with various interpreter options. + + This tool wraps the 'perl' interpreter, allowing users to run Perl scripts + or provide one-liners with fine-grained control over Perl's execution + environment and features. It supports all command-line switches + documented by 'perl -h'. The 'perl-type-tiny' module would be available + within the Perl environment managed by conda. + + Args: + program_file: Path to the Perl script file to execute. + program_code_e: List of Perl code strings to execute as one-liners (-e). + Can be specified multiple times. Code is executed before `program_file`. + program_code_E: List of Perl code strings to execute as one-liners (-E), + enabling all optional features. Can be specified multiple times. + Code is executed before `program_file`. + script_arguments: List of arguments to pass to the Perl script. These will be available + in the Perl script via the @ARGV array. + record_separator_octal: Specify record separator (e.g., '0' for NUL, '0777' for paragraph mode). + If no argument, defaults to '\0'. + autosplit_mode: Enable autosplit mode with -n or -p (splits $_ into @F). + unicode_features: Enable listed Unicode features (e.g., 'a' for all, 'l' for locale). + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). + debugger: Run program under debugger. Optionally specify debugger (e.g., 'ptkdb'). + debugging_flags: Set debugging flags (argument is a bit mask or alphabets). + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. + split_pattern: split() pattern for -a switch (e.g., '/\s+/'). + edit_in_place_extension: Edit <> files in place. Makes backup if extension supplied (e.g., '.bak'). + include_directories: List of directories to specify for @INC/#include. Can be specified multiple times. + line_ending_processing_octal: Enable line ending processing, specifies line terminator (e.g., '012' for LF). + use_modules: List of modules to 'use' before executing program (e.g., 'strict', 'warnings'). + Corresponds to -M module. + no_modules: List of modules to 'no' before executing program (e.g., 'strict'). + Corresponds to -M- module. + assume_loop_n: Assume "while (<>) { ... }" loop around program. + assume_loop_p: Assume loop like -n but print line also, like sed. + rudimentary_switch_parsing: Enable rudimentary parsing for switches after programfile. + search_path_for_programfile: Look for programfile using PATH environment variable. + tainting_warnings: Enable tainting warnings. + tainting_checks: Enable tainting checks. + dump_core: Dump core after parsing program. + allow_unsafe_operations: Allow unsafe operations. + print_version: Print version, patchlevel and license. + print_config_variable: Print configuration summary or a single Config.pm variable (e.g., 'archname'). + enable_warnings: Enable many useful warnings (-w). + enable_all_warnings: Enable all warnings (-W). + ignore_text_before_shebang_dir: Ignore text before #!perl line. Optionally cd to directory. + disable_all_warnings: Disable all warnings (-X). + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + # Input validation + if not program_file and not (program_code_e or program_code_E) and not print_version and not print_config_variable: + raise ValueError( + "Either 'program_file', 'program_code_e', 'program_code_E', " + "'print_version', or 'print_config_variable' must be provided " + "to specify an action for Perl." + ) + + if include_directories: + for d in include_directories: + if not d.is_dir(): + raise NotADirectoryError(f"Include directory not found: {d}") + + if ignore_text_before_shebang_dir: + if not ignore_text_before_shebang_dir.is_dir(): + raise NotADirectoryError(f"Directory for -x option not found: {ignore_text_before_shebang_dir}") + + # Build the command + cmd = _build_perl_command( + record_separator_octal=record_separator_octal, + autosplit_mode=autosplit_mode, + unicode_features=unicode_features, + check_syntax_only=check_syntax_only, + debugger=debugger, + debugging_flags=debugging_flags, + program_code_e=program_code_e, + program_code_E=program_code_E, + no_sitecustomize=no_sitecustomize, + split_pattern=split_pattern, + edit_in_place_extension=edit_in_place_extension, + include_directories=include_directories, + line_ending_processing_octal=line_ending_processing_octal, + use_modules=use_modules, + no_modules=no_modules, + assume_loop_n=assume_loop_n, + assume_loop_p=assume_loop_p, + rudimentary_switch_parsing=rudimentary_switch_parsing, + search_path_for_programfile=search_path_for_programfile, + tainting_warnings=tainting_warnings, + tainting_checks=tainting_checks, + dump_core=dump_core, + allow_unsafe_operations=allow_unsafe_operations, + print_version=print_version, + print_config_variable=print_config_variable, + enable_warnings=enable_warnings, + enable_all_warnings=enable_all_warnings, + ignore_text_before_shebang_dir=ignore_text_before_shebang_dir, + disable_all_warnings=disable_all_warnings, + program_file=program_file, + script_arguments=script_arguments, + ) + + command_executed = " ".join(map(str, cmd)) + stdout = "" + stderr = "" + output_files: List[Path] = [] + + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding="utf-8" + ) + stdout = process.stdout + stderr = process.stderr + + # If -i is used, the original file is backed up and the new content is written to the original path. + # The backup file would be an output file. + if edit_in_place_extension and program_file: + backup_file = program_file.with_suffix(program_file.suffix + edit_in_place_extension) + if backup_file.exists(): + output_files.append(backup_file) + + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: perl command not found. Please ensure Perl is installed and in your PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + except Exception as e: + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": f"An unexpected error occurred: {e}", + "output_files": [], + } + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/app/perl-type-tiny_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/app/perl-type-tiny_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c683f431f2ae71de6d6516b8db1104354fbde59b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/app/perl-type-tiny_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/app/perl-type-tiny_server.py') +SERVER_NAME = 'biosci_perl_type_tiny' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4e4aeba0a5dbea92926fe16cd424e894992e673f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-type-tiny: + build: . + image: mcp-perl-type-tiny:latest + container_name: mcp-perl-type-tiny + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-type-tiny + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..280753baca65a58896aa7a454f8cc7bd9b90095f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-type-tiny + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-type-tiny/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-types-serialiser/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-types-serialiser/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-types-serialiser/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..881eb3c306d946ae0a04dce0442703d999f893f8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-unicode-map via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-unicode-map -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-unicode-map_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-unicode-map_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-unicode-map_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/app/perl-unicode-map_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/app/perl-unicode-map_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e9dd9001292fcf7a5f06e6c84d34cbf12c5b96f7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/app/perl-unicode-map_server.py @@ -0,0 +1,264 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union +import tempfile + +# No need to import mcp as per instructions + +@mcp.tool() +def run_perl_script( + program_file: Optional[Path] = None, + program_lines: Optional[List[str]] = None, + script_arguments: Optional[List[str]] = None, + record_separator_octal: Optional[str] = None, + autosplit_mode: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + program_lines_extended: Optional[List[str]] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_terminator_octal: Optional[str] = None, + modules_to_use: Optional[List[str]] = None, + modules_to_no_use: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + rudimentary_parsing_for_switches: bool = False, + search_path_for_program_file: bool = False, + enable_tainting_warnings: bool = False, + enable_tainting_checks: bool = False, + dump_core_after_parsing: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_variable: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_perl_line_dir: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> dict: + """ + Executes a Perl script or program lines with specified Perl interpreter switches. + + This tool provides a robust interface to the Perl interpreter, allowing the execution + of Perl scripts with fine-grained control over various runtime options. It is suitable + for running any Perl program, including those that utilize modules like `perl-unicode-map` + for character set mapping and other Unicode functionalities. + + Args: + program_file: Path to the Perl program file to execute. + Required if `program_lines` or `program_lines_extended` are not provided, + and if not requesting version/config info. + program_lines: A list of Perl code lines to execute directly via the `-e` switch. + Cannot be used with `program_file` or `program_lines_extended`. + script_arguments: Arguments to pass to the Perl script. These are appended after + the program file or `-e`/`-E` lines. + record_separator_octal: Specify the input record separator. If an octal string + (e.g., '0' for NUL, '0777' for paragraph mode) is provided, + it sets `$/`. If an empty string, it defaults to `\0`. + autosplit_mode: Enable autosplit mode (`-a`) with `-n` or `-p`. This splits `$_` + into `@F` based on the pattern specified by `split_pattern` or `/\s+/`. + unicode_features: Enables listed Unicode features (`-C`). Can be a number or a list + (e.g., 'all', 'io', 'say'). + check_syntax_only: Check syntax only (`-c`). Runs `BEGIN` and `CHECK` blocks but + does not execute the main program. + debugger: Run the program under a debugger (`-d`). Optionally specify a debugger + (e.g., 'DB'). + debugging_flags: Set debugging flags (`-D`). Argument is a bit mask or alphabets. + program_lines_extended: A list of Perl code lines to execute directly via the `-E` switch. + Similar to `-e`, but enables all optional features (e.g., `say`, `state`). + Cannot be used with `program_file` or `program_lines`. + no_sitecustomize: Don't do `$sitelib/sitecustomize.pl` at startup (`-f`). + split_pattern: The `split()` pattern for the `-a` switch (`-F/pattern/`). + The slashes are optional in the argument string (e.g., '/\s+/' or '\s+'). + edit_in_place_extension: Edit `<>` files in place (`-i`). If an extension is supplied + (e.g., '.bak'), a backup file will be made with that extension. + If an empty string `""` is provided, files are edited without backup. + include_directories: Specify `@INC` directories (`-I`). These directories are added + to Perl's search path for modules. + line_ending_terminator_octal: Enable line ending processing (`-l`). Specifies the line + terminator (e.g., '012' for newline). If an octal string + is provided, it sets `$\`. If an empty string, it enables + line ending processing without changing `$\`. + modules_to_use: List of modules to `use` before executing the program (`-M`). + Each string should be a module name (e.g., 'strict', 'warnings'). + modules_to_no_use: List of modules to `no` before executing the program (`-M-`). + Each string should be a module name. + loop_around_program: Assume "while (<>) { ... }" loop around the program (`-n`). + Reads input line by line. + loop_and_print: Assume loop like `-n` but print line also, like `sed` (`-p`). + rudimentary_parsing_for_switches: Enable rudimentary parsing for switches after the + program file (`-s`). + search_path_for_program_file: Look for the program file using the `PATH` environment + variable (`-S`). + enable_tainting_warnings: Enable tainting warnings (`-t`). + enable_tainting_checks: Enable tainting checks (`-T`). + dump_core_after_parsing: Dump core after parsing the program (`-u`). + allow_unsafe_operations: Allow unsafe operations (`-U`). + print_version: Print Perl version, patchlevel, and license (`-v`). + Mutually exclusive with program execution options. + print_config_variable: Print configuration summary (`-V`) or a single `Config.pm` + variable (`-V:variable`). Mutually exclusive with program + execution options. + enable_warnings: Enable many useful warnings (`-w`). + enable_all_warnings: Enable all warnings (`-W`). + ignore_text_before_perl_line_dir: Ignore text before the `#!perl` line (`-x`). + Optionally `cd` to the specified directory. + disable_all_warnings: Disable all warnings (`-X`). + """ + command = ["perl"] + output_files: List[Path] = [] + + # Input validation + has_program_source = program_file is not None or program_lines is not None or program_lines_extended is not None + has_info_request = print_version or print_config_variable is not None + + if has_program_source and has_info_request: + raise ValueError( + "Cannot specify program source (file or lines) along with " + "version/config print options (-v or -V)." + ) + if not has_program_source and not has_info_request: + raise ValueError( + "Either a program source (program_file, program_lines, or program_lines_extended) " + "or an info request (print_version, print_config_variable) must be provided." + ) + + if program_file and (program_lines is not None or program_lines_extended is not None): + raise ValueError("Cannot specify both 'program_file' and 'program_lines' or 'program_lines_extended'.") + if program_lines is not None and program_lines_extended is not None: + raise ValueError("Cannot specify both 'program_lines' (-e) and 'program_lines_extended' (-E).") + + if program_file: + if not program_file.is_file(): + raise FileNotFoundError(f"Program file not found: {program_file}") + + if include_directories: + for d in include_directories: + if not d.is_dir(): + raise NotADirectoryError(f"Include directory not found: {d}") + if ignore_text_before_perl_line_dir: + if not ignore_text_before_perl_line_dir.is_dir(): + raise NotADirectoryError(f"Directory for -x option not found: {ignore_text_before_perl_line_dir}") + + # Build command + if record_separator_octal is not None: + command.append(f"-0{record_separator_octal}") + if autosplit_mode: + command.append("-a") + if unicode_features is not None: + command.append(f"-C{unicode_features}") + if check_syntax_only: + command.append("-c") + if debugger is not None: + command.append(f"-d:{debugger}") + if debugging_flags is not None: + command.append(f"-D{debugging_flags}") + if program_lines: + for line in program_lines: + command.extend(["-e", line]) + if program_lines_extended: + for line in program_lines_extended: + command.extend(["-E", line]) + if no_sitecustomize: + command.append("-f") + if split_pattern is not None: + command.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + command.append(f"-i{edit_in_place_extension}") + if include_directories: + for d in include_directories: + command.extend(["-I", str(d)]) + if line_ending_terminator_octal is not None: + command.append(f"-l{line_ending_terminator_octal}") + if modules_to_use: + for module in modules_to_use: + command.extend(["-M", module]) # Using -M for 'use module' + if modules_to_no_use: + for module in modules_to_no_use: + command.extend(["-M-", module]) # Using -M- for 'no module' + if loop_around_program: + command.append("-n") + if loop_and_print: + command.append("-p") + if rudimentary_parsing_for_switches: + command.append("-s") + if search_path_for_program_file: + command.append("-S") + if enable_tainting_warnings: + command.append("-t") + if enable_tainting_checks: + command.append("-T") + if dump_core_after_parsing: + command.append("-u") + if allow_unsafe_operations: + command.append("-U") + if print_version: + command.append("-v") + if print_config_variable is not None: + command.append(f"-V:{print_config_variable}") + # Note: The perl -V switch without an argument is covered by print_config_variable=None + # if the user explicitly wanted to pass -V. However, the current signature + # only allows -V:variable. If print_config_variable is None, -V is not added. + # For simplicity, we assume if print_config_variable is None, the user doesn't want -V. + # If they want -V (no arg), they would set print_config_variable = "". + # Let's adjust this to allow print_config_variable = "" for -V. + # The current code `if print_config_variable is not None:` handles both string and empty string. + + if enable_warnings: + command.append("-w") + if enable_all_warnings: + command.append("-W") + if ignore_text_before_perl_line_dir is not None: + command.append(f"-x{ignore_text_before_perl_line_dir}") + if disable_all_warnings: + command.append("-X") + + # Add program file and its arguments + if program_file: + command.append(str(program_file)) + if script_arguments: + command.extend(script_arguments) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + + # If -i was used, Perl modifies files in place and potentially creates backups. + # Identifying these output files robustly without knowing the input files + # passed to Perl's diamond operator (<>) is challenging. + # For this tool, we will not attempt to automatically track files modified by -i. + # Users should manage these files based on their script's input. + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl command failed with exit code {e.returncode}: {e}", + "returncode": e.returncode, + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'perl' command not found. Ensure Perl is installed and in your system's PATH.", + "error": "Perl executable not found", + "returncode": 127, + "output_files": [], + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/app/perl-unicode-map_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/app/perl-unicode-map_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..79e9a02b7e110e160e965a1551aba684275d9c87 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/app/perl-unicode-map_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/app/perl-unicode-map_server.py') +SERVER_NAME = 'biosci_perl_unicode_map' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e7ef8d7a2a344f77de3733d64cd9be1450518f00 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-unicode-map: + build: . + image: mcp-perl-unicode-map:latest + container_name: mcp-perl-unicode-map + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-unicode-map + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dc152987b03c644554279b75fbde4a293e6e1758 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-unicode-map + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-unicode-map/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7f4cb95d79eb70a08a3b354d161e2040f947bf29 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-uri via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-uri -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-uri_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-uri_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-uri_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/app/perl-uri_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/app/perl-uri_server.py new file mode 100644 index 0000000000000000000000000000000000000000..eccea1886a87ba5a9a5555b6f2c9fe1fe1bd6954 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/app/perl-uri_server.py @@ -0,0 +1,322 @@ +import subprocess +import json +from typing import Optional, List, Dict, Any, Union +from pathlib import Path + +def _run_perl_uri(script: str, args: List[str]) -> Dict[str, Any]: + """ + Helper to execute Perl code using the URI module and return structured results. + """ + full_script = f"use URI; use URI::file; use URI::QueryParam; use JSON::PP; {script}" + cmd = ["perl", "-e", full_script, "--"] + args + + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout.strip(), + "stderr": process.stderr.strip(), + "success": True + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "success": False, + "error": str(e) + } + +@mcp.tool() +def uri_new( + uri_str: str, + scheme: Optional[str] = None +) -> Dict[str, Any]: + """ + Constructs a new URI object and returns its basic components (scheme, opaque, path, fragment). + + :param uri_str: The URI string to parse. + :param scheme: Optional scheme specification (used if uri_str is relative). + """ + perl_code = """ + my $u = URI->new($ARGV[0], $ARGV[1]); + my %res = ( + scheme => $u->scheme, + opaque => $u->opaque, + path => $u->path, + fragment => $u->fragment, + as_string => $u->as_string, + as_iri => $u->as_iri, + is_secure => $u->secure ? JSON::PP::true : JSON::PP::false, + has_recognized_scheme => $u->has_recognized_scheme ? JSON::PP::true : JSON::PP::false + ); + print encode_json(\%res); + """ + args = [uri_str, scheme if scheme else ""] + result = _run_perl_uri(perl_code, args) + + if result["success"] and result["stdout"]: + result["parsed"] = json.loads(result["stdout"]) + return result + +@mcp.tool() +def uri_new_abs( + uri_str: str, + base_uri: str +) -> Dict[str, Any]: + """ + Constructs a new absolute URI object by resolving a relative URI against a base URI. + + :param uri_str: The relative or absolute URI string. + :param base_uri: The absolute base URI. + """ + perl_code = """ + my $u = URI->new_abs($ARGV[0], $ARGV[1]); + print encode_json({ absolute_uri => $u->as_string }); + """ + result = _run_perl_uri(perl_code, [uri_str, base_uri]) + if result["success"] and result["stdout"]: + result["data"] = json.loads(result["stdout"]) + return result + +@mcp.tool() +def uri_canonical( + uri_str: str +) -> Dict[str, Any]: + """ + Returns a normalized (canonical) version of the URI. + + :param uri_str: The URI string to normalize. + """ + perl_code = """ + my $u = URI->new($ARGV[0])->canonical; + print encode_json({ canonical_uri => $u->as_string }); + """ + result = _run_perl_uri(perl_code, [uri_str]) + if result["success"] and result["stdout"]: + result["data"] = json.loads(result["stdout"]) + return result + +@mcp.tool() +def uri_abs_rel( + uri_str: str, + base_uri: str, + mode: str = "abs" +) -> Dict[str, Any]: + """ + Returns an absolute or relative URI reference relative to a base URI. + + :param uri_str: The URI to transform. + :param base_uri: The base URI for resolution or relativization. + :param mode: Either 'abs' to get absolute URI or 'rel' to get relative URI. + """ + if mode not in ["abs", "rel"]: + return {"error": "mode must be 'abs' or 'rel'"} + + perl_code = """ + my $u = URI->new($ARGV[0]); + my $base = URI->new($ARGV[1]); + my $res = ($ARGV[2] eq 'abs') ? $u->abs($base) : $u->rel($base); + print encode_json({ result => $res->as_string }); + """ + result = _run_perl_uri(perl_code, [uri_str, base_uri, mode]) + if result["success"] and result["stdout"]: + result["data"] = json.loads(result["stdout"]) + return result + +@mcp.tool() +def uri_file_conversion( + path_or_uri: str, + to_uri: bool = True, + os: Optional[str] = None, + make_absolute: bool = False +) -> Dict[str, Any]: + """ + Converts between file system paths and file:// URIs. + + :param path_or_uri: The file path (if to_uri is True) or the file URI (if to_uri is False). + :param to_uri: If True, converts path to URI. If False, converts URI to path. + :param os: Optional OS type (e.g., 'Unix', 'Win32', 'Mac'). + :param make_absolute: If True and to_uri is True, creates an absolute file URI. + """ + if to_uri: + # Path to URI + perl_code = """ + my $u; + if ($ARGV[2] eq '1') { + $u = URI::file->new_abs($ARGV[0], $ARGV[1]); + } else { + $u = URI::file->new($ARGV[0], $ARGV[1]); + } + print encode_json({ uri => $u->as_string }); + """ + args = [path_or_uri, os if os else "", "1" if make_absolute else "0"] + else: + # URI to Path + perl_code = """ + my $u = URI->new($ARGV[0]); + my $path = $u->file($ARGV[1]); + print encode_json({ path => $path }); + """ + args = [path_or_uri, os if os else ""] + + result = _run_perl_uri(perl_code, args) + if result["success"] and result["stdout"]: + result["data"] = json.loads(result["stdout"]) + return result + +@mcp.tool() +def uri_query_params( + uri_str: str, + action: str = "get", + key: Optional[str] = None, + values: Optional[List[str]] = None +) -> Dict[str, Any]: + """ + Manages individual query parameters of a URI using URI::QueryParam. + + :param uri_str: The URI string. + :param action: 'get' (return values for key), 'set' (replace values for key), + 'append' (add values for key), 'delete' (remove key), + 'list_keys' (return all keys). + :param key: The parameter key to operate on. + :param values: List of values for 'set' or 'append' actions. + """ + perl_code = """ + my $u = URI->new($ARGV[0]); + my $action = $ARGV[1]; + my $key = $ARGV[2]; + my @vals = split('\\0', $ARGV[3] // ''); + + my %res; + if ($action eq 'get') { + my @v = $u->query_param($key); + $res{values} = \@v; + } elsif ($action eq 'set') { + $u->query_param($key, @vals); + $res{new_uri} = $u->as_string; + } elsif ($action eq 'append') { + $u->query_param_append($key, @vals); + $res{new_uri} = $u->as_string; + } elsif ($action eq 'delete') { + my @old = $u->query_param_delete($key); + $res{deleted_values} = \@old; + $res{new_uri} = $u->as_string; + } elsif ($action eq 'list_keys') { + my @keys = $u->query_param; + $res{keys} = \@keys; + } + print encode_json(\%res); + """ + val_str = "\0".join(values) if values else "" + args = [uri_str, action, key if key else "", val_str] + + result = _run_perl_uri(perl_code, args) + if result["success"] and result["stdout"]: + result["data"] = json.loads(result["stdout"]) + return result + +@mcp.tool() +def uri_query_form( + uri_str: str, + new_form: Optional[Dict[str, Union[str, List[str]]]] = None, + delimiter: str = "&" +) -> Dict[str, Any]: + """ + Sets or gets the entire query component as a form (application/x-www-form-urlencoded). + + :param uri_str: The URI string. + :param new_form: Optional dictionary to set as the new query form. + :param delimiter: Delimiter for the query string (usually '&' or ';'). + """ + perl_code = """ + my $u = URI->new($ARGV[0]); + my $json_form = $ARGV[1]; + my $delim = $ARGV[2] || '&'; + + my @old_form = $u->query_form; + + if ($json_form) { + my $hash = decode_json($json_form); + $u->query_form($hash, $delim); + } + + print encode_json({ + old_form => \@old_form, + current_uri => $u->as_string, + query_string => $u->query + }); + """ + form_json = json.dumps(new_form) if new_form else "" + result = _run_perl_uri(perl_code, [uri_str, form_json, delimiter]) + if result["success"] and result["stdout"]: + result["data"] = json.loads(result["stdout"]) + return result + +@mcp.tool() +def uri_server_info( + uri_str: str +) -> Dict[str, Any]: + """ + Extracts server-related components from the URI (authority, userinfo, host, port). + + :param uri_str: The URI string. + """ + perl_code = """ + my $u = URI->new($ARGV[0]); + my %res; + eval { + $res{authority} = $u->authority; + $res{userinfo} = $u->userinfo; + $res{host} = $u->host; + $res{ihost} = $u->ihost; + $res{port} = $u->port; + $res{host_port} = $u->host_port; + }; + if ($@) { + $res{error} = "Scheme does not support server methods: $@"; + } + print encode_json(\%res); + """ + result = _run_perl_uri(perl_code, [uri_str]) + if result["success"] and result["stdout"]: + result["data"] = json.loads(result["stdout"]) + return result + +@mcp.tool() +def uri_path_segments( + uri_str: str, + new_segments: Optional[List[str]] = None +) -> Dict[str, Any]: + """ + Gets or sets the path segments of a hierarchical URI. + + :param uri_str: The URI string. + :param new_segments: Optional list of segments to set. + """ + perl_code = """ + my $u = URI->new($ARGV[0]); + my $json_segs = $ARGV[1]; + + if ($json_segs) { + my $segs = decode_json($json_segs); + $u->path_segments(@$segs); + } + + my @current = $u->path_segments; + print encode_json({ + segments => \@current, + path => $u->path, + uri => $u->as_string + }); + """ + segs_json = json.dumps(new_segments) if new_segments else "" + result = _run_perl_uri(perl_code, [uri_str, segs_json]) + if result["success"] and result["stdout"]: + result["data"] = json.loads(result["stdout"]) + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/app/perl-uri_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/app/perl-uri_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6dc98dd02df74e611be035185568e18e1d521ec5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/app/perl-uri_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/app/perl-uri_server.py') +SERVER_NAME = 'biosci_perl_uri' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..96c8b30739f5a06fae2111e4baff5261c386c608 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-uri: + build: . + image: mcp-perl-uri:latest + container_name: mcp-perl-uri + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-uri + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c03c680d489684cca387a6ab52f48a0316e246a7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-uri + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-uri/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..359b1738eb16f881b7fe89a8c1fa4cb888618943 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-url-encode via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-url-encode -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-url-encode_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-url-encode_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-url-encode_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/app/perl-url-encode_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/app/perl-url-encode_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4dbf208fabe9f99dbb632f050068fa233e7633fd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/app/perl-url-encode_server.py @@ -0,0 +1,188 @@ +import subprocess +import json +from typing import Optional, Dict, List, Any +from pathlib import Path + +@mcp.tool() +def url_encode(text: str) -> Dict[str, Any]: + """ + Encodes a string into application/x-www-form-urlencoded format. + + Args: + text: The string to be URL encoded. + """ + cmd = ["perl", "-MURL::Encode=url_encode", "-e", "print url_encode($ARGV[0])", "--", text] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "encoded_string": result.stdout, + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def url_decode(text: str) -> Dict[str, Any]: + """ + Decodes an application/x-www-form-urlencoded encoded string. + + Args: + text: The URL encoded string to decode. + """ + cmd = ["perl", "-MURL::Encode=url_decode", "-e", "print url_decode($ARGV[0])", "--", text] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "decoded_string": result.stdout, + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def url_encode_utf8(text: str) -> Dict[str, Any]: + """ + Encodes a Unicode string into application/x-www-form-urlencoded format (UTF-8). + + Args: + text: The Unicode string to be URL encoded. + """ + cmd = ["perl", "-MURL::Encode=url_encode_utf8", "-e", "print url_encode_utf8($ARGV[0])", "--", text] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "encoded_string": result.stdout, + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def url_decode_utf8(text: str) -> Dict[str, Any]: + """ + Decodes an application/x-www-form-urlencoded encoded string into a Unicode string (UTF-8). + + Args: + text: The URL encoded string to decode. + """ + cmd = ["perl", "-MURL::Encode=url_decode_utf8", "-e", "print url_decode_utf8($ARGV[0])", "--", text] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "decoded_string": result.stdout, + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def url_params_decode(query_string: str) -> Dict[str, Any]: + """ + Decodes a URL query string into a key-value structure. + Note: Returns a list of pairs to handle multiple values for the same key. + + Args: + query_string: The query string (e.g., 'a=1&b=2&a=3'). + """ + # We use Perl to decode and then format as JSON for easy parsing in Python + perl_script = """ + use URL::Encode qw(url_params_decode); + use JSON; + my $params = url_params_decode($ARGV[0]); + print encode_json($params); + """ + cmd = ["perl", "-MURL::Encode", "-MJSON", "-e", perl_script, "--", query_string] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "decoded_params": json.loads(result.stdout), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + except json.JSONDecodeError: + return { + "command_executed": " ".join(cmd), + "error": "Failed to parse Perl output as JSON. Ensure 'perl-json' is installed.", + "stdout": result.stdout, + "stderr": result.stderr + } + +@mcp.tool() +def url_params_encode(params_json: str) -> Dict[str, Any]: + """ + Encodes a JSON object/dictionary of key-value pairs into a URL query string. + + Args: + params_json: A JSON string representing the dictionary of parameters to encode. + Example: '{"name": "John Doe", "city": "New York"}' + """ + # Validate JSON input + try: + json.loads(params_json) + except json.JSONDecodeError as e: + return {"error": f"Invalid JSON input: {str(e)}"} + + perl_script = """ + use URL::Encode qw(url_params_encode); + use JSON; + my $hashref = decode_json($ARGV[0]); + print url_params_encode($hashref); + """ + cmd = ["perl", "-MURL::Encode", "-MJSON", "-e", perl_script, "--", params_json] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "encoded_query_string": result.stdout, + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/app/perl-url-encode_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/app/perl-url-encode_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9cae2bdaa84b07014e5a0c306770eeee25ee7930 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/app/perl-url-encode_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/app/perl-url-encode_server.py') +SERVER_NAME = 'biosci_perl_url_encode' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4f270e3e4c23542022656c19ca62d7744ab19285 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-url-encode: + build: . + image: mcp-perl-url-encode:latest + container_name: mcp-perl-url-encode + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-url-encode + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b1b6523a0cc50970804c1a7b5a3150a2155a7203 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-url-encode + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-url-encode/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c3c92b834128ce0f0b432f07ef90b6df89edabbd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-version via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-version -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-version_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-version_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-version_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/app/perl-version_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/app/perl-version_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5c49a1c3ba81d46132abb40773455bd1a8726106 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/app/perl-version_server.py @@ -0,0 +1,250 @@ +import subprocess +from typing import Optional, Dict, Any, List + +@mcp.tool() +def perl_version_parse( + version_string: str, +) -> Dict[str, Any]: + """ + Parses a version string into a structured version object using Perl's version->parse(). + This is the most flexible way to create a version object. + + Args: + version_string: The version string to parse (e.g., '1.2.3', 'v1.2', '1.002003'). + """ + if not version_string: + return {"error": "version_string cannot be empty"} + + # Perl code to parse and print the stringified version object + perl_code = 'eval { my $v = version->parse($ARGV[0]); print $v }; if ($@) { warn $@; exit 1; }' + cmd = ["perl", "-Mversion", "-e", perl_code, "--", version_string] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "parsed_version": result.stdout.strip(), + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "error": f"Failed to parse version string: {version_string}", + "output_files": [] + } + +@mcp.tool() +def perl_version_declare( + version_string: str, +) -> Dict[str, Any]: + """ + Creates a version object using Perl's version->declare(). + This is typically used to ensure a version is treated as a v-string (dotted-decimal). + + Args: + version_string: The version string to declare (e.g., '1.2.3'). + """ + if not version_string: + return {"error": "version_string cannot be empty"} + + perl_code = 'eval { my $v = version->declare($ARGV[0]); print $v }; if ($@) { warn $@; exit 1; }' + cmd = ["perl", "-Mversion", "-e", perl_code, "--", version_string] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "declared_version": result.stdout.strip(), + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "error": f"Failed to declare version string: {version_string}", + "output_files": [] + } + +@mcp.tool() +def perl_version_numify( + version_string: str, +) -> Dict[str, Any]: + """ + Returns the numeric representation (floating point) of a version string. + Example: 'v1.2.3' becomes '1.002003'. + + Args: + version_string: The version string to numify. + """ + if not version_string: + return {"error": "version_string cannot be empty"} + + perl_code = 'eval { my $v = version->parse($ARGV[0]); print $v->numify }; if ($@) { warn $@; exit 1; }' + cmd = ["perl", "-Mversion", "-e", perl_code, "--", version_string] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "numified_version": result.stdout.strip(), + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "error": f"Failed to numify version string: {version_string}", + "output_files": [] + } + +@mcp.tool() +def perl_version_normal( + version_string: str, +) -> Dict[str, Any]: + """ + Returns the normalized dotted-decimal representation of a version string. + Example: '1.2' becomes 'v1.200.0'. + + Args: + version_string: The version string to normalize. + """ + if not version_string: + return {"error": "version_string cannot be empty"} + + perl_code = 'eval { my $v = version->parse($ARGV[0]); print $v->normal }; if ($@) { warn $@; exit 1; }' + cmd = ["perl", "-Mversion", "-e", perl_code, "--", version_string] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "normalized_version": result.stdout.strip(), + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "error": f"Failed to normalize version string: {version_string}", + "output_files": [] + } + +@mcp.tool() +def perl_version_is_alpha( + version_string: str, +) -> Dict[str, Any]: + """ + Checks if a version string is considered an alpha release (contains an underscore). + + Args: + version_string: The version string to check. + """ + if not version_string: + return {"error": "version_string cannot be empty"} + + perl_code = 'eval { my $v = version->parse($ARGV[0]); print $v->is_alpha ? "true" : "false" }; if ($@) { warn $@; exit 1; }' + cmd = ["perl", "-Mversion", "-e", perl_code, "--", version_string] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "is_alpha": result.stdout.strip() == "true", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "error": f"Failed to check alpha status for: {version_string}", + "output_files": [] + } + +@mcp.tool() +def perl_version_is_qv( + version_string: str, +) -> Dict[str, Any]: + """ + Checks if a version string was parsed as a "quoted version" (v-string). + + Args: + version_string: The version string to check. + """ + if not version_string: + return {"error": "version_string cannot be empty"} + + perl_code = 'eval { my $v = version->parse($ARGV[0]); print $v->is_qv ? "true" : "false" }; if ($@) { warn $@; exit 1; }' + cmd = ["perl", "-Mversion", "-e", perl_code, "--", version_string] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "is_qv": result.stdout.strip() == "true", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "error": f"Failed to check qv status for: {version_string}", + "output_files": [] + } + +@mcp.tool() +def perl_version_compare( + v1: str, + v2: str, +) -> Dict[str, Any]: + """ + Compares two version strings using Perl's version comparison logic. + Returns 1 if v1 > v2, -1 if v1 < v2, and 0 if they are equal. + + Args: + v1: The first version string. + v2: The second version string. + """ + if not v1 or not v2: + return {"error": "Both v1 and v2 must be provided"} + + perl_code = 'eval { my $obj1 = version->parse($ARGV[0]); my $obj2 = version->parse($ARGV[1]); print $obj1 <=> $obj2 }; if ($@) { warn $@; exit 1; }' + cmd = ["perl", "-Mversion", "-e", perl_code, "--", v1, v2] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + comparison_result = int(result.stdout.strip()) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "comparison_result": comparison_result, + "interpretation": "v1 > v2" if comparison_result > 0 else ("v1 < v2" if comparison_result < 0 else "v1 == v2"), + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "error": f"Failed to compare versions: {v1} and {v2}", + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/app/perl-version_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/app/perl-version_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2a1b89604b737cbcece86125bdcd1428fec163c8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/app/perl-version_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/app/perl-version_server.py') +SERVER_NAME = 'biosci_perl_version' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..39c75c4464e0c8d5726d15a8fc1d9704d7732fcc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-version: + build: . + image: mcp-perl-version:latest + container_name: mcp-perl-version + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-version + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3000a31cd98c1304e99cb3a989389a0fea9d05b6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-version + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-version/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..25a0db90f0ee86f710258070adcbaecd574ff13d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-www-robotrules via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-www-robotrules -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-www-robotrules_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-www-robotrules_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-www-robotrules_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/app/perl-www-robotrules_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/app/perl-www-robotrules_server.py new file mode 100644 index 0000000000000000000000000000000000000000..af8b795a8e1e8eb8b02c5c1532d2ba921c940a98 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/app/perl-www-robotrules_server.py @@ -0,0 +1,181 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict, Any + +@mcp.tool() +def check_robots_url_allowed( + robots_txt_content: str, + user_agent: str, + url_to_check: str, + base_url: str = "http://localhost", +) -> Dict[str, Any]: + """ + Checks if a specific URL is allowed for a given user agent based on robots.txt content + using the Perl WWW::RobotRules module. + + Args: + robots_txt_content: The raw text content of the robots.txt file. + user_agent: The name of the robot/user-agent to check (e.g., 'Googlebot'). + url_to_check: The full URL or path to check for access permissions. + base_url: The base URL where the robots.txt is hosted (required by the parser). + """ + # Input validation + if not robots_txt_content.strip(): + return {"error": "robots_txt_content cannot be empty"} + if not user_agent.strip(): + return {"error": "user_agent cannot be empty"} + if not url_to_check.strip(): + return {"error": "url_to_check cannot be empty"} + + # Create a temporary file for the robots.txt content to avoid shell escaping issues + with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as tmp: + tmp.write(robots_txt_content) + tmp_path = tmp.name + + # Construct the Perl script + # WWW::RobotRules->new($ua_name) + # $rules->parse($base_url, $content) + # $rules->allowed($url) + perl_script = f""" +use WWW::RobotRules; +my $ua = '{user_agent}'; +my $base = '{base_url}'; +my $url = '{url_to_check}'; +my $rules = WWW::RobotRules->new($ua); + +open(my $fh, '<', '{tmp_path}') or die "Could not open temp file: $!"; +my $content = do {{ local $/; <$fh> }}; +close($fh); + +$rules->parse($base, $content); +if ($rules->allowed($url)) {{ + print "ALLOWED"; +}} else {{ + print "DISALLOWED"; +}} +""" + + try: + result = subprocess.run( + ["perl", "-e", perl_script], + capture_output=True, + text=True, + check=True + ) + + is_allowed = result.stdout.strip() == "ALLOWED" + + return { + "command_executed": f"perl -e 'WWW::RobotRules->allowed(...)'", + "is_allowed": is_allowed, + "status": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Perl execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + finally: + # Cleanup + if Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def check_robots_url_allowed_from_file( + robots_txt_path: str, + user_agent: str, + url_to_check: str, + base_url: str = "http://localhost", +) -> Dict[str, Any]: + """ + Checks if a specific URL is allowed for a given user agent using a local robots.txt file. + + Args: + robots_txt_path: Path to the local robots.txt file. + user_agent: The name of the robot/user-agent to check. + url_to_check: The full URL or path to check for access permissions. + base_url: The base URL where the robots.txt is conceptually hosted. + """ + path_obj = Path(robots_txt_path) + if not path_obj.exists(): + return {"error": f"File not found: {robots_txt_path}"} + + try: + content = path_obj.read_text() + return check_robots_url_allowed( + robots_txt_content=content, + user_agent=user_agent, + url_to_check=url_to_check, + base_url=base_url + ) + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def get_robots_txt_agent_string( + user_agent: str +) -> Dict[str, Any]: + """ + Returns the agent string that the WWW::RobotRules parser will use for identification. + This is useful for verifying how the Perl module identifies your crawler. + + Args: + user_agent: The name of the robot/user-agent. + """ + perl_script = f""" +use WWW::RobotRules; +my $rules = WWW::RobotRules->new('{user_agent}'); +print $rules->agent(); +""" + try: + result = subprocess.run( + ["perl", "-e", perl_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "perl -e 'WWW::RobotRules->agent()'", + "agent_string": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Perl execution failed", + "stderr": e.stderr + } + +@mcp.tool() +def validate_perl_robotrules_environment() -> Dict[str, Any]: + """ + Verifies that Perl and the WWW::RobotRules module are correctly installed in the environment. + """ + perl_script = "use WWW::RobotRules; print 'OK';" + try: + result = subprocess.run( + ["perl", "-e", perl_script], + capture_output=True, + text=True, + check=True + ) + return { + "status": "Ready", + "module_found": result.stdout.strip() == "OK", + "perl_version": subprocess.run(["perl", "-v"], capture_output=True, text=True).stdout.splitlines()[1] + } + except subprocess.CalledProcessError: + return { + "status": "Error", + "message": "WWW::RobotRules module not found. Please install perl-www-robotrules." + } + except FileNotFoundError: + return { + "status": "Error", + "message": "Perl interpreter not found in PATH." + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/app/perl-www-robotrules_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/app/perl-www-robotrules_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e1e8a5864e8def63072f293dfa6607483fd058c4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/app/perl-www-robotrules_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/app/perl-www-robotrules_server.py') +SERVER_NAME = 'biosci_perl_www_robotrules' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e92d138122bf09afea98701d4914441bb0abd469 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-www-robotrules: + build: . + image: mcp-perl-www-robotrules:latest + container_name: mcp-perl-www-robotrules + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-www-robotrules + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ec69db11a386bcf3fea1cf062fd0d0117813066c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-www-robotrules + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom-xpath/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom-xpath/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom-xpath/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1c65f47840946cbd317ba6c8817b18d5704dcd8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-xml-dom via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-xml-dom -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-xml-dom_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-xml-dom_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-xml-dom_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/app/perl-xml-dom_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/app/perl-xml-dom_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b37257303a34dfeeeb1b2bf038c6fbb5387fe6be --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/app/perl-xml-dom_server.py @@ -0,0 +1,233 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# No need to import mcp, as per instructions. + +@mcp.tool() +def execute_perl_script( + program_file: Optional[Path] = None, + script_arguments: Optional[List[str]] = None, + record_separator: Optional[str] = None, + autosplit_mode: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + run_debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + execute_program_lines: Optional[List[str]] = None, + execute_program_lines_with_features: Optional[List[str]] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing_terminator: Optional[str] = None, + use_modules: Optional[List[str]] = None, + no_modules: Optional[List[str]] = None, + assume_while_loop: bool = False, + assume_while_loop_and_print: bool = False, + enable_rudimentary_parsing_for_switches: bool = False, + look_for_programfile_in_path: bool = False, + enable_tainting_warnings: bool = False, + enable_tainting_checks: bool = False, + dump_core_after_parsing: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary_variable: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang_directory: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> Dict[str, Any]: + """ + Executes a Perl script or one-liner with various command-line options. + + This function wraps the 'perl' interpreter, allowing execution of Perl scripts + and one-liners with a comprehensive set of available switches. It can be used + to run scripts that utilize Perl modules like XML::DOM (which is a dependency + of the 'perl-xml-dom' package). + + Args: + program_file: Path to the Perl script file to execute. If one or more + `execute_program_lines` or `execute_program_lines_with_features` + are provided, this can be omitted. + script_arguments: A list of arguments to pass to the Perl script itself. + record_separator: Specify the input record separator. If no argument is + provided (pass an empty string ""), it defaults to '\0'. + Provide as an octal string (e.g., '0' for '\0', '0777'). + autosplit_mode: Enable autosplit mode with -n or -p (splits $_ into @F). + unicode_features: Enables listed Unicode features. Can be a number or a list + of feature names (e.g., 'all', 'io', '5.18'). + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks) without executing. + run_debugger: Run the program under the Perl debugger. Optionally specify + a debugger type (e.g., 'ptkdb'). + debugging_flags: Set debugging flags. Argument is a bit mask (number) or + alphabets (e.g., 't' for trace, 's' for subroutine call/return). + execute_program_lines: One or more lines of Perl program code to execute. + Each string in the list corresponds to a separate '-e' switch. + execute_program_lines_with_features: Like -e, but enables all optional features + (e.g., strict, warnings, say, state). + Each string in the list corresponds to a separate '-E' switch. + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. + split_pattern: The pattern for split() when -a switch is enabled (e.g., '/\s+/'). + The slashes are optional in the CLI, but should be included if desired. + edit_in_place_extension: Edit <> files in place. If an extension is supplied + (e.g., '.bak'), a backup file will be created. + Pass an empty string "" for no backup. + include_directories: A list of directories to add to @INC for module searching. + Each path in the list corresponds to a separate '-I' switch. + line_ending_processing_terminator: Enable line ending processing. Specifies the + line terminator. Provide as an octal string. + If no argument (pass empty string ""), it uses the current value of $/. + use_modules: A list of modules to 'use' before executing the program. + Each string in the list corresponds to a separate '-M' switch. + no_modules: A list of modules to 'no' (disable) before executing the program. + Each string in the list corresponds to a separate '-M-' switch. + assume_while_loop: Assume "while (<>) { ... }" loop around the program. + assume_while_loop_and_print: Assume loop like -n but print line also, similar to 'sed'. + enable_rudimentary_parsing_for_switches: Enable rudimentary parsing for switches + after the program file name. + look_for_programfile_in_path: Look for the program file using the PATH environment variable. + enable_tainting_warnings: Enable tainting warnings. + enable_tainting_checks: Enable tainting checks (implies -t). + dump_core_after_parsing: Dump core after parsing the program. + allow_unsafe_operations: Allow unsafe operations (e.g., unlink directories). + print_version: Print Perl version, patchlevel, and license information. + print_config_summary_variable: Print configuration summary (like 'perl -V') + or a single Config.pm variable (e.g., 'archname'). + enable_warnings: Enable many useful warnings (equivalent to 'use warnings;'). + enable_all_warnings: Enable all warnings (more verbose than -w). + ignore_text_before_shebang_directory: Ignore text before the #!perl line. + Optionally change to the specified directory first. + disable_all_warnings: Disable all warnings (equivalent to 'no warnings;'). + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + # Initialize mutable default arguments + script_arguments = script_arguments if script_arguments is not None else [] + execute_program_lines = execute_program_lines if execute_program_lines is not None else [] + execute_program_lines_with_features = execute_program_lines_with_features if execute_program_lines_with_features is not None else [] + include_directories = include_directories if include_directories is not None else [] + use_modules = use_modules if use_modules is not None else [] + no_modules = no_modules if no_modules is not None else [] + + # Input validation + if program_file: + if not program_file.is_file(): + raise ValueError(f"Program file not found or is not a file: {program_file}") + + for d in include_directories: + if not d.is_dir(): + raise ValueError(f"Include directory not found or is not a directory: {d}") + + if ignore_text_before_shebang_directory: + if not ignore_text_before_shebang_directory.is_dir(): + raise ValueError( + f"Ignore text before shebang directory not found or is not a directory: " + f"{ignore_text_before_shebang_directory}" + ) + + cmd = ["perl"] + + # Construct command based on provided arguments + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit_mode: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if run_debugger is not None: + cmd.append(f"-d:{run_debugger}") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + for line in execute_program_lines: + cmd.extend(["-e", line]) + for line in execute_program_lines_with_features: + cmd.extend(["-E", line]) + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + cmd.append(f"-i{edit_in_place_extension}") + for d in include_directories: + cmd.extend(["-I", str(d)]) + if line_ending_processing_terminator is not None: + cmd.append(f"-l{line_ending_processing_terminator}") + for module in use_modules: + cmd.extend(["-M", module]) # Use -M for 'use module' + for module in no_modules: + cmd.extend(["-M-", module]) # Use -M- for 'no module' + if assume_while_loop: + cmd.append("-n") + if assume_while_loop_and_print: + cmd.append("-p") + if enable_rudimentary_parsing_for_switches: + cmd.append("-s") + if look_for_programfile_in_path: + cmd.append("-S") + if enable_tainting_warnings: + cmd.append("-t") + if enable_tainting_checks: + cmd.append("-T") + if dump_core_after_parsing: + cmd.append("-u") + if allow_unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config_summary_variable is not None: + cmd.append(f"-V:{print_config_summary_variable}") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if ignore_text_before_shebang_directory is not None: + cmd.append(f"-x{ignore_text_before_shebang_directory}") + if disable_all_warnings: + cmd.append("-X") + + # Add program file and its arguments + if program_file: + cmd.append(str(program_file)) + + cmd.extend(script_arguments) + + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + command_executed = " ".join(cmd) + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'perl' command not found. Is Perl installed and in your PATH?", + "error": "Perl executable not found.", + "returncode": 127, + "output_files": [], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/app/perl-xml-dom_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/app/perl-xml-dom_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e7a49df5402b3e255b0fb29f9410cd61a58dc445 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/app/perl-xml-dom_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/app/perl-xml-dom_server.py') +SERVER_NAME = 'biosci_perl_xml_dom' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3b2631a3efb1728e5c303e147530908304139631 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-xml-dom: + build: . + image: mcp-perl-xml-dom:latest + container_name: mcp-perl-xml-dom + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-xml-dom + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..388dd92e379ca6c6c0788e67dc5766ff88a19d64 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-xml-dom + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-dom/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..526415173f2b617c51918aef3bbd0ad6bdb17881 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-xml-filter-buffertext via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-xml-filter-buffertext -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-xml-filter-buffertext_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-xml-filter-buffertext_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-xml-filter-buffertext_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/app/perl-xml-filter-buffertext_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/app/perl-xml-filter-buffertext_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5615b28f62900e04f8ff37a3e93bf498fb980c4a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/app/perl-xml-filter-buffertext_server.py @@ -0,0 +1,230 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# No need to import mcp, as per instructions. + +@mcp.tool() +def run_perl_xml_filter_buffertext( + input_xml: Path, + output_xml: Path, + record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debug_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + additional_modules_to_load: Optional[List[str]] = None, + rudimentary_switch_parsing: bool = False, + search_path_for_program: bool = False, + enable_tainting_warnings: bool = False, + enable_tainting_checks: bool = False, + dump_core_on_parse_error: bool = False, + allow_unsafe_operations: bool = False, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + ignore_text_before_perl: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Processes an XML file using the perl-xml-filter-buffertext module to buffer + character data events. + + This tool wraps the Perl interpreter to execute a dynamically generated script + that utilizes XML::Filter::BufferText and XML::SAX::Writer. It reads an input + XML file, applies the buffering filter, and writes the processed XML to an + output file. Various Perl interpreter options are exposed for fine-grained + control over the execution environment of the generated script. + + Args: + input_xml: Path to the input XML file to be filtered. + output_xml: Path where the filtered XML output will be written. + record_separator: Specifies the input record separator (e.g., '\\0'). Corresponds to perl -0. + autosplit: Enables autosplit mode with -n or -p (splits $_ into @F). Corresponds to perl -a. + unicode_features: Enables listed Unicode features (e.g., 'all', 'io'). Corresponds to perl -C. + check_syntax_only: Checks syntax only (runs BEGIN and CHECK blocks) for the generated script. Corresponds to perl -c. + debugger: Runs the program under the specified debugger. Corresponds to perl -d[:debugger]. + debug_flags: Sets debugging flags (argument is a bit mask or alphabets). Corresponds to perl -D. + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. Corresponds to perl -f. + split_pattern: Specifies the split() pattern for -a switch (e.g., '/\s+/'). Corresponds to perl -F. + include_directories: List of directories to add to @INC for module searching. Corresponds to perl -I. + line_ending_processing: Enables line ending processing, specifies line terminator (e.g., '\\n'). Corresponds to perl -l. + additional_modules_to_load: List of additional modules to execute "use/no module..." before program. Corresponds to perl -m/-M. + rudimentary_switch_parsing: Enables rudimentary parsing for switches after programfile. Corresponds to perl -s. + search_path_for_program: Looks for programfile using PATH environment variable. Corresponds to perl -S. + enable_tainting_warnings: Enables tainting warnings. Corresponds to perl -t. + enable_tainting_checks: Enables tainting checks. Corresponds to perl -T. + dump_core_on_parse_error: Dumps core after parsing program. Corresponds to perl -u. + allow_unsafe_operations: Allows unsafe operations. Corresponds to perl -U. + enable_warnings: Enables many useful warnings (-w). Mutually exclusive with enable_all_warnings and disable_all_warnings. + enable_all_warnings: Enables all warnings (-W). Mutually exclusive with enable_warnings and disable_all_warnings. + disable_all_warnings: Disables all warnings (-X). Mutually exclusive with enable_warnings and enable_all_warnings. + ignore_text_before_perl: Ignores text before #!perl line (optionally cd to directory). Corresponds to perl -x. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # 1. Input validation + if not input_xml.is_file(): + raise FileNotFoundError(f"Input XML file not found: {input_xml}") + + # Ensure output directory exists + output_xml.parent.mkdir(parents=True, exist_ok=True) + + # Validate mutually exclusive warning flags + warning_flags_count = sum([enable_warnings, enable_all_warnings, disable_all_warnings]) + if warning_flags_count > 1: + raise ValueError("Only one of -w, -W, or -X (enable_warnings, enable_all_warnings, disable_all_warnings) can be specified.") + + # Validate include_directories + if include_directories: + for d in include_directories: + if not d.is_dir(): + raise NotADirectoryError(f"Include directory not found: {d}") + + # Validate ignore_text_before_perl directory + if ignore_text_before_perl is not None and not ignore_text_before_perl.is_dir(): + raise NotADirectoryError(f"Directory for -x option not found: {ignore_text_before_perl}") + + command = ["perl"] + + # Add perl interpreter options based on parameters + if record_separator is not None: + command.append(f"-0{record_separator}") + if autosplit: + command.append("-a") + if unicode_features is not None: + command.append(f"-C{unicode_features}") + if check_syntax_only: + command.append("-c") + if debugger is not None: + command.append(f"-d:{debugger}") + if debug_flags is not None: + command.append(f"-D{debug_flags}") + if no_sitecustomize: + command.append("-f") + if split_pattern is not None: + command.append(f"-F{split_pattern}") + if include_directories: + for d in include_directories: + command.append(f"-I{d}") + if line_ending_processing is not None: + command.append(f"-l{line_ending_processing}") + + # Add additional modules specified by the user via -M + if additional_modules_to_load: + for module in additional_modules_to_load: + command.append(f"-M{module}") + + if rudimentary_switch_parsing: + command.append("-s") + if search_path_for_program: + command.append("-S") + if enable_tainting_warnings: + command.append("-t") + if enable_tainting_checks: + command.append("-T") + if dump_core_on_parse_error: + command.append("-u") + if allow_unsafe_operations: + command.append("-U") + if enable_warnings: + command.append("-w") + if enable_all_warnings: + command.append("-W") + if disable_all_warnings: + command.append("-X") + if ignore_text_before_perl is not None: + command.append(f"-x{ignore_text_before_perl}") + + # 2. Create a temporary Perl script to use XML::Filter::BufferText + # The script explicitly uses 'strict' for good practice. + # 'warnings' is omitted from the script to allow CLI flags (-w, -W, -X) + # to fully control warning behavior without potential conflicts. + perl_script_content = f""" + use strict; + use XML::SAX::ParserFactory; + use XML::Filter::BufferText; + use XML::SAX::Writer; + + my $input_file = shift @ARGV; + my $output_file = shift @ARGV; + + die "Usage: $0 \\n" unless defined $input_file && defined $output_file; + + open my $OUT, '>', $output_file or die "Cannot open $output_file: $!\\n"; + + my $writer = XML::SAX::Writer->new( Output => $OUT ); + my $filter = XML::Filter::BufferText->new( Handler => $writer ); + my $parser = XML::SAX::ParserFactory->parser( Handler => $filter ); + + eval {{ + $parser->parse_uri($input_file); + }}; + if ($@) {{ + warn "Error parsing XML: $@\\n"; + exit 1; + }} + + close $OUT; + exit 0; + """ + + stdout = "" + stderr = "" + output_files: List[Path] = [] + temp_script_path: Optional[Path] = None + + try: + # Write the Perl script to a temporary file + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".pl") as temp_script_file: + temp_script_file.write(perl_script_content) + temp_script_path = Path(temp_script_file.name) + + # Append the temporary script path and input/output files as arguments + command.append(str(temp_script_path)) + command.append(str(input_xml)) + command.append(str(output_xml)) + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, # Raise CalledProcessError for non-zero exit codes + ) + stdout = process.stdout + stderr = process.stderr + output_files.append(output_xml) + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl command failed with exit code {e.returncode}", + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'perl' command not found. Is Perl installed and in your PATH?", + "error": "Perl interpreter not found.", + "output_files": [], + } + finally: + # Clean up the temporary script file + if temp_script_path and temp_script_path.exists(): + temp_script_path.unlink() + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/app/perl-xml-filter-buffertext_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/app/perl-xml-filter-buffertext_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8b299a761b7bbf3b09c1e9e8dcaacc23b3e6d465 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/app/perl-xml-filter-buffertext_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/app/perl-xml-filter-buffertext_server.py') +SERVER_NAME = 'biosci_perl_xml_filter_buffertext' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b1b6b4fbb25dd74912cfa05f98b1abecbfff9b18 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-xml-filter-buffertext: + build: . + image: mcp-perl-xml-filter-buffertext:latest + container_name: mcp-perl-xml-filter-buffertext + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-xml-filter-buffertext + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..679261cb5ca0f826a1f653e7d9eadadc285fd2e6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-xml-filter-buffertext + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-filter-buffertext/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0a7aca7ccbcc120265bc3debc46dd9557889966b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-xml-libxml via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-xml-libxml -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-xml-libxml_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-xml-libxml_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-xml-libxml_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/app/perl-xml-libxml_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/app/perl-xml-libxml_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1f5b6a370ab96e88c4bd3baf5dfe954e7bb46de7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/app/perl-xml-libxml_server.py @@ -0,0 +1,268 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union + +@mcp.tool() +def perl_xml_libxml_validate( + xml_path: str, + schema_path: Optional[str] = None, + schema_type: str = "xsd", +): + """ + Validates an XML file using perl-xml-libxml. Can check for well-formedness or + validate against an XSD or DTD. + + Args: + xml_path: Path to the XML file to validate. + schema_path: Optional path to a schema file (XSD or DTD). + schema_type: Type of schema provided ('xsd' or 'dtd'). Defaults to 'xsd'. + """ + xml_file = Path(xml_path) + if not xml_file.exists(): + return {"error": f"XML file not found: {xml_path}"} + + # Construct Perl one-liner for validation + perl_script = [ + "use XML::LibXML;", + "my $xml = shift;", + "my $schema_file = shift;", + "my $type = shift;", + "my $parser = XML::LibXML->new();", + "eval {", + " if ($schema_file) {", + " if ($type eq 'xsd') {", + " my $schema = XML::LibXML::Schema->new(location => $schema_file);", + " my $doc = $parser->parse_file($xml);", + " $schema->validate($doc);", + " } elsif ($type eq 'dtd') {", + " $parser->validation(1);", + " $parser->parse_file($xml);", + " }", + " } else {", + " $parser->parse_file($xml);", + " }", + "};", + "if ($@) { die \"Validation failed: $@\"; } else { print \"Validation successful\\n\"; }", + ] + + cmd = ["perl", "-MXML::LibXML", "-e", "".join(perl_script), str(xml_file)] + if schema_path: + s_path = Path(schema_path) + if not s_path.exists(): + return {"error": f"Schema file not found: {schema_path}"} + cmd.append(str(s_path)) + cmd.append(schema_type) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Validation failed" + } + +@mcp.tool() +def perl_xml_libxml_xpath( + xml_path: str, + expression: str, + output_format: str = "string", +): + """ + Extracts data from an XML file using an XPath expression via XML::LibXML. + + Args: + xml_path: Path to the XML file. + expression: XPath expression to evaluate. + output_format: How to return results ('string' for text content, 'xml' for raw XML nodes). + """ + xml_file = Path(xml_path) + if not xml_file.exists(): + return {"error": f"XML file not found: {xml_path}"} + + # Construct Perl one-liner for XPath + perl_script = [ + "use XML::LibXML;", + "my $xml = shift;", + "my $xpath = shift;", + "my $fmt = shift;", + "my $dom = XML::LibXML->load_xml(location => $xml);", + "for my $node ($dom->findnodes($xpath)) {", + " if ($fmt eq 'xml') { print $node->toString(), \"\\n\"; }", + " else { print $node->textContent(), \"\\n\"; }", + "}" + ] + + cmd = ["perl", "-MXML::LibXML", "-e", "".join(perl_script), str(xml_file), expression, output_format] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "results": result.stdout.splitlines() + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "XPath query failed" + } + +@mcp.tool() +def perl_xml_libxml_format( + xml_path: str, + indent: int = 1, + no_blanks: bool = True, +): + """ + Pretty-prints/formats an XML file using XML::LibXML. + + Args: + xml_path: Path to the XML file to format. + indent: Indentation level (0, 1, or 2). Defaults to 1. + no_blanks: If True, removes existing whitespace before re-formatting. Defaults to True. + """ + xml_file = Path(xml_path) + if not xml_file.exists(): + return {"error": f"XML file not found: {xml_path}"} + + if indent < 0 or indent > 2: + return {"error": "Indent must be 0, 1, or 2"} + + blanks_flag = 1 if no_blanks else 0 + + perl_script = [ + "use XML::LibXML;", + "my $xml = shift;", + "my $ind = shift;", + "my $nb = shift;", + "my $dom = XML::LibXML->load_xml(location => $xml, no_blanks => $nb);", + "print $dom->toString($ind);" + ] + + cmd = ["perl", "-MXML::LibXML", "-e", "".join(perl_script), str(xml_file), str(indent), str(blanks_flag)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "formatted_xml": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Formatting failed" + } + +@mcp.tool() +def perl_xml_libxml_execute( + script_path: Optional[str] = None, + one_liner: Optional[str] = None, + input_files: Optional[List[str]] = None, + warnings: bool = True, + taint_check: bool = False, + include_dirs: Optional[List[str]] = None, + autosplit: bool = False, + loop_n: bool = False, + loop_p: bool = False, +): + """ + General purpose Perl execution tool with XML::LibXML pre-loaded. + Allows running custom scripts or one-liners that utilize the library. + + Args: + script_path: Path to a .pl script to execute. + one_liner: A string containing Perl code to execute (equivalent to -e). + input_files: List of files to pass as arguments to the script. + warnings: Enable many useful warnings (-w). Defaults to True. + taint_check: Enable tainting checks (-T). Defaults to False. + include_dirs: List of directories to add to @INC (-I). + autosplit: Enable autosplit mode (-a) with -n or -p. + loop_n: Assume "while (<>) { ... }" loop around program (-n). + loop_p: Assume loop like -n but print line also (-p). + """ + cmd = ["perl", "-MXML::LibXML"] + + if warnings: + cmd.append("-w") + if taint_check: + cmd.append("-T") + if autosplit: + cmd.append("-a") + if loop_n: + cmd.append("-n") + if loop_p: + cmd.append("-p") + + if include_dirs: + for d in include_dirs: + cmd.extend(["-I", d]) + + if one_liner: + cmd.extend(["-e", one_liner]) + elif script_path: + s_path = Path(script_path) + if not s_path.exists(): + return {"error": f"Script not found: {script_path}"} + cmd.append(str(s_path)) + else: + return {"error": "Either script_path or one_liner must be provided."} + + if input_files: + for f in input_files: + f_path = Path(f) + if f_path.exists(): + cmd.append(str(f_path)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "exit_code": e.returncode, + "error": "Perl execution failed" + } + +@mcp.tool() +def perl_xml_libxml_info(): + """ + Returns version information for the perl-xml-libxml installation and the underlying libxml2 library. + """ + perl_script = "use XML::LibXML; printf('XML::LibXML Version: %s\\nLibXML2 Version: %s\\n', $XML::LibXML::VERSION, XML::LibXML::LIBXML_DOTTED_VERSION);" + cmd = ["perl", "-e", perl_script] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to retrieve version info" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/app/perl-xml-libxml_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/app/perl-xml-libxml_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..41ec9b8ff7e8ff11fd724e67ce476991644beda5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/app/perl-xml-libxml_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/app/perl-xml-libxml_server.py') +SERVER_NAME = 'biosci_perl_xml_libxml' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..1414450d5cab98c47adcf029be3d8009ab5161cb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-xml-libxml: + build: . + image: mcp-perl-xml-libxml:latest + container_name: mcp-perl-xml-libxml + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-xml-libxml + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8f9a178635543090a48cafd5b83741825cb5031f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-xml-libxml + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxml/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..67ab6c07121fa7bf1035ad5937122f5f07121c8d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-xml-libxslt via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-xml-libxslt -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-xml-libxslt_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-xml-libxslt_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-xml-libxslt_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/app/perl-xml-libxslt_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/app/perl-xml-libxslt_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5b4f61fa0efd0600d6c40fd78486b5bbd93fb49f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/app/perl-xml-libxslt_server.py @@ -0,0 +1,189 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict, List, Literal + +@mcp.tool() +def transform_xml_with_libxslt( + xml_input_file: Path, + xslt_stylesheet_file: Path, + output_file: Path, + xslt_parameters: Optional[Dict[str, str]] = None, + max_recursion_depth: Optional[int] = None, + max_variables: Optional[int] = None, + output_method: Literal["bytes", "chars"] = "bytes", + enable_perl_warnings: bool = False, + enable_perl_taint_checks: bool = False, +) -> Dict[str, any]: + """ + Performs an XSLT transformation using the perl-xml-libxslt module. + + This tool wraps the XML::LibXSLT Perl module to apply an XSLT stylesheet + to an XML input file, producing an output file. It generates a temporary + Perl script to execute the transformation. + + Args: + xml_input_file: Path to the input XML file. Must exist. + xslt_stylesheet_file: Path to the XSLT stylesheet file. Must exist. + output_file: Path to the desired output file. The parent directory + will be created if it doesn't exist. + xslt_parameters: A dictionary of parameters to pass to the XSLT stylesheet. + Keys are parameter names, values are strings. The tool + will use `XML::LibXSLT::xpath_to_string` for proper + XPath quoting of these values within the Perl script. + max_recursion_depth: Sets the maximum recursion depth for the stylesheet. + If provided, must be a positive integer. Default value + in libxslt is 250. If None, the default is used. + max_variables: Sets the maximum number of variables for a stylesheet. + If provided, must be a positive integer. Default value + is system-specific. If None, the default is used. + output_method: Specifies how the output should be handled. + "bytes" uses `output_as_bytes` (byte string encoded in + stylesheet's output encoding). + "chars" uses `output_as_chars` (UTF-8 encoded string of + characters). + enable_perl_warnings: If True, enables many useful Perl warnings (-w). + enable_perl_taint_checks: If True, enables Perl tainting checks (-T). + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + In case of an error, an "error" key with a description will be included. + + Raises: + FileNotFoundError: If the input XML or XSLT stylesheet file does not exist. + ValueError: If `max_recursion_depth` or `max_variables` are invalid. + subprocess.CalledProcessError: If the Perl script execution fails. + """ + # Input validation + if not xml_input_file.is_file(): + raise FileNotFoundError(f"XML input file not found: {xml_input_file}") + if not xslt_stylesheet_file.is_file(): + raise FileNotFoundError(f"XSLT stylesheet file not found: {xslt_stylesheet_file}") + + # Ensure output directory exists + output_file.parent.mkdir(parents=True, exist_ok=True) + + perl_script_content: List[str] = [] + perl_script_content.append("use strict;") + perl_script_content.append("use warnings;") + perl_script_content.append("use XML::LibXSLT;") + perl_script_content.append("use XML::LibXML;") + + # Use resolved absolute paths to avoid issues with working directories + perl_script_content.append(f"my $xml_input_file = '{xml_input_file.resolve()}';") + perl_script_content.append(f"my $xslt_stylesheet_file = '{xslt_stylesheet_file.resolve()}';") + perl_script_content.append(f"my $output_file = '{output_file.resolve()}';") + perl_script_content.append(f"my $output_method = '{output_method}';") + + perl_script_content.append("my $xslt = XML::LibXSLT->new();") + + if max_recursion_depth is not None: + if not isinstance(max_recursion_depth, int) or max_recursion_depth <= 0: + raise ValueError("max_recursion_depth must be a positive integer.") + perl_script_content.append(f"XML::LibXSLT->max_depth({max_recursion_depth});") + + if max_variables is not None: + if not isinstance(max_variables, int) or max_variables <= 0: + raise ValueError("max_variables must be a positive integer.") + perl_script_content.append(f"XML::LibXSLT->max_vars({max_variables});") + + perl_script_content.append( + "my $source_doc = XML::LibXML->load_xml(location => $xml_input_file) " + "or die \"Failed to load XML input '$xml_input_file': $!\";" + ) + perl_script_content.append( + "my $style_doc = XML::LibXML->load_xml(location => $xslt_stylesheet_file, no_cdata => 1) " + "or die \"Failed to load XSLT stylesheet '$xslt_stylesheet_file': $!\";" + ) + + perl_script_content.append( + "my $stylesheet = $xslt->parse_stylesheet($style_doc) " + "or die \"Failed to parse stylesheet: $!\";" + ) + + if xslt_parameters: + perl_script_content.append("my %params;") + for key, value in xslt_parameters.items(): + # XML::LibXSLT::xpath_to_string handles proper XPath quoting for string values + # The value itself needs to be escaped for Perl string literal, then xpath_to_string will handle it. + # Simple single-quote escaping for Perl string. + escaped_value = value.replace("'", "\\'") + perl_script_content.append(f"$params{{'{key}'}} = XML::LibXSLT::xpath_to_string('{escaped_value}');") + perl_script_content.append( + "my $results = $stylesheet->transform($source_doc, %params) " + "or die \"Failed to transform: $!\";" + ) + else: + perl_script_content.append( + "my $results = $stylesheet->transform($source_doc) " + "or die \"Failed to transform: $!\";" + ) + + perl_script_content.append("my $output_content;") + perl_script_content.append("if ($output_method eq 'chars') {") + perl_script_content.append(" $output_content = $stylesheet->output_as_chars($results);") + perl_script_content.append("} else {") + perl_script_content.append(" $output_content = $stylesheet->output_as_bytes($results);") + perl_script_content.append("}") + + # Use standard Perl file I/O instead of File::Slurp for broader compatibility + perl_script_content.append( + "open my $fh, '>', $output_file or die \"Cannot open output file '$output_file': $!\";" + ) + perl_script_content.append("if ($output_method eq 'bytes') {") + perl_script_content.append(" binmode $fh;") + perl_script_content.append("}") + perl_script_content.append("print $fh $output_content;") + perl_script_content.append( + "close $fh or die \"Cannot close output file '$output_file': $!\";" + ) + perl_script_content.append("exit 0;") + + full_perl_script = "\n".join(perl_script_content) + + tmp_script_path: Optional[Path] = None + try: + # Create a temporary Perl script file + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".pl", encoding='utf-8') as tmp_script_file: + tmp_script_file.write(full_perl_script) + tmp_script_path = Path(tmp_script_file.name) + + command: List[str] = ["perl"] + if enable_perl_warnings: + command.append("-w") + if enable_perl_taint_checks: + command.append("-T") + command.append(str(tmp_script_path)) + + process = subprocess.run( + command, + capture_output=True, + text=True, # Capture stdout/stderr as text + check=True, # Raise CalledProcessError for non-zero exit codes + encoding='utf-8' # Explicitly set encoding for text output + ) + stdout = process.stdout + stderr = process.stderr + output_files = [str(output_file.resolve())] + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + stdout = e.stdout + stderr = e.stderr + output_files = [] + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + "error": f"Perl script execution failed with exit code {e.returncode}", + } + finally: + # Clean up the temporary script file + if tmp_script_path and tmp_script_path.exists(): + tmp_script_path.unlink() \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/app/perl-xml-libxslt_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/app/perl-xml-libxslt_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fbb57c78809a7e209214cfcc83279e70bc6c780c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/app/perl-xml-libxslt_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/app/perl-xml-libxslt_server.py') +SERVER_NAME = 'biosci_perl_xml_libxslt' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f5c00f6a68ef86eeead452398fa4a38308248dc5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-xml-libxslt: + build: . + image: mcp-perl-xml-libxslt:latest + container_name: mcp-perl-xml-libxslt + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-xml-libxslt + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cc5733222e7c5f97a58d1b24956fb90ac54fb6cf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-xml-libxslt + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-libxslt/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..64e41c86c971ea103bcf1564da14eb4f139de2f2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-xml-namespacesupport via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-xml-namespacesupport -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-xml-namespacesupport_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-xml-namespacesupport_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-xml-namespacesupport_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/app/perl-xml-namespacesupport_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/app/perl-xml-namespacesupport_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5b6f0e18967dc77020c4bc1e498755fd8f18634d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/app/perl-xml-namespacesupport_server.py @@ -0,0 +1,83 @@ +import subprocess +from pathlib import Path +from typing import Optional, Dict, Any + +# No need to import mcp as per instructions + +@mcp.tool() +def get_module_info() -> Dict[str, Any]: + """ + Provides information about the perl-xml-namespacesupport module. + + This tool is designed to interact with the perl-xml-namespacesupport module, + which is primarily a Perl library for programmatic use, not a standalone + command-line executable. This function attempts to verify the module's + presence and retrieve its version by executing a Perl one-liner. + + As perl-xml-namespacesupport does not expose direct command-line functions, + this tool serves as a utility to confirm its installation and basic status. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any + output files (which will be empty in this case). + """ + command = ["perl", "-MXML::NamespaceSupport", "-e", "print $XML::NamespaceSupport::VERSION // 'VERSION not defined'"] + command_str = " ".join(command) + stdout = "" + stderr = "" + output_files: list[str] = [] + + try: + result = subprocess.run(command, capture_output=True, text=True, check=True) + stdout = result.stdout.strip() + stderr = result.stderr.strip() + + # Check for module not found in stderr, even if check=True didn't catch it (less likely with -M) + if "Can't locate XML/NamespaceSupport.pm" in stderr: + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": f"Error: Perl module XML::NamespaceSupport not found. Please ensure it is installed in your Perl environment. Original stderr: {stderr}", + "output_files": output_files, + } + + except subprocess.CalledProcessError as e: + stdout = e.stdout.strip() + stderr = e.stderr.strip() + + if "Can't locate XML/NamespaceSupport.pm" in stderr: + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": f"Error: Perl module XML::NamespaceSupport not found. Please ensure it is installed in your Perl environment. Original stderr: {stderr}", + "output_files": output_files, + } + else: + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": f"Error executing Perl command (exit code {e.returncode}): {e}\n{stderr}", + "output_files": output_files, + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and accessible in your PATH.", + "output_files": output_files, + } + except Exception as e: + # Catch any other unexpected errors during execution + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": f"An unexpected error occurred: {e}\n{stderr}", + "output_files": output_files, + } + + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/app/perl-xml-namespacesupport_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/app/perl-xml-namespacesupport_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e9cad2ab0a5fac7b4e66713ee53e9a7369a03f15 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/app/perl-xml-namespacesupport_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/app/perl-xml-namespacesupport_server.py') +SERVER_NAME = 'biosci_perl_xml_namespacesupport' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e4a75cea631affd21a341310dbc648e7faadb29f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-xml-namespacesupport: + build: . + image: mcp-perl-xml-namespacesupport:latest + container_name: mcp-perl-xml-namespacesupport + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-xml-namespacesupport + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d71e545f2f858462b13761cfadcfc84ade648af4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-xml-namespacesupport + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-namespacesupport/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fe812e7864e2670c70fde10769364b33c4937c53 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-xml-parser via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-xml-parser -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-xml-parser_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-xml-parser_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-xml-parser_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/app/perl-xml-parser_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/app/perl-xml-parser_server.py new file mode 100644 index 0000000000000000000000000000000000000000..04db9f02c2242d70f85935aa863a838e679f143b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/app/perl-xml-parser_server.py @@ -0,0 +1,231 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +# No need to import mcp, as per instructions. + +# Helper function for common subprocess execution logic +def _execute_command(cmd: List[str]) -> dict: + """ + Executes a shell command and returns structured output. + """ + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [], # This will be populated by specific tools if needed + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": f"Error: The command '{cmd[0]}' was not found. " + "Please ensure Perl is installed and in your PATH.", + "error": "Executable not found", + "returncode": 127, + "output_files": [], + } + +@mcp.tool() +def run_perl_script( + program_file: Optional[Path] = None, + program_string: Optional[str] = None, + program_string_extended: bool = False, + program_arguments: Optional[List[str]] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + modules_to_use: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + rudimentary_parsing: bool = False, + search_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + ignore_text_before_shebang_dir: Optional[Path] = None, +) -> dict: + """ + Executes a Perl script or one-liner, providing access to various Perl interpreter switches. + + This tool allows running Perl programs, potentially utilizing modules like XML::Parser + (which is expected to be available in the execution environment), by passing a script file + or a program string along with interpreter options. + + Args: + program_file: Path to the Perl script file to execute. Mutually exclusive with `program_string`. + program_string: A one-line Perl program string to execute. Mutually exclusive with `program_file`. + program_string_extended: If `program_string` is used, enables all optional features (uses -E instead of -e). + program_arguments: A list of strings to be passed as arguments to the Perl script. + record_separator: Specify record separator (e.g., '0' for null, '0777' for paragraph mode). + autosplit: Enable autosplit mode with -n or -p (splits $_ into @F). + unicode_features: Enables listed Unicode features (e.g., 'all', 'io', 'say'). + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). + debugger: Run program under debugger (e.g., 'perl -d' or 'perl -d:MyDebugger'). + debugging_flags: Set debugging flags (argument is a bit mask or alphabets). + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. + split_pattern: split() pattern for -a switch (e.g., '/\\s+/'). Must start and end with '/'. + edit_in_place_extension: Edit <> files in place. If extension is supplied, makes backup (e.g., '.bak'). + include_directories: List of directories to add to @INC/#include path. + line_ending_processing: Enable line ending processing, specifies line terminator (e.g., '0' for null). + modules_to_use: List of modules to execute "use/no module..." before executing program. + Prefix with '-' for 'no module' (e.g., ['strict', '-warnings']). + loop_around_program: Assume "while (<>) { ... }" loop around program (-n). + loop_and_print: Assume loop like -n but print line also, like sed (-p). + rudimentary_parsing: Enable rudimentary parsing for switches after programfile (-s). + search_path: Look for programfile using PATH environment variable (-S). + tainting_warnings: Enable tainting warnings (-t). + tainting_checks: Enable tainting checks (-T). + dump_core: Dump core after parsing program (-u). + allow_unsafe_operations: Allow unsafe operations (-U). + print_version: Print Perl version, patchlevel, and license (-v). + print_config_summary: Print configuration summary (or a single Config.pm variable) (-V[:variable]). + enable_warnings: Enable many useful warnings (-w). + enable_all_warnings: Enable all warnings (-W). + disable_all_warnings: Disable all warnings (-X). + ignore_text_before_shebang_dir: Ignore text before #!perl line (optionally cd to directory) (-x[directory]). + """ + cmd = ["perl"] + output_files: List[Path] = [] + + # Input validation + if program_file and program_string: + raise ValueError("Cannot specify both 'program_file' and 'program_string'. Choose one.") + + # If no program file/string, then -v or -V must be active + if not program_file and not program_string and not print_version and print_config_summary is None: + raise ValueError("Either 'program_file' or 'program_string' must be provided, " + "unless 'print_version' or 'print_config_summary' is true.") + + if program_file: + if not program_file.is_file(): + raise FileNotFoundError(f"Program file not found: {program_file}") + + # Handle mutually exclusive warning flags + if disable_all_warnings and (enable_warnings or enable_all_warnings): + raise ValueError("Cannot use 'disable_all_warnings' (-X) with 'enable_warnings' (-w) or 'enable_all_warnings' (-W).") + # Note: -W implies -w, so if both enable_warnings and enable_all_warnings are true, -W will take precedence. + + # Add switches + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if debugger is not None: + cmd.append(f"-d:{debugger}" if debugger else "-d") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if program_string: + if program_string_extended: + cmd.append("-E") + else: + cmd.append("-e") + cmd.append(program_string) + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + if not (split_pattern.startswith('/') and split_pattern.endswith('/')): + raise ValueError("split_pattern must start and end with '/' (e.g., '/\\s+/').") + cmd.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + cmd.append(f"-i{edit_in_place_extension}") + # If a backup is made (e.g., -i.bak), the backup file would be an output. + # However, the exact name depends on the input file(s) processed by the Perl script, + # which is not directly known by this generic wrapper. + # The primary "output" is the modified input file itself. + if include_directories: + for inc_dir in include_directories: + if not inc_dir.is_dir(): + raise NotADirectoryError(f"Include directory not found: {inc_dir}") + cmd.append(f"-I{inc_dir}") + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + if modules_to_use: + for module in modules_to_use: + # Perl's -mmodule and -Mmodule are for 'use module', -m-module and -M-module are for 'no module'. + # We'll use -m for 'use' and -M for 'no' for clarity, though Perl often treats them similarly. + if module.startswith('-'): # For 'no module' + cmd.append(f"-M{module}") # e.g., -M-warnings + else: # For 'use module' + cmd.append(f"-m{module}") # e.g., -mstrict + if loop_and_print: # -p implies -n, so if both are set, -p takes precedence. + cmd.append("-p") + elif loop_around_program: + cmd.append("-n") + if rudimentary_parsing: + cmd.append("-s") + if search_path: + cmd.append("-S") + if tainting_warnings: + cmd.append("-t") + if tainting_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if allow_unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config_summary is not None: + cmd.append(f"-V:{print_config_summary}" if print_config_summary else "-V") + if disable_all_warnings: + cmd.append("-X") + elif enable_all_warnings: # -W implies -w, so if -W is set, no need for -w + cmd.append("-W") + elif enable_warnings: + cmd.append("-w") + if ignore_text_before_shebang_dir is not None: + if not ignore_text_before_shebang_dir.is_dir(): + raise NotADirectoryError(f"Directory for -x not found: {ignore_text_before_shebang_dir}") + cmd.append(f"-x{ignore_text_before_shebang_dir}") + + # Add program file if provided and not using -e/-E + if program_file and not program_string: + cmd.append(str(program_file)) + + # Add program arguments, separated by '--' if a program file is present and arguments are given + # This ensures that arguments are passed to the script, not interpreted as perl switches. + if program_arguments: + if program_file and not program_string: # Only add '--' if a script file is being executed + cmd.append("--") + cmd.extend(program_arguments) + + # Execute the command + result = _execute_command(cmd) + result["output_files"] = output_files # Ensure output_files is always present + + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/app/perl-xml-parser_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/app/perl-xml-parser_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..57462fb43d3e96ee6d74e852829849321e215ccd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/app/perl-xml-parser_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/app/perl-xml-parser_server.py') +SERVER_NAME = 'biosci_perl_xml_parser' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..fdbede1ca7da14dc2b6eb726021302b3d53e52d9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-xml-parser: + build: . + image: mcp-perl-xml-parser:latest + container_name: mcp-perl-xml-parser + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-xml-parser + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e72efa35b9c852f50a0f1c9b562aa24c0929245f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-xml-parser + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-parser/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0c9f1c0ce8551eb32942d5cf70a37f4153c474e6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-xml-regexp via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-xml-regexp -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-xml-regexp_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-xml-regexp_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-xml-regexp_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/app/perl-xml-regexp_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/app/perl-xml-regexp_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4a9a6fb39b243c1f4812f7b1511a083092885aca --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/app/perl-xml-regexp_server.py @@ -0,0 +1,162 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +@mcp.tool() +def perl_xml_regexp_validate( + text: str, + token_type: str = "Name" +) -> Dict[str, Any]: + """ + Validates if a given string matches a specific XML token regular expression + provided by the XML::RegExp Perl module. + + Args: + text: The string to validate against the XML regular expression. + token_type: The type of XML token to validate against. + Common values: 'Name', 'NmToken', 'NCName', 'QName', 'AttValue', + 'EntityValue', 'SystemLiteral', 'PubidLiteral', 'Char', 'S', + 'VersionNum', 'EncName', 'EncodingDecl', 'VersionInfo', 'Misc', + 'Comment', 'PI', 'CDSect', 'Reference', 'EntityRef', 'CharRef'. + """ + # List of common valid tokens in XML::RegExp for validation + valid_tokens = [ + "Name", "NmToken", "NCName", "QName", "AttValue", "EntityValue", + "SystemLiteral", "PubidLiteral", "Char", "S", "VersionNum", + "EncName", "EncodingDecl", "VersionInfo", "Misc", "Comment", + "PI", "CDSect", "Reference", "EntityRef", "CharRef", "BaseChar", + "Ideographic", "CombiningChar", "Digit", "Extender", "Letter" + ] + + if token_type not in valid_tokens: + # We allow it but warn or handle it; Perl will throw an error if the variable doesn't exist + pass + + # Construct the perl command + # We use -MXML::RegExp to load the module + # We use $ARGV[0] for the text and $ARGV[1] for the token type to avoid shell injection + perl_script = 'use XML::RegExp; my $type = $ARGV[1]; no strict "refs"; if ($ARGV[0] =~ /^${"XML::RegExp::$type"}$/) { print "MATCH"; } else { print "NO_MATCH"; }' + + cmd = [ + "perl", + "-MXML::RegExp", + "-e", perl_script, + text, + token_type + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + is_valid = result.stdout.strip() == "MATCH" + + return { + "command_executed": " ".join(cmd), + "is_valid": is_valid, + "token_type": token_type, + "input_text": text, + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def perl_xml_regexp_execute( + code: str, + args: Optional[List[str]] = None +) -> Dict[str, Any]: + """ + Executes a custom Perl snippet that utilizes the XML::RegExp module. + The module is automatically loaded via '-MXML::RegExp'. + + Args: + code: The Perl code to execute. Example: 'print $XML::RegExp::Name' + args: Optional list of command-line arguments to pass to the Perl script. + """ + cmd_args = args if args is not None else [] + + cmd = [ + "perl", + "-MXML::RegExp", + "-e", code, + "--" + ] + cmd_args + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr, + "status": "error" + } + +@mcp.tool() +def perl_xml_regexp_info() -> Dict[str, Any]: + """ + Returns the version information of the installed XML::RegExp module and the Perl interpreter. + """ + perl_cmd = ["perl", "-v"] + module_cmd = ["perl", "-MXML::RegExp", "-e", "print $XML::RegExp::VERSION"] + + try: + perl_ver = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + mod_ver = subprocess.run(module_cmd, capture_output=True, text=True, check=True) + + return { + "perl_version_info": perl_ver.stdout.splitlines()[1] if len(perl_ver.stdout.splitlines()) > 1 else perl_ver.stdout, + "xml_regexp_version": mod_ver.stdout.strip(), + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to retrieve version information. Ensure perl and perl-xml-regexp are installed.", + "stderr": e.stderr, + "status": "error" + } + +@mcp.tool() +def perl_xml_regexp_list_regexes() -> Dict[str, Any]: + """ + Lists the available regular expression variables provided by the XML::RegExp module. + """ + # This script inspects the XML::RegExp namespace + perl_script = ( + 'use XML::RegExp; ' + 'foreach my $entry (sort keys %XML::RegExp::) { ' + ' print "$entry\\n" if $entry =~ /^[A-Z]/; ' + '}' + ) + + cmd = ["perl", "-MXML::RegExp", "-e", perl_script] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + regex_list = [line.strip() for line in result.stdout.splitlines() if line.strip()] + + return { + "available_regex_variables": regex_list, + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/app/perl-xml-regexp_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/app/perl-xml-regexp_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8f740fd6df437e9bbdf7dfc608721a25769877ab --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/app/perl-xml-regexp_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/app/perl-xml-regexp_server.py') +SERVER_NAME = 'biosci_perl_xml_regexp' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c92fc9c45f722c087cc45f134c8cbdac7bb09b16 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-xml-regexp: + build: . + image: mcp-perl-xml-regexp:latest + container_name: mcp-perl-xml-regexp + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-xml-regexp + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c28e608c0cf6a96dd35c8a6cca6c05b2e28a69c2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-xml-regexp + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-regexp/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2d10f06824700eb4504b231de66270b64d60fcad --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-xml-sax-base via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-xml-sax-base -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-xml-sax-base_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-xml-sax-base_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-xml-sax-base_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/app/perl-xml-sax-base_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/app/perl-xml-sax-base_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e6bd3e3a7d492a1de509042fdc1807b6e2260cf6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/app/perl-xml-sax-base_server.py @@ -0,0 +1,228 @@ +from typing import Optional, List +import subprocess +from pathlib import Path + +@mcp.tool() +def perl_xml_sax_base_run( + program_file: Optional[str] = None, + one_liner: Optional[str] = None, + arguments: Optional[List[str]] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + syntax_check: bool = False, + debugger: Optional[str] = None, + debug_flags: Optional[str] = None, + one_liner_all_features: Optional[str] = None, + no_site_customize: bool = False, + split_pattern: Optional[str] = None, + inplace_extension: Optional[str] = None, + include_dirs: Optional[List[str]] = None, + line_ending_processing: Optional[str] = None, + modules: Optional[List[str]] = None, + loop_n: bool = False, + loop_p: bool = False, + switch_parsing: bool = False, + path_search: bool = False, + taint_warnings: bool = False, + taint_checks: bool = False, + dump_core: bool = False, + unsafe_operations: bool = False, + print_version: bool = False, + config_summary: Optional[str] = None, + warnings: bool = False, + all_warnings: bool = False, + extract_directory: Optional[str] = None, + disable_all_warnings: bool = False, +): + """ + Executes the Perl interpreter with the XML::SAX::Base environment. + This tool provides access to the Perl CLI switches as defined in the perl-xml-sax-base package environment. + + Args: + program_file: Path to the Perl script to execute. + one_liner: One line of program (several -e's allowed, but here as a single string). + arguments: Arguments passed to the programfile. + record_separator: Specify record separator (-0). + autosplit: Autosplit mode with -n or -p (-a). + unicode_features: Enables the listed Unicode features (-C). + syntax_check: Check syntax only (-c). + debugger: Run program under debugger (-d). + debug_flags: Set debugging flags (-D). + one_liner_all_features: Like -e, but enables all optional features (-E). + no_site_customize: Don't do $sitelib/sitecustomize.pl at startup (-f). + split_pattern: split() pattern for -a switch (-F). + inplace_extension: Edit <> files in place, makes backup if extension supplied (-i). + include_dirs: Specify @INC/#include directory (-I). + line_ending_processing: Enable line ending processing, specifies line terminator (-l). + modules: Execute "use module..." before executing program (-M). + loop_n: Assume "while (<>) { ... }" loop around program (-n). + loop_p: Assume loop like -n but print line also (-p). + switch_parsing: Enable rudimentary parsing for switches after programfile (-s). + path_search: Look for programfile using PATH environment variable (-S). + taint_warnings: Enable tainting warnings (-t). + taint_checks: Enable tainting checks (-T). + dump_core: Dump core after parsing program (-u). + unsafe_operations: Allow unsafe operations (-U). + print_version: Print version, patchlevel and license (-v). + config_summary: Print configuration summary or a single Config.pm variable (-V). + warnings: Enable many useful warnings (-w). + all_warnings: Enable all warnings (-W). + extract_directory: Ignore text before #!perl line, optionally cd to directory (-x). + disable_all_warnings: Disable all warnings (-X). + """ + cmd = ["perl"] + + # Handle switches + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if syntax_check: + cmd.append("-c") + if debugger is not None: + cmd.append(f"-d{debugger}") + if debug_flags is not None: + cmd.append(f"-D{debug_flags}") + if one_liner is not None: + cmd.extend(["-e", one_liner]) + if one_liner_all_features is not None: + cmd.extend(["-E", one_liner_all_features]) + if no_site_customize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if inplace_extension is not None: + cmd.append(f"-i{inplace_extension}") + if include_dirs: + for d in include_dirs: + cmd.append(f"-I{d}") + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + if modules: + for m in modules: + cmd.append(f"-M{m}") + if loop_n: + cmd.append("-n") + if loop_p: + cmd.append("-p") + if switch_parsing: + cmd.append("-s") + if path_search: + cmd.append("-S") + if taint_warnings: + cmd.append("-t") + if taint_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if config_summary is not None: + cmd.append(f"-V:{config_summary}" if config_summary else "-V") + if warnings: + cmd.append("-w") + if all_warnings: + cmd.append("-W") + if extract_directory is not None: + cmd.append(f"-x{extract_directory}") + if disable_all_warnings: + cmd.append("-X") + + # Handle program file and arguments + if program_file: + prog_path = Path(program_file) + if not prog_path.exists(): + return {"error": f"Program file not found: {program_file}"} + cmd.append(str(prog_path)) + + if arguments: + cmd.extend(arguments) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def perl_xml_sax_base_check_version(): + """ + Checks the installed version of the XML::SAX::Base Perl module. + This is useful to verify that the library is correctly installed in the environment. + """ + cmd = ["perl", "-MXML::SAX::Base", "-e", "print $XML::SAX::Base::VERSION"] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "module": "XML::SAX::Base", + "version": result.stdout.strip(), + "command_executed": " ".join(cmd), + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "error": "XML::SAX::Base module not found or failed to load.", + "stderr": e.stderr, + "command_executed": " ".join(cmd), + "status": "error" + } + +@mcp.tool() +def perl_xml_sax_base_validate_xml_structure( + xml_file: str, +): + """ + Uses XML::SAX::Base to perform a basic parse of an XML file to check for well-formedness. + Note: XML::SAX::Base is a base class; this tool uses it to verify the SAX parsing chain. + + Args: + xml_file: Path to the XML file to validate. + """ + xml_path = Path(xml_file) + if not xml_path.exists(): + return {"error": f"XML file not found: {xml_file}"} + + # Perl one-liner to attempt parsing using the SAX Base logic + # It uses XML::SAX::ParserFactory to find an available parser that inherits from Base + perl_code = ( + "use XML::SAX::ParserFactory; " + "my $handler = XML::SAX::Base->new(); " + "my $parser = XML::SAX::ParserFactory->parser(Handler => $handler); " + "eval { $parser->parse_uri($ARGV[0]) }; " + "if ($@) { die $@; }" + ) + + cmd = ["perl", "-e", perl_code, str(xml_path)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "message": f"XML file {xml_file} is well-formed according to SAX parser.", + "stdout": result.stdout, + "command_executed": " ".join(cmd), + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "error": f"Validation failed for {xml_file}", + "stderr": e.stderr, + "command_executed": " ".join(cmd), + "status": "error" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/app/perl-xml-sax-base_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/app/perl-xml-sax-base_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d3caa4501ccd0a35a6fc89bf9591636fbd9cf87d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/app/perl-xml-sax-base_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/app/perl-xml-sax-base_server.py') +SERVER_NAME = 'biosci_perl_xml_sax_base' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..1a9a1e4ddd94a241df31aeca32c89f9a39b8d36a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-xml-sax-base: + build: . + image: mcp-perl-xml-sax-base:latest + container_name: mcp-perl-xml-sax-base + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-xml-sax-base + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d358461587267c837158b1577f9423c6a24b72df --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-xml-sax-base + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-base/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..325d6d7aaefdf66c54c95e360bb5fc54ba8f3535 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-xml-sax-expat via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-xml-sax-expat -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-xml-sax-expat_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-xml-sax-expat_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-xml-sax-expat_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/app/perl-xml-sax-expat_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/app/perl-xml-sax-expat_server.py new file mode 100644 index 0000000000000000000000000000000000000000..78f7f2f4392350e7202f8fe5b88737aec7a681b7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/app/perl-xml-sax-expat_server.py @@ -0,0 +1,239 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +# Helper function for validating directory existence +def _validate_dir_exists(path: Path, param_name: str): + """Validates that a given path exists and is a directory.""" + if not path.exists(): + raise ValueError(f"Error: {param_name} '{path}' does not exist.") + if not path.is_dir(): + raise ValueError(f"Error: {param_name} '{path}' is not a directory.") + +@mcp.tool() +def run_perl_script( + program_file: Optional[Path] = None, + program_line: Optional[List[str]] = None, + program_line_extended: Optional[List[str]] = None, + script_arguments: Optional[List[str]] = None, + record_separator_octal: Optional[str] = None, + autosplit_mode: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + module_operations: Optional[List[str]] = None, + assume_loop_no_print: bool = False, + assume_loop_and_print: bool = False, + rudimentary_switch_parsing: bool = False, + look_for_programfile_in_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core_after_parsing: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang_dir: Optional[Path] = None, + disable_all_warnings: bool = False, + pass_dash_dash: bool = False, +) -> dict: + """ + Executes a Perl script or one-liner with various command-line options. + + This tool provides an interface to the Perl interpreter, allowing users to run + Perl programs, check syntax, enable debugging, manage warnings, and more. + It supports all the standard command-line switches available with the `perl` + executable. + + Args: + program_file (Optional[Path]): Path to the Perl script file to execute. + Cannot be used with `program_line` or `program_line_extended`. + program_line (Optional[List[str]]): One or more lines of program code to execute. + Equivalent to multiple `-e` switches. + program_line_extended (Optional[List[str]]): One or more lines of program code to execute, + enabling all optional features. Equivalent to multiple `-E` switches. + script_arguments (Optional[List[str]]): Arguments to be passed to the Perl script. + record_separator_octal (Optional[str]): Specifies the input record separator. + If no argument, defaults to `\0`. (e.g., "0", "0777") + autosplit_mode (bool): Enables autosplit mode with -n or -p (splits $_ into @F). Equivalent to `-a`. + unicode_features (Optional[str]): Enables listed Unicode features. (e.g., "all", "io") Equivalent to `-C`. + check_syntax_only (bool): Checks syntax only (runs BEGIN and CHECK blocks). Equivalent to `-c`. + debugger (Optional[str]): Runs program under debugger. Optionally specify debugger name. Equivalent to `-d[:debugger]`. + debugging_flags (Optional[str]): Sets debugging flags (argument is a bit mask or alphabets). Equivalent to `-D`. + no_sitecustomize (bool): Don't do $sitelib/sitecustomize.pl at startup. Equivalent to `-f`. + split_pattern (Optional[str]): `split()` pattern for -a switch. (e.g., "/\s+/") Equivalent to `-F`. + edit_in_place_extension (Optional[str]): Edits <> files in place. Makes backup if extension supplied. + (e.g., ".bak") Equivalent to `-i[extension]`. + include_directories (Optional[List[Path]]): Specifies @INC/#include directories. Equivalent to multiple `-I`. + line_ending_processing (Optional[str]): Enables line ending processing, specifies line terminator. + (e.g., "012" for newline) Equivalent to `-l[octal]`. + module_operations (Optional[List[str]]): Executes "use/no module..." before executing program. + Each string should be in the format "m:Module", "M:Module", + "m-:Module", or "M-:Module". (e.g., ["m:XML::SAX::Expat", "M-:strict"]) + assume_loop_no_print (bool): Assumes "while (<>) { ... }" loop around program. Equivalent to `-n`. + assume_loop_and_print (bool): Assumes loop like -n but prints line also, like sed. Equivalent to `-p`. + rudimentary_switch_parsing (bool): Enables rudimentary parsing for switches after programfile. Equivalent to `-s`. + look_for_programfile_in_path (bool): Looks for programfile using PATH environment variable. Equivalent to `-S`. + tainting_warnings (bool): Enables tainting warnings. Equivalent to `-t`. + tainting_checks (bool): Enables tainting checks. Equivalent to `-T`. + dump_core_after_parsing (bool): Dumps core after parsing program. Equivalent to `-u`. + allow_unsafe_operations (bool): Allows unsafe operations. Equivalent to `-U`. + print_version (bool): Prints version, patchlevel and license. Equivalent to `-v`. + print_config_summary (Optional[str]): Prints configuration summary. Optionally specify a Config.pm variable. + (e.g., "archname") Equivalent to `-V[:variable]`. + enable_warnings (bool): Enables many useful warnings. Equivalent to `-w`. + enable_all_warnings (bool): Enables all warnings. Equivalent to `-W`. + ignore_text_before_shebang_dir (Optional[Path]): Ignores text before #!perl line. + Optionally change directory to the specified path. + Equivalent to `-x[directory]`. + disable_all_warnings (bool): Disables all warnings. Equivalent to `-X`. + pass_dash_dash (bool): Explicitly passes '--' before the program file or script arguments. + Useful if script arguments might be mistaken for Perl options. + + Returns: + dict: A dictionary containing the command executed, stdout, stderr, and any output files. + Includes an 'error' key if the execution fails. + """ + command: List[str] = ["perl"] + output_files: List[Path] = [] + + # Input validation + if program_file: + if not program_file.is_file(): + raise ValueError(f"Error: Program file '{program_file}' does not exist or is not a file.") + if program_line or program_line_extended: + raise ValueError("Cannot specify both a program file and a one-liner (-e or -E).") + elif not (program_line or program_line_extended): + # If no program_file, at least one of program_line or program_line_extended must be provided + # to prevent perl from hanging waiting for STDIN, unless -v or -V is used. + if not (print_version or print_config_summary is not None): + raise ValueError("Either a 'program_file' or 'program_line'/'program_line_extended' must be provided.") + + if assume_loop_no_print and assume_loop_and_print: + raise ValueError("Cannot use both -n (assume loop, no print) and -p (assume loop, print line).") + if enable_warnings and enable_all_warnings: + raise ValueError("Cannot use both -w (enable warnings) and -W (enable all warnings). -W implies -w.") + if (enable_warnings or enable_all_warnings) and disable_all_warnings: + raise ValueError("Cannot enable warnings (-w or -W) and disable all warnings (-X) simultaneously.") + + # Add switches + if record_separator_octal is not None: + command.append(f"-0{record_separator_octal}") + if autosplit_mode: + command.append("-a") + if unicode_features is not None: + command.append(f"-C{unicode_features}") + if check_syntax_only: + command.append("-c") + if debugger is not None: + command.append(f"-d:{debugger}" if debugger else "-d") + if debugging_flags is not None: + command.append(f"-D{debugging_flags}") + if program_line: + for line in program_line: + command.extend(["-e", line]) + if program_line_extended: + for line in program_line_extended: + command.extend(["-E", line]) + if no_sitecustomize: + command.append("-f") + if split_pattern is not None: + command.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + command.append(f"-i{edit_in_place_extension}") + if include_directories: + for directory in include_directories: + _validate_dir_exists(directory, "include_directory") + command.extend(["-I", str(directory)]) + if line_ending_processing is not None: + command.append(f"-l{line_ending_processing}") + if module_operations: + for op in module_operations: + # Validate format: e.g., "m:MyModule", "M-:AnotherModule" + if not (op.startswith("m:") or op.startswith("M:") or op.startswith("m-:") or op.startswith("M-:")): + raise ValueError(f"Invalid module operation format: '{op}'. Expected 'm:Module', 'M:Module', 'm-:Module', or 'M-:Module'.") + # Reconstruct the command-line argument, e.g., "-mMyModule" or "-M-AnotherModule" + prefix, module_name = op.split(':', 1) + command.append(f"-{prefix}{module_name}") + if assume_loop_no_print: + command.append("-n") + if assume_loop_and_print: + command.append("-p") + if rudimentary_switch_parsing: + command.append("-s") + if look_for_programfile_in_path: + command.append("-S") + if tainting_warnings: + command.append("-t") + if tainting_checks: + command.append("-T") + if dump_core_after_parsing: + command.append("-u") + if allow_unsafe_operations: + command.append("-U") + if print_version: + command.append("-v") + if print_config_summary is not None: + command.append(f"-V:{print_config_summary}" if print_config_summary else "-V") + if enable_warnings: + command.append("-w") + if enable_all_warnings: + command.append("-W") + if ignore_text_before_shebang_dir is not None: + _validate_dir_exists(ignore_text_before_shebang_dir, "ignore_text_before_shebang_dir") + command.append(f"-x{ignore_text_before_shebang_dir}") + if disable_all_warnings: + command.append("-X") + + # Add '--' if explicitly requested or if there are script arguments and no program file + # (perl handles '--' implicitly if program_file is present and followed by args) + if pass_dash_dash or (not program_file and script_arguments): + command.append("--") + + # Add program file + if program_file: + command.append(str(program_file)) + + # Add script arguments + if script_arguments: + command.extend(script_arguments) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"Perl execution failed with exit code {e.returncode}" + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "output_files": [], + "error": "Perl executable not found." + } + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/app/perl-xml-sax-expat_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/app/perl-xml-sax-expat_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..76067a778e28a2c1b318df0e24019b22d5c46079 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/app/perl-xml-sax-expat_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/app/perl-xml-sax-expat_server.py') +SERVER_NAME = 'biosci_perl_xml_sax_expat' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d3b51fb674174e9235b018006ee4892f07d30790 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-xml-sax-expat: + build: . + image: mcp-perl-xml-sax-expat:latest + container_name: mcp-perl-xml-sax-expat + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-xml-sax-expat + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..70e8590d3eba26bd879d43a6396d2118f1236dcf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-xml-sax-expat + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6378f2a84548a1958dd57ff9c8489ecd13f3573d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-xml-sax-writer via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-xml-sax-writer -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-xml-sax-writer_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-xml-sax-writer_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-xml-sax-writer_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/app/perl-xml-sax-writer_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/app/perl-xml-sax-writer_server.py new file mode 100644 index 0000000000000000000000000000000000000000..148e9ad25659396744403bc0224111df13e77919 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/app/perl-xml-sax-writer_server.py @@ -0,0 +1,216 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Union + +# No need to import mcp, as per instructions. + +@mcp.tool() +def execute_perl_script( + program_file: Optional[Path] = None, + program_line: Optional[List[str]] = None, + program_line_extended: Optional[List[str]] = None, + program_arguments: Optional[List[str]] = None, + record_separator_octal: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debug_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + module_options: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + rudimentary_switch_parsing: bool = False, + search_programfile_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + ignore_text_before_shebang: Optional[Path] = None, +) -> Dict[str, Union[str, List[str], int]]: + """ + Executes a Perl script or one-liner with specified Perl interpreter options. + + The 'perl-xml-sax-writer' package is a Perl library (XML::SAX::Writer) and does not + have its own direct command-line interface. This tool provides access to the + generic Perl interpreter's command-line switches, which can be used to run a custom + Perl script that might utilize XML::SAX::Writer or any other Perl module. + + Args: + program_file: Path to the Perl script file to execute. Mutually exclusive with program_line and program_line_extended. + program_line: A list of Perl program lines to execute. Each string is treated as a separate -e argument. + Mutually exclusive with program_file. + program_line_extended: A list of Perl program lines to execute, enabling all optional features. + Each string is treated as a separate -E argument. Mutually exclusive with program_file. + program_arguments: A list of arguments to pass to the Perl script. + record_separator_octal: Specify record separator (e.g., '0' for null, '0777' for octal value). + autosplit: Enable autosplit mode with -n or -p (splits $_ into @F). + unicode_features: Enables listed Unicode features (e.g., 'all', 'io'). + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). + debugger: Run program under debugger. Can be just 'd' or 'd:MyDebugger'. + debug_flags: Set debugging flags (argument is a bit mask or alphabets). + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. + split_pattern: split() pattern for -a switch (e.g., '/\s+/'). // are optional. + edit_in_place_extension: Edit <> files in place (makes backup if extension supplied, e.g., '.bak'). + include_directories: Specify @INC/#include directories. + line_ending_processing: Enable line ending processing, specifies line terminator (e.g., '012'). + module_options: Execute "use/no module..." before executing program. + Each string should be prefixed with 'm', 'M', 'm-', or 'M-' as needed (e.g., "MXML::SAX::Writer", "m-strict"). + loop_around_program: Assume "while (<>) { ... }" loop around program. Mutually exclusive with loop_and_print. + loop_and_print: Assume loop like -n but print line also, like sed. Mutually exclusive with loop_around_program. + rudimentary_switch_parsing: Enable rudimentary parsing for switches after programfile. + search_programfile_path: Look for programfile using PATH environment variable. + tainting_warnings: Enable tainting warnings. + tainting_checks: Enable tainting checks. + dump_core: Dump core after parsing program. + allow_unsafe_operations: Allow unsafe operations. + print_version: Print version, patchlevel and license. + print_config_summary: Print configuration summary (or a single Config.pm variable, e.g., 'osname'). + enable_warnings: Enable many useful warnings. Mutually exclusive with enable_all_warnings and disable_all_warnings. + enable_all_warnings: Enable all warnings. Mutually exclusive with enable_warnings and disable_all_warnings. + disable_all_warnings: Disable all warnings. Mutually exclusive with enable_warnings and enable_all_warnings. + ignore_text_before_shebang: Ignore text before #!perl line (optionally cd to directory). + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + cmd = ["perl"] + output_files: List[str] = [] + + # Input validation + program_sources = [program_file, program_line, program_line_extended] + if sum(1 for x in program_sources if x is not None) > 1: + raise ValueError("Only one of program_file, program_line, or program_line_extended can be specified.") + + if program_file and not program_file.is_file(): + raise FileNotFoundError(f"Program file not found: {program_file}") + + if loop_around_program and loop_and_print: + raise ValueError("Cannot specify both 'loop_around_program' (-n) and 'loop_and_print' (-p).") + + warning_flags_count = sum(1 for x in [enable_warnings, enable_all_warnings, disable_all_warnings] if x) + if warning_flags_count > 1: + raise ValueError("Cannot specify more than one warning flag (-w, -W, -X).") + + # Build command + if record_separator_octal is not None: + cmd.append(f"-0{record_separator_octal}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if debugger is not None: + cmd.append(f"-d{':' + debugger if debugger else ''}") + if debug_flags is not None: + cmd.append(f"-D{debug_flags}") + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + cmd.append(f"-i{edit_in_place_extension}") + if include_directories: + for d in include_directories: + if not d.is_dir(): + raise NotADirectoryError(f"Include directory not found: {d}") + cmd.append(f"-I{d}") + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + if module_options: + for mod_opt in module_options: + if not mod_opt.startswith(('m', 'M', 'm-', 'M-')): + raise ValueError(f"Invalid module option format: {mod_opt}. Must start with 'm', 'M', 'm-', or 'M-'.") + cmd.append(f"-{mod_opt}") + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if rudimentary_switch_parsing: + cmd.append("-s") + if search_programfile_path: + cmd.append("-S") + if tainting_warnings: + cmd.append("-t") + if tainting_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if allow_unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config_summary is not None: + cmd.append(f"-V{':' + print_config_summary if print_config_summary else ''}") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if disable_all_warnings: + cmd.append("-X") + if ignore_text_before_shebang is not None: + if not ignore_text_before_shebang.is_dir(): + raise NotADirectoryError(f"Directory for -x not found: {ignore_text_before_shebang}") + cmd.append(f"-x{ignore_text_before_shebang}") + + if program_line: + for line in program_line: + cmd.append("-e") + cmd.append(line) + elif program_line_extended: + for line in program_line_extended: + cmd.append("-E") + cmd.append(line) + elif program_file: + cmd.append(str(program_file)) + + if program_arguments: + cmd.extend(program_arguments) + + command_executed = " ".join(map(str, cmd)) + + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": output_files, + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: Perl executable not found. Please ensure Perl is installed and in your PATH.", + "error": "Perl executable not found", + "returncode": 127, + "output_files": output_files, + } + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/app/perl-xml-sax-writer_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/app/perl-xml-sax-writer_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..95058f46d4cf8b1e837078c2e1ee3a4ea0077d64 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/app/perl-xml-sax-writer_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/app/perl-xml-sax-writer_server.py') +SERVER_NAME = 'biosci_perl_xml_sax_writer' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..db4a9aa7fa1c893e0ad43b5275093caa40e13d39 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-xml-sax-writer: + build: . + image: mcp-perl-xml-sax-writer:latest + container_name: mcp-perl-xml-sax-writer + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-xml-sax-writer + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e95236b48c96dd7a8d8c6383dff1b04bd35e680b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-xml-sax-writer + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-writer/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4887ed827bf3a2f9a9288486a11851eb2da8963a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-xml-sax via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-xml-sax -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-xml-sax_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-xml-sax_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-xml-sax_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/app/perl-xml-sax_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/app/perl-xml-sax_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0d4d47345eec52446d9d5180a46926275a7cedca --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/app/perl-xml-sax_server.py @@ -0,0 +1,198 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def xml_sax_list_parsers() -> Dict[str, Any]: + """ + Get a list of all known/registered XML SAX parsers on the system. + This corresponds to the XML::SAX->parsers() method. + """ + # Perl one-liner to dump the parsers list using Data::Dumper for structured output + perl_cmd = [ + "perl", "-MXML::SAX", "-MData::Dumper", "-e", + "$Data::Dumper::Terse = 1; $Data::Dumper::Indent = 1; print Dumper(XML::SAX->parsers())" + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(perl_cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(perl_cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def xml_sax_add_parser(module_name: str) -> Dict[str, Any]: + """ + Register a new SAX parser module in the system's ParserDetails.ini. + + Args: + module_name: The Perl module name of the parser (e.g., 'XML::SAX::PurePerl' or 'XML::LibXML::SAX') + """ + if not module_name: + raise ValueError("module_name must be provided") + + # Perl one-liner to add the parser and save the configuration + perl_cmd = [ + "perl", "-MXML::SAX", "-e", + f"XML::SAX->add_parser(q({module_name}))->save_parsers()" + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(perl_cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "message": f"Successfully added and saved parser: {module_name}", + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(perl_cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def xml_sax_remove_parser(module_name: str) -> Dict[str, Any]: + """ + Remove a registered SAX parser module from the system's configuration. + + Args: + module_name: The Perl module name of the parser to remove. + """ + if not module_name: + raise ValueError("module_name must be provided") + + # Perl one-liner to remove the parser and save the configuration + perl_cmd = [ + "perl", "-MXML::SAX", "-e", + f"XML::SAX->remove_parser(q({module_name}))->save_parsers()" + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(perl_cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "message": f"Successfully removed and saved parser: {module_name}", + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(perl_cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def xml_sax_save_parsers() -> Dict[str, Any]: + """ + Explicitly save the current state of registered parsers to the ParserDetails.ini file. + """ + perl_cmd = ["perl", "-MXML::SAX", "-e", "XML::SAX->save_parsers()"] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(perl_cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "message": "Parser configuration saved successfully.", + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(perl_cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def xml_sax_parse_validate( + xml_file: str, + parser_package: Optional[str] = None +) -> Dict[str, Any]: + """ + Validate an XML file using a SAX parser to check for well-formedness. + + Args: + xml_file: Path to the XML file to be parsed. + parser_package: Optional specific SAX parser package to use (e.g., 'XML::SAX::PurePerl'). + If not provided, the system default is used. + """ + file_path = Path(xml_file) + if not file_path.exists(): + return {"error": f"File not found: {xml_file}", "status": "error"} + + # Construct the Perl script + # We use XML::SAX::ParserFactory to get a parser and parse the file. + # If parser_package is specified, we set $XML::SAX::ParserPackage. + perl_script = "use XML::SAX::ParserFactory; " + if parser_package: + perl_script += f"$XML::SAX::ParserPackage = q({parser_package}); " + + perl_script += ( + "my $p = XML::SAX::ParserFactory->parser(); " + "eval { $p->parse_uri($ARGV[0]) }; " + "if ($@) { print STDERR $@; exit 1 } else { print 'OK' }" + ) + + perl_cmd = ["perl", "-e", perl_script, str(file_path)] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(perl_cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "result": "File is well-formed" if "OK" in result.stdout else "Unknown status", + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(perl_cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "XML Parsing Error: " + e.stderr, + "status": "error" + } + +@mcp.tool() +def xml_sax_get_version() -> Dict[str, Any]: + """ + Check the installed version of the XML::SAX Perl module. + """ + perl_cmd = ["perl", "-MXML::SAX", "-e", "print $XML::SAX::VERSION"] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(perl_cmd), + "version": result.stdout.strip(), + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(perl_cmd), + "error": str(e), + "status": "error" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/app/perl-xml-sax_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/app/perl-xml-sax_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0a8c9a043c5495834166695e53c44b6b3a062f8f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/app/perl-xml-sax_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/app/perl-xml-sax_server.py') +SERVER_NAME = 'biosci_perl_xml_sax' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..08990f858f048c9465a67efc3e850e3d8e134db7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-xml-sax: + build: . + image: mcp-perl-xml-sax:latest + container_name: mcp-perl-xml-sax + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-xml-sax + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8f5ca6e94667ae6113c1d9501f6e64772d540fb6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-xml-sax + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aed3e876b512be9a7de4296215185bfaaeac68f9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-xml-simple via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-xml-simple -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-xml-simple_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-xml-simple_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-xml-simple_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/app/perl-xml-simple_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/app/perl-xml-simple_server.py new file mode 100644 index 0000000000000000000000000000000000000000..24821b19422f71de0326a98b39e8eb9db8d54da7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/app/perl-xml-simple_server.py @@ -0,0 +1,248 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union, Dict, Any +import tempfile + +# No need to import mcp as per instructions + +@mcp.tool() +def run_perl_script( + program_file: Optional[Path] = None, + program_arguments: Optional[List[str]] = None, + program_code: Optional[List[str]] = None, + record_separator: Optional[Union[str, int]] = None, + autosplit_mode: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + enable_all_features_code: Optional[List[str]] = None, + no_sitelib_startup: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing: Optional[Union[str, int]] = None, + use_modules: Optional[List[str]] = None, + use_strict_modules: Optional[List[str]] = None, + loop_around_program: bool = False, + print_and_loop: bool = False, + rudimentary_switch_parsing: bool = False, + look_for_programfile_in_path: bool = False, + enable_tainting_warnings: bool = False, + enable_tainting_checks: bool = False, + dump_core_after_parsing: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_variable: Optional[str] = None, + enable_useful_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_perl_line_flag: bool = False, + ignore_text_before_perl_line_dir: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> Dict[str, Any]: + """ + Executes a Perl script with various interpreter options. + + This tool wraps the 'perl' interpreter, allowing users to run Perl programs + with fine-grained control over execution environment, debugging, and warnings. + It can execute a Perl script from a file, or directly from provided code strings. + It is suitable for running scripts that utilize Perl modules like XML::Simple + if they are available in the Perl environment. + + Args: + program_file: Path to the Perl script file to execute. + program_arguments: List of arguments to pass to the Perl script. + program_code: List of Perl code lines to execute via the -e switch. + Multiple -e switches are allowed. + record_separator: Specify record separator (e.g., '0' for NUL, or an octal value). + If an empty string is provided, it defaults to '\0'. + autosplit_mode: Enable autosplit mode with -n or -p (splits $_ into @F). + unicode_features: Enables listed Unicode features (e.g., 'all', 'io', 'say'). + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). + debugger: Run program under debugger (e.g., 'ptkdb'). + debugging_flags: Set debugging flags (argument is a bit mask or alphabets). + enable_all_features_code: List of Perl code lines to execute via the -E switch. + Like -e, but enables all optional features. + no_sitelib_startup: Don't do $sitelib/sitecustomize.pl at startup. + split_pattern: split() pattern for -a switch (e.g., '/\s+/'). + edit_in_place_extension: Edit <> files in place. If an extension is supplied + (e.g., '.bak'), a backup file is made. If an empty + string is supplied, no backup is made. + include_directories: List of directories to specify for @INC/#include. + Multiple -I switches are allowed. + line_ending_processing: Enable line ending processing, specifies line terminator + (e.g., '0' for NUL, or an octal value). + use_modules: List of modules to execute 'use module...' before program. + Each string should be the module name (e.g., 'XML::Simple') + or '-module_name' to 'no module_name'. + use_strict_modules: List of modules to execute 'use module...' before program, + enabling all optional features. Each string should be the + module name (e.g., 'strict') or '-module_name' to 'no module_name'. + loop_around_program: Assume "while (<>) { ... }" loop around program. + print_and_loop: Assume loop like -n but print line also, like sed. + rudimentary_switch_parsing: Enable rudimentary parsing for switches after programfile. + look_for_programfile_in_path: Look for programfile using PATH environment variable. + enable_tainting_warnings: Enable tainting warnings. + enable_tainting_checks: Enable tainting checks. + dump_core_after_parsing: Dump core after parsing program. + allow_unsafe_operations: Allow unsafe operations. + print_version: Print Perl version, patchlevel and license. + print_config_variable: Print configuration summary. If an empty string is provided, + it prints the full summary (-V). If a variable name is provided + (e.g., 'archname'), it prints that specific Config.pm variable (-V:variable). + enable_useful_warnings: Enable many useful warnings (-w). + enable_all_warnings: Enable all warnings (-W). + ignore_text_before_perl_line_flag: Ignore text before #!perl line (-x without directory). + ignore_text_before_perl_line_dir: Ignore text before #!perl line and optionally cd to directory (-x directory). + disable_all_warnings: Disable all warnings (-X). + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + # Input validation + if program_file and not program_file.is_file(): + raise ValueError(f"Program file not found: {program_file}") + + if ignore_text_before_perl_line_dir and not ignore_text_before_perl_line_dir.is_dir(): + raise ValueError(f"Directory for -x option not found: {ignore_text_before_perl_line_dir}") + + if include_directories: + for inc_dir in include_directories: + if not inc_dir.is_dir(): + raise ValueError(f"Include directory not found: {inc_dir}") + + # Build the command + cmd = ["perl"] + + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit_mode: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if debugger is not None: + cmd.append(f"-d:{debugger}") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if program_code: + for code_line in program_code: + cmd.extend(["-e", code_line]) + if enable_all_features_code: + for code_line in enable_all_features_code: + cmd.extend(["-E", code_line]) + if no_sitelib_startup: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + cmd.append(f"-i{edit_in_place_extension}") + if include_directories: + for inc_dir in include_directories: + cmd.append(f"-I{inc_dir}") + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + if use_modules: + for module_spec in use_modules: + cmd.append(f"-m{module_spec}") + if use_strict_modules: + for module_spec in use_strict_modules: + cmd.append(f"-M{module_spec}") + if loop_around_program: + cmd.append("-n") + if print_and_loop: + cmd.append("-p") + if rudimentary_switch_parsing: + cmd.append("-s") + if look_for_programfile_in_path: + cmd.append("-S") + if enable_tainting_warnings: + cmd.append("-t") + if enable_tainting_checks: + cmd.append("-T") + if dump_core_after_parsing: + cmd.append("-u") + if allow_unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config_variable is not None: + if print_config_variable == "": + cmd.append("-V") # For -V (summary) + else: + cmd.append(f"-V:{print_config_variable}") # For -V:variable + if enable_useful_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if ignore_text_before_perl_line_dir: + cmd.append(f"-x{ignore_text_before_perl_line_dir}") + elif ignore_text_before_perl_line_flag: + cmd.append("-x") + if disable_all_warnings: + cmd.append("-X") + + # Program file and its arguments + if program_file: + cmd.append(str(program_file)) + if program_arguments: + cmd.extend(program_arguments) + + # Ensure at least one action is specified, otherwise perl might just hang or do nothing useful. + if not program_file and not program_code and not enable_all_features_code and not print_version and print_config_variable is None: + raise ValueError( + "Either 'program_file', 'program_code', 'enable_all_features_code', " + "or a flag like 'print_version' or 'print_config_variable' must be provided to execute Perl." + ) + + command_executed = " ".join(str(arg) for arg in cmd) + stdout = "" + stderr = "" + output_files: List[Path] = [] + + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + + # Handle -i option for in-place editing and backup files + if edit_in_place_extension is not None and program_file: + # The original file is modified + output_files.append(program_file) + # If an extension was provided, a backup file is created + if edit_in_place_extension != "": + backup_file = Path(str(program_file) + edit_in_place_extension) + if backup_file.exists(): + output_files.append(backup_file) + + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": output_files, + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Ensure Perl is installed and in your PATH.", + "error": "Perl executable not found", + "returncode": 127, + "output_files": output_files, + } + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/app/perl-xml-simple_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/app/perl-xml-simple_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0477aa9b4d00b9c0ca5559db7703b3ebd12a3e00 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/app/perl-xml-simple_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/app/perl-xml-simple_server.py') +SERVER_NAME = 'biosci_perl_xml_simple' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..14e1624bcf9301057a0256c51b7aaef94e7b8abe --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-xml-simple: + build: . + image: mcp-perl-xml-simple:latest + container_name: mcp-perl-xml-simple + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-xml-simple + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0ec7070d15b71913655da2e74ef3bba8272c909e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-xml-simple + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-simple/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3c5a84cbc0dbd89c282399543b082a022a7e379e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-xml-twig via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-xml-twig -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-xml-twig_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-xml-twig_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-xml-twig_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/app/perl-xml-twig_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/app/perl-xml-twig_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4a84a4b146872d7705649e39efd9578e262412c5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/app/perl-xml-twig_server.py @@ -0,0 +1,313 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +@mcp.tool() +def xml_pp( + input_files: List[str], + style: str = "indented", + in_place_ext: Optional[str] = None, + encoding: Optional[str] = None, + preserve_white_spaces: bool = False, + load_dtd: bool = False, + verbose: bool = False, +) -> dict: + """ + XML pretty printer using XML::Twig. + + Args: + input_files: List of XML files to process. + style: Output style (indented, record, record_c, indented_a, none, nsgmls, smgl, cvs). + in_place_ext: If provided, edit files in place and use this extension for backups (e.g., '.bak'). + encoding: Output encoding. + preserve_white_spaces: If True, preserve white spaces. + load_dtd: If True, load the DTD. + verbose: Enable verbose output. + """ + cmd = ["xml_pp"] + + # Style validation + valid_styles = ["indented", "record", "record_c", "indented_a", "none", "nsgmls", "smgl", "cvs"] + if style not in valid_styles: + style = "indented" + cmd.extend(["-s", style]) + + if in_place_ext is not None: + cmd.append(f"-i{in_place_ext}") + + if encoding: + cmd.extend(["-e", encoding]) + + if preserve_white_spaces: + cmd.append("-p") + + if load_dtd: + cmd.append("-l") + + if verbose: + cmd.append("-v") + + # File validation + validated_files = [] + for f in input_files: + path = Path(f) + if not path.exists(): + return {"error": f"Input file not found: {f}"} + validated_files.append(str(path)) + + cmd.extend(validated_files) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": validated_files if in_place_ext else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def xml_grep( + xpath: str, + input_files: List[str], + root: Optional[str] = None, + wrap: Optional[str] = None, + nowrap: bool = False, + descr: Optional[str] = None, + cond: Optional[str] = None, + count: bool = False, + files_with_matches: bool = False, + files_without_matches: bool = False, + pretty_print: Optional[str] = None, + text_only: bool = False, + html: bool = False, + encoding: Optional[str] = None, +) -> dict: + """ + Grep-like utility for XML files using XPath expressions. + + Args: + xpath: The XPath expression to search for. + input_files: List of XML files to search. + root: Look for matches under this root. + wrap: Wrap the results in this tag. + nowrap: Do not wrap the results. + descr: Add a description tag. + cond: Additional condition (XPath). + count: Only print the count of matches. + files_with_matches: Only print filenames of files containing matches. + files_without_matches: Only print filenames of files NOT containing matches. + pretty_print: Pretty print the output using this style. + text_only: Output only the text content of matches. + html: Input is HTML. + encoding: Input/Output encoding. + """ + cmd = ["xml_grep"] + + if root: + cmd.extend(["--root", root]) + if wrap: + cmd.extend(["--wrap", wrap]) + if nowrap: + cmd.append("--nowrap") + if descr: + cmd.extend(["--descr", descr]) + if cond: + cmd.extend(["--cond", cond]) + if count: + cmd.append("--count") + if files_with_matches: + cmd.append("--files-with-matches") + if files_without_matches: + cmd.append("--files-without-matches") + if pretty_print: + cmd.extend(["--pretty_print", pretty_print]) + if text_only: + cmd.append("--text_only") + if html: + cmd.append("--html") + if encoding: + cmd.extend(["--encoding", encoding]) + + cmd.append(xpath) + + # File validation + validated_files = [] + for f in input_files: + path = Path(f) + if not path.exists(): + return {"error": f"Input file not found: {f}"} + validated_files.append(str(path)) + + cmd.extend(validated_files) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def xml_split( + input_file: str, + level: Optional[int] = None, + condition: Optional[str] = None, + size: Optional[str] = None, + max_files: Optional[int] = None, + base_name: Optional[str] = None, + verbose: bool = False, +) -> dict: + """ + Split an XML file into several smaller files. + + Args: + input_file: The XML file to split. + level: Split at this level (depth). + condition: Split at elements matching this XPath condition. + size: Split into files of approximately this size (e.g., '1Mb', '500Kb'). + max_files: Maximum number of files to create. + base_name: Base name for the output files. + verbose: Enable verbose output. + """ + path = Path(input_file) + if not path.exists(): + return {"error": f"Input file not found: {input_file}"} + + cmd = ["xml_split"] + + if level is not None: + cmd.extend(["-l", str(level)]) + if condition: + cmd.extend(["-c", condition]) + if size: + cmd.extend(["-s", size]) + if max_files is not None: + cmd.extend(["-n", str(max_files)]) + if base_name: + cmd.extend(["-b", base_name]) + if verbose: + cmd.append("-v") + + cmd.append(str(path)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + # xml_split creates files in the current directory or based on base_name + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "info": "Check the current directory for generated XML chunks and the master file." + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def xml_merge( + input_file: str, + output_file: Optional[str] = None, + verbose: bool = False, +) -> dict: + """ + Merge XML files split by xml_split. + + Args: + input_file: The master XML file (usually file-main.xml) created by xml_split. + output_file: Name of the merged output file. If not provided, prints to stdout. + verbose: Enable verbose output. + """ + path = Path(input_file) + if not path.exists(): + return {"error": f"Master input file not found: {input_file}"} + + cmd = ["xml_merge"] + + if output_file: + cmd.extend(["-o", output_file]) + if verbose: + cmd.append("-v") + + cmd.append(str(path)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] if output_file else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def xml_spellcheck( + input_files: List[str], + conf: Optional[str] = None, + pretty_print: str = "indented", +) -> dict: + """ + Spellcheck the text content of XML files. + + Args: + input_files: List of XML files to spellcheck. + conf: Configuration file for the spellchecker. + pretty_print: Pretty print style for the output. + """ + cmd = ["xml_spellcheck"] + + if conf: + cmd.extend(["--conf", conf]) + + cmd.extend(["--pretty_print", pretty_print]) + + # File validation + validated_files = [] + for f in input_files: + path = Path(f) + if not path.exists(): + return {"error": f"Input file not found: {f}"} + validated_files.append(str(path)) + + cmd.extend(validated_files) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/app/perl-xml-twig_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/app/perl-xml-twig_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..12d6533ef9c409a39374399a4854dbde72e5311f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/app/perl-xml-twig_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/app/perl-xml-twig_server.py') +SERVER_NAME = 'biosci_perl_xml_twig' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..88e6d4d1be0a8cf53c6d56a131ad026dd93d5dfd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-xml-twig: + build: . + image: mcp-perl-xml-twig:latest + container_name: mcp-perl-xml-twig + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-xml-twig + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8bfafe49d7f1dce26cdce59fb037b414f9fb12c4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-xml-twig + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9433b4eb03a610c368d4ccf8af6afe66eef40519 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-xml-writer via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-xml-writer -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-xml-writer_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-xml-writer_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-xml-writer_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/app/perl-xml-writer_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/app/perl-xml-writer_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4d374a6388f55e31dd81827a5e7db640d55e3acf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/app/perl-xml-writer_server.py @@ -0,0 +1,258 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Union + +# No need to import mcp, as per instructions. + +@mcp.tool() +def run_perl_script( + program_file: Optional[Path] = None, + script_arguments: Optional[List[str]] = None, + record_separator_octal: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debug_flags: Optional[str] = None, + execute_program_line: Optional[List[str]] = None, + execute_program_line_extended: Optional[List[str]] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place: bool = False, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing_terminator: Optional[str] = None, + use_module_loose: Optional[List[str]] = None, + use_module_strict: Optional[List[str]] = None, + no_module: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + rudimentary_switch_parsing: bool = False, + search_path_for_programfile: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core_after_parsing: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang: bool = False, + ignore_text_before_shebang_directory: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> dict: + """ + Executes a Perl script or Perl code with various interpreter options. + + This tool wraps the 'perl' interpreter, allowing execution of Perl scripts + or one-liners with fine-grained control over its behavior, including + module loading, debugging, warning levels, and input/output processing. + While the context is 'perl-xml-writer', this function provides general + Perl script execution capabilities. + + Args: + program_file: Path to the Perl script file to execute. + If not provided, 'execute_program_line' or + 'execute_program_line_extended' must be used, or a + version/config print option. + script_arguments: A list of arguments to pass to the Perl script. + record_separator_octal: Specifies the input record separator. + If no argument, defaults to '\0'. + autosplit: Enables autosplit mode with -n or -p (splits $_ into @F). + unicode_features: Enables listed Unicode features (number or list). + check_syntax_only: Checks syntax only (runs BEGIN and CHECK blocks). + debugger: Runs the program under the debugger. Optionally specify a debugger name. + debug_flags: Sets debugging flags (argument is a bit mask or alphabets). + execute_program_line: One line of program to execute. Can be specified multiple times. + Omit 'program_file' if using this. + execute_program_line_extended: Like 'execute_program_line', but enables all + optional features. Can be specified multiple times. + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. + split_pattern: Pattern for split() with 'autosplit' switch (e.g., '/\s+/'). + edit_in_place: Enables in-place editing of files specified by '<>'. + edit_in_place_extension: If 'edit_in_place' is True, this specifies an extension + for backup files (e.g., 'bak' creates '.bak' files). + If None or empty, no backup is made. + include_directories: Specify @INC/#include directories. Can be specified multiple times. + line_ending_processing_terminator: Enables line ending processing, specifies line terminator. + Defaults to '\n' if no argument. + use_module_loose: Execute "use module..." before executing program (corresponds to -m). + Can be specified multiple times. + use_module_strict: Execute "use module..." before executing program (corresponds to -M). + Can be specified multiple times. + no_module: Execute "no module..." before executing program (corresponds to -M-). + Can be specified multiple times. + loop_around_program: Assumes "while (<>) { ... }" loop around program. + loop_and_print: Assumes loop like 'loop_around_program' but prints line also, like sed. + rudimentary_switch_parsing: Enables rudimentary parsing for switches after program_file. + search_path_for_programfile: Looks for 'program_file' using PATH environment variable. + tainting_warnings: Enables tainting warnings. + tainting_checks: Enables tainting checks. + dump_core_after_parsing: Dumps core after parsing program. + allow_unsafe_operations: Allows unsafe operations. + print_version: Prints Perl version, patchlevel, and license. + print_config_summary: Prints configuration summary (or a single Config.pm variable). + enable_warnings: Enables many useful warnings. + enable_all_warnings: Enables all warnings. + ignore_text_before_shebang: Ignores text before #!perl line in the script. + ignore_text_before_shebang_directory: If 'ignore_text_before_shebang' is True, + optionally change to this directory before execution. + disable_all_warnings: Disables all warnings. + """ + command = ["perl"] + output_files = [] + + # Input validation + if program_file: + if not program_file.is_file(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Program file '{program_file}' does not exist.", + "output_files": [], + } + if execute_program_line or execute_program_line_extended: + return { + "command_executed": "", + "stdout": "", + "stderr": "Error: Cannot specify both 'program_file' and '-e'/'E' options.", + "output_files": [], + } + + if not program_file and not (execute_program_line or execute_program_line_extended or print_version or print_config_summary is not None): + return { + "command_executed": "", + "stdout": "", + "stderr": "Error: Either 'program_file' or at least one of '-e'/'E' options, or '-v'/'V' must be provided.", + "output_files": [], + } + + if include_directories: + for d in include_directories: + if not d.is_dir(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Include directory '{d}' does not exist or is not a directory.", + "output_files": [], + } + + if ignore_text_before_shebang and ignore_text_before_shebang_directory: + if not ignore_text_before_shebang_directory.is_dir(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Directory for -x option '{ignore_text_before_shebang_directory}' does not exist or is not a directory.", + "output_files": [], + } + + # Build command + if record_separator_octal is not None: + command.append(f"-0{record_separator_octal}") + if autosplit: + command.append("-a") + if unicode_features is not None: + command.append(f"-C{unicode_features}") + if check_syntax_only: + command.append("-c") + if debugger is not None: + command.append(f"-d:{debugger}" if debugger else "-d") + if debug_flags is not None: + command.append(f"-D{debug_flags}") + if execute_program_line: + for line in execute_program_line: + command.extend(["-e", line]) + if execute_program_line_extended: + for line in execute_program_line_extended: + command.extend(["-E", line]) + if no_sitecustomize: + command.append("-f") + if split_pattern is not None: + command.append(f"-F{split_pattern}") + if edit_in_place: + if edit_in_place_extension is not None: + command.append(f"-i{edit_in_place_extension}") + else: + command.append("-i") + if include_directories: + for d in include_directories: + command.extend(["-I", str(d)]) + if line_ending_processing_terminator is not None: + command.append(f"-l{line_ending_processing_terminator}") + if use_module_loose: + for module in use_module_loose: + command.extend(["-m", module]) + if use_module_strict: + for module in use_module_strict: + command.extend(["-M", module]) + if no_module: + for module in no_module: + command.extend(["-M-", module]) + if loop_around_program: + command.append("-n") + if loop_and_print: + command.append("-p") + if rudimentary_switch_parsing: + command.append("-s") + if search_path_for_programfile: + command.append("-S") + if tainting_warnings: + command.append("-t") + if tainting_checks: + command.append("-T") + if dump_core_after_parsing: + command.append("-u") + if allow_unsafe_operations: + command.append("-U") + if print_version: + command.append("-v") + if print_config_summary is not None: + command.append(f"-V:{print_config_summary}" if print_config_summary else "-V") + if enable_warnings: + command.append("-w") + if enable_all_warnings: + command.append("-W") + if ignore_text_before_shebang: + if ignore_text_before_shebang_directory is not None: + command.append(f"-x{ignore_text_before_shebang_directory}") + else: + command.append("-x") + if disable_all_warnings: + command.append("-X") + + # Add program file and its arguments + if program_file: + command.append(str(program_file)) + if script_arguments: + command.extend(script_arguments) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"Perl execution failed with exit code {e.returncode}", + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "output_files": [], + "error": "Perl executable not found.", + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/app/perl-xml-writer_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/app/perl-xml-writer_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..21940aea12b6fedfbaa9c0961d03ceed54e2edba --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/app/perl-xml-writer_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/app/perl-xml-writer_server.py') +SERVER_NAME = 'biosci_perl_xml_writer' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..165ca65a7e45d0c0a9bd78ce57df9295942d1af1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-xml-writer: + build: . + image: mcp-perl-xml-writer:latest + container_name: mcp-perl-xml-writer + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-xml-writer + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8d8bb8910b900e491ffb67c7826e0e131b7e7941 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-xml-writer + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-writer/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-xpath/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-xpath/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a254626fd7a64b2d9ec5568dbc273a2652a30ffa --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-xpath/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +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 + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-xml-xpath via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-xml-xpath -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-xml-xpath_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-xml-xpath_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-xml-xpath_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-xpath/app/perl-xml-xpath_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-xpath/app/perl-xml-xpath_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fc608778f428d86970c2df03bd3de44ad1e59696 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-xpath/app/perl-xml-xpath_server.py @@ -0,0 +1,382 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Union + +# Helper function to execute Perl scripts using XML::XPath +def _execute_perl_xpath_script( + perl_script_logic: str, + xml_input_file: Optional[Path] = None, + xml_input_string: Optional[str] = None, + xpath_expression: str = "", + context_node_xpath: Optional[str] = None, + namespaces: Optional[List[str]] = None, + additional_perl_flags: Optional[List[str]] = None, + output_modified_xml: bool = False, +) -> Dict[str, Union[str, List[str]]]: + """ + Constructs and executes a Perl script using the XML::XPath module. + + Args: + perl_script_logic: The core Perl code snippet to perform the XPath operation. + xml_input_file: Path to the input XML file. + xml_input_string: The input XML content as a string. + xpath_expression: The XPath expression to be used in the perl_script_logic. + context_node_xpath: An optional XPath expression to define the context node + for the main XPath query. If not found, the document root + will be used as context. + namespaces: A list of namespace mappings in "prefix=uri" format (e.g., ["foo=http://example.com/foo"]). + additional_perl_flags: Optional list of additional flags to pass to the perl interpreter (e.g., ['-w']). + output_modified_xml: If True, the entire modified XML document will be printed to stdout. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + if (xml_input_file is None and xml_input_string is None) or \ + (xml_input_file is not None and xml_input_string is not None): + raise ValueError("Exactly one of 'xml_input_file' or 'xml_input_string' must be provided.") + + if xml_input_file and not xml_input_file.is_file(): + raise FileNotFoundError(f"Input XML file not found: {xml_input_file}") + + if namespaces is None: + namespaces = [] + if additional_perl_flags is None: + additional_perl_flags = [] + + perl_script_lines = [ + "use strict;", + "use warnings;", + "use XML::XPath;", + "use XML::XPath::XMLParser;", # Needed for as_string and document root access + "my $xp;", + ] + + if xml_input_file: + perl_script_lines.append(f"my $filename = '{xml_input_file.resolve()}';") + perl_script_lines.append("$xp = XML::XPath->new(filename => $filename);") + elif xml_input_string: + # Escape single quotes in the XML string for Perl + escaped_xml_string = xml_input_string.replace("'", "'\\''") + perl_script_lines.append(f"my $xml_string = '{escaped_xml_string}';") + perl_script_lines.append("$xp = XML::XPath->new(xml => $xml_string);") + + # Add namespace declarations + for ns_pair in namespaces: + if '=' not in ns_pair: + raise ValueError(f"Invalid namespace format: '{ns_pair}'. Expected 'prefix=uri'.") + prefix, uri = ns_pair.split('=', 1) + # Escape single quotes in prefix and uri + prefix = prefix.replace("'", "'\\''") + uri = uri.replace("'", "'\\''") + perl_script_lines.append(f"$xp->set_namespace('{prefix}', '{uri}');") + + # Handle context node if specified + if context_node_xpath: + escaped_context_xpath = context_node_xpath.replace("'", "'\\''") + perl_script_lines.append(f"my $context_nodeset = $xp->find('{escaped_context_xpath}');") + perl_script_lines.append("my $context_node;") + perl_script_lines.append("if ($context_nodeset->size > 0) {") + perl_script_lines.append(" $context_node = $context_nodeset->get_node(1); # Use the first matching node as context") + perl_script_lines.append("} else {") + perl_script_lines.append(" # If context_node_xpath doesn't match, use document root as context for main query") + perl_script_lines.append(" $context_node = $xp->{_root};") + perl_script_lines.append("}") + else: + perl_script_lines.append("my $context_node = $xp->{_root};") # Default context is document root + + # Add the specific logic for the XPath operation + escaped_xpath_expression = xpath_expression.replace("'", "'\\''") + perl_script_lines.append(f"my $xpath_expr = '{escaped_xpath_expression}';") + perl_script_lines.append(perl_script_logic) + + # If output_modified_xml is true, we need to print the modified XML + if output_modified_xml: + perl_script_lines.append("print XML::XPath::XMLParser::as_string($xp->{_root});") + + full_perl_script = "\n".join(perl_script_lines) + + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".pl") as tmp_script: + tmp_script.write(full_perl_script) + tmp_script_path = Path(tmp_script.name) + + command = ["perl"] + additional_perl_flags + [str(tmp_script_path)] + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding="utf-8" + ) + stdout = process.stdout + stderr = process.stderr + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"Perl script execution failed with exit code {e.returncode}", + } + finally: + if tmp_script_path.exists(): + tmp_script_path.unlink() # Clean up the temporary script + + +@mcp.tool() +def xpath_find_nodes_as_string( + xpath_expression: str, + xml_input_file: Optional[Path] = None, + xml_input_string: Optional[str] = None, + context_node_xpath: Optional[str] = None, + namespaces: Optional[List[str]] = None, + additional_perl_flags: Optional[List[str]] = None, +) -> Dict[str, Union[str, List[str]]]: + """ + Finds nodes matching an XPath expression and returns them as XML strings. + + This tool uses the XML::XPath Perl module to parse an XML document (from a file or string), + evaluate an XPath expression, and return the XML representation of all matching nodes. + + Args: + xpath_expression: The XPath expression to evaluate. + xml_input_file: Path to the input XML file. + xml_input_string: The input XML content as a string. + context_node_xpath: An optional XPath expression to define the context node + for the main XPath query. If not found, the document root + will be used as context. + namespaces: A list of namespace mappings in "prefix=uri" format (e.g., ["foo=http://example.com/foo"]). + additional_perl_flags: Optional list of additional flags to pass to the perl interpreter (e.g., ['-w']). + + Returns: + A dictionary containing the command executed, stdout (XML strings of matched nodes, + each on a new line), stderr, and any output files. + """ + if not xpath_expression: + raise ValueError("xpath_expression cannot be empty.") + + perl_logic = """ +my $nodeset = $xp->findnodes($xpath_expr, $context_node); +foreach my $node ($nodeset->get_nodelist) { + print XML::XPath::XMLParser::as_string($node), "\\n"; +} +""" + return _execute_perl_xpath_script( + perl_script_logic=perl_logic, + xml_input_file=xml_input_file, + xml_input_string=xml_input_string, + xpath_expression=xpath_expression, + context_node_xpath=context_node_xpath, + namespaces=namespaces, + additional_perl_flags=additional_perl_flags, + ) + + +@mcp.tool() +def xpath_find_value( + xpath_expression: str, + xml_input_file: Optional[Path] = None, + xml_input_string: Optional[str] = None, + context_node_xpath: Optional[str] = None, + namespaces: Optional[List[str]] = None, + additional_perl_flags: Optional[List[str]] = None, +) -> Dict[str, Union[str, List[str]]]: + """ + Evaluates an XPath expression and returns its string value. + + This tool uses the XML::XPath Perl module to parse an XML document (from a file or string) + and evaluate an XPath expression, returning the string value of the result. + If the XPath returns a NodeSet, its string value (as per XPath rules) is returned. + + Args: + xpath_expression: The XPath expression to evaluate. + xml_input_file: Path to the input XML file. + xml_input_string: The input XML content as a string. + context_node_xpath: An optional XPath expression to define the context node + for the main XPath query. If not found, the document root + will be used as context. + namespaces: A list of namespace mappings in "prefix=uri" format (e.g., ["foo=http://example.com/foo"]). + additional_perl_flags: Optional list of additional flags to pass to the perl interpreter (e.g., ['-w']). + + Returns: + A dictionary containing the command executed, stdout (the string value), + stderr, and any output files. + """ + if not xpath_expression: + raise ValueError("xpath_expression cannot be empty.") + + perl_logic = """ +my $value = $xp->findvalue($xpath_expr, $context_node); +print $value, "\\n"; +""" + return _execute_perl_xpath_script( + perl_script_logic=perl_logic, + xml_input_file=xml_input_file, + xml_input_string=xml_input_string, + xpath_expression=xpath_expression, + context_node_xpath=context_node_xpath, + namespaces=namespaces, + additional_perl_flags=additional_perl_flags, + ) + + +@mcp.tool() +def xpath_exists( + xpath_expression: str, + xml_input_file: Optional[Path] = None, + xml_input_string: Optional[str] = None, + context_node_xpath: Optional[str] = None, + namespaces: Optional[List[str]] = None, + additional_perl_flags: Optional[List[str]] = None, +) -> Dict[str, Union[str, List[str]]]: + """ + Checks if an XPath expression matches any nodes and returns a boolean result. + + This tool uses the XML::XPath Perl module to parse an XML document (from a file or string) + and check if the given XPath expression matches any nodes. + + Args: + xpath_expression: The XPath expression to check for existence. + xml_input_file: Path to the input XML file. + xml_input_string: The input XML content as a string. + context_node_xpath: An optional XPath expression to define the context node + for the main XPath query. If not found, the document root + will be used as context. + namespaces: A list of namespace mappings in "prefix=uri" format (e.g., ["foo=http://example.com/foo"]). + additional_perl_flags: Optional list of additional flags to pass to the perl interpreter (e.g., ['-w']). + + Returns: + A dictionary containing the command executed, stdout ('1' for true, '0' for false), + stderr, and any output files. + """ + if not xpath_expression: + raise ValueError("xpath_expression cannot be empty.") + + perl_logic = """ +my $exists = $xp->exists($xpath_expr, $context_node) ? 1 : 0; +print $exists, "\\n"; +""" + return _execute_perl_xpath_script( + perl_script_logic=perl_logic, + xml_input_file=xml_input_file, + xml_input_string=xml_input_string, + xpath_expression=xpath_expression, + context_node_xpath=context_node_xpath, + namespaces=namespaces, + additional_perl_flags=additional_perl_flags, + ) + + +@mcp.tool() +def xpath_set_node_text( + xpath_expression: str, + new_text: str, + xml_input_file: Optional[Path] = None, + xml_input_string: Optional[str] = None, + context_node_xpath: Optional[str] = None, + namespaces: Optional[List[str]] = None, + additional_perl_flags: Optional[List[str]] = None, +) -> Dict[str, Union[str, List[str]]]: + """ + Sets the text content for a node or attribute matching an XPath expression. + Returns the modified XML document. + + This tool uses the XML::XPath Perl module to modify an XML document by setting + the text content of nodes or attributes identified by an XPath expression. + The full modified XML document is returned in stdout. + + Args: + xpath_expression: The XPath expression identifying the node(s) or attribute to modify. + new_text: The new text content to set. Can be an empty string. + xml_input_file: Path to the input XML file. + xml_input_string: The input XML content as a string. + context_node_xpath: An optional XPath expression to define the context node + for the main XPath query. If not found, the document root + will be used as context. + namespaces: A list of namespace mappings in "prefix=uri" format (e.g., ["foo=http://example.com/foo"]). + additional_perl_flags: Optional list of additional flags to pass to the perl interpreter (e.g., ['-w']). + + Returns: + A dictionary containing the command executed, stdout (the modified XML document), + stderr, and any output files. + """ + if not xpath_expression: + raise ValueError("xpath_expression cannot be empty.") + if new_text is None: + new_text = "" # Allow empty string, but not None + + escaped_new_text = new_text.replace("'", "'\\''") + + perl_logic = f""" +my $nodeset = $xp->findnodes($xpath_expr, $context_node); +foreach my $node ($nodeset->get_nodelist) {{ + $xp->setNodeText($node, '{escaped_new_text}'); +}} +""" + return _execute_perl_xpath_script( + perl_script_logic=perl_logic, + xml_input_file=xml_input_file, + xml_input_string=xml_input_string, + xpath_expression=xpath_expression, + context_node_xpath=context_node_xpath, + namespaces=namespaces, + additional_perl_flags=additional_perl_flags, + output_modified_xml=True, + ) + + +@mcp.tool() +def xpath_create_node( + xpath_expression: str, + xml_input_file: Optional[Path] = None, + xml_input_string: Optional[str] = None, + namespaces: Optional[List[str]] = None, + additional_perl_flags: Optional[List[str]] = None, +) -> Dict[str, Union[str, List[str]]]: + """ + Creates a node (or path of nodes) matching the given XPath expression. + Returns the modified XML document. + + This tool uses the XML::XPath Perl module to create new nodes in an XML document. + If parts of the path do not exist, they will be created automatically. + The full modified XML document is returned in stdout. + Note: The `context_node_xpath` parameter is not applicable for `createNode` as it + operates relative to the document root. + + Args: + xpath_expression: The XPath expression specifying the node(s) to create. + This should be an absolute path or a path relative to the + document root. + xml_input_file: Path to the input XML file. + xml_input_string: The input XML content as a string. + namespaces: A list of namespace mappings in "prefix=uri" format (e.g., ["foo=http://example.com/foo"]). + additional_perl_flags: Optional list of additional flags to pass to the perl interpreter (e.g., ['-w']). + + Returns: + A dictionary containing the command executed, stdout (the modified XML document), + stderr, and any output files. + """ + if not xpath_expression: + raise ValueError("xpath_expression cannot be empty.") + + perl_logic = """ +$xp->createNode($xpath_expr); +""" + return _execute_perl_xpath_script( + perl_script_logic=perl_logic, + xml_input_file=xml_input_file, + xml_input_string=xml_input_string, + xpath_expression=xpath_expression, + context_node_xpath=None, # createNode operates relative to the document root, not a specific context node object + namespaces=namespaces, + additional_perl_flags=additional_perl_flags, + output_modified_xml=True, + ) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-xpath/app/perl-xml-xpath_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-xpath/app/perl-xml-xpath_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1ea45c219532f9f79446a9afd8e4f9201c6ed1cd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-xpath/app/perl-xml-xpath_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-xpath/app/perl-xml-xpath_server.py') +SERVER_NAME = 'biosci_perl_xml_xpath' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-xpath/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-xpath/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-xpath/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-xpath/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-xpath/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7b7e2257ed46ad577ba6ca9cd3a71cd4a6642110 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-xpath/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-xml-xpath: + build: . + image: mcp-perl-xml-xpath:latest + container_name: mcp-perl-xml-xpath + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-xml-xpath + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file