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60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
#!/usr/bin/env python3
"""
OpenProblems Spatial Transcriptomics MCP Server

A Model Context Protocol server that provides AI agents with standardized access
to Nextflow pipelines, Viash components, and spatial transcriptomics workflows
within the OpenProblems project.
"""

import asyncio
import json
import logging
import subprocess
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
from .documentation_generator_simple import DocumentationGenerator

from mcp.server import Server
from mcp.server.models import InitializationOptions
from mcp.types import (
    GetPromptResult,
    Prompt,
    PromptArgument,
    PromptMessage,
    Resource,
    TextContent,
    Tool,
)
import mcp.server.stdio

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Initialize the MCP server
server = Server("OpenProblems-SpatialAI-MCP")

# Server configuration
SERVER_VERSION = "0.1.0"
SERVER_NAME = "OpenProblems Spatial Transcriptomics MCP"

# Initialize documentation generator
doc_generator = DocumentationGenerator()


@server.list_resources()
async def handle_list_resources() -> List[Resource]:
    """List available resources for spatial transcriptomics workflows."""
    return [
        Resource(
            uri="server://status",
            name="Server Status",
            description="Current status and configuration of the MCP server",
            mimeType="application/json",
        ),
        Resource(
            uri="documentation://nextflow",
            name="Nextflow Documentation",
            description="Comprehensive documentation for Nextflow workflows and best practices",
            mimeType="application/json",
        ),
        Resource(
            uri="documentation://viash",
            name="Viash Documentation",
            description="Documentation for Viash components and configuration",
            mimeType="application/json",
        ),
        Resource(
            uri="documentation://docker",
            name="Docker Documentation",
            description="Docker best practices and optimization guidelines",
            mimeType="application/json",
        ),
        Resource(
            uri="templates://spatial-workflows",
            name="Spatial Transcriptomics Pipeline Templates",
            description="Curated Nextflow pipeline templates for spatial transcriptomics analysis",
            mimeType="application/json",
        ),
    ]


@server.read_resource()
async def handle_read_resource(uri: str) -> str:
    """Read and return resource content based on URI."""
    logger.info(f"Reading resource: {uri}")

    if uri == "server://status":
        status = {
            "server_name": SERVER_NAME,
            "version": SERVER_VERSION,
            "status": "running",
            "capabilities": {
                "nextflow_execution": True,
                "viash_components": True,
                "docker_builds": True,
                "automated_testing": True,
                "log_analysis": True,
            },
            "supported_formats": ["h5ad", "json", "yaml", "nf", "vsh.yaml"],
            "documentation_available": True,
        }
        return json.dumps(status, indent=2)

    elif uri == "documentation://nextflow":
        # Try to load cached documentation first
        cached_docs = await doc_generator.load_cached_documentation()
        if "nextflow" in cached_docs:
            return cached_docs["nextflow"]
        else:
            # Fallback to basic documentation
            nextflow_docs = {
                "overview": "Nextflow is a workflow framework for bioinformatics pipelines",
                "status": "Real documentation not yet cached - run 'python -m mcp_server.documentation_scraper' to download",
                "best_practices": {
                    "dsl_version": "Use DSL2 for all new workflows",
                    "resource_management": "Specify memory and CPU requirements for each process",
                    "error_handling": "Implement retry strategies and error handling",
                    "containerization": "Use Docker/Singularity containers for reproducibility",
                },
                "common_patterns": {
                    "input_channels": "Use Channel.fromPath() for file inputs",
                    "output_publishing": "Use publishDir directive for results",
                    "conditional_execution": "Use when clause for conditional processes",
                },
                "troubleshooting": {
                    "oom_errors": "Increase memory allocation or implement dynamic resource allocation",
                    "missing_files": "Check file paths and ensure proper input staging",
                    "container_issues": "Verify container availability and permissions",
                },
            }
            return json.dumps(nextflow_docs, indent=2)

    elif uri == "documentation://viash":
        # Try to load cached documentation first
        cached_docs = await doc_generator.load_cached_documentation()
        if "viash" in cached_docs:
            return cached_docs["viash"]
        else:
            # Fallback to basic documentation
            viash_docs = {
                "overview": "Viash is a meta-framework for building reusable workflow modules",
                "status": "Real documentation not yet cached - run 'python -m mcp_server.documentation_scraper' to download",
                "component_structure": {
                    "config_file": "YAML configuration defining component metadata",
                    "script": "Core functionality implementation",
                    "platforms": "Target platforms (docker, native, nextflow)",
                },
                "best_practices": {
                    "modularity": "Keep components focused on single tasks",
                    "documentation": "Provide clear descriptions and examples",
                    "testing": "Include unit tests for all components",
                    "versioning": "Use semantic versioning for component releases",
                },
                "common_commands": {
                    "build": "viash build config.vsh.yaml",
                    "run": "viash run config.vsh.yaml",
                    "test": "viash test config.vsh.yaml",
                    "ns_build": "viash ns build",
                },
            }
            return json.dumps(viash_docs, indent=2)

    elif uri == "documentation://docker":
        # Try to load cached documentation first
        cached_docs = await doc_generator.load_cached_documentation()
        if "docker" in cached_docs:
            return cached_docs["docker"]
        else:
            # Return generated Docker best practices
            return await doc_generator._generate_docker_docs()

    elif uri == "templates://spatial-workflows":
        # Try to load cached documentation first
        cached_docs = await doc_generator.load_cached_documentation()
        if "spatial_templates" in cached_docs:
            return cached_docs["spatial_templates"]
        else:
            # Return generated spatial workflow templates
            return await doc_generator._generate_spatial_templates()

    else:
        raise ValueError(f"Unknown resource URI: {uri}")


@server.list_tools()
async def handle_list_tools() -> List[Tool]:
    """List available tools for spatial transcriptomics workflows."""
    return [
        Tool(
            name="echo_test",
            description="Simple echo test to verify MCP communication",
            inputSchema={
                "type": "object",
                "properties": {
                    "message": {
                        "type": "string",
                        "description": "Message to echo back"
                    }
                },
                "required": ["message"]
            }
        ),
        Tool(
            name="list_available_tools",
            description="List all available MCP tools and their descriptions",
            inputSchema={
                "type": "object",
                "properties": {},
            }
        ),
        Tool(
            name="run_nextflow_workflow",
            description="Execute a Nextflow pipeline from OpenProblems repositories",
            inputSchema={
                "type": "object",
                "properties": {
                    "workflow_name": {
                        "type": "string",
                        "description": "Name of the Nextflow workflow (e.g., main.nf)"
                    },
                    "github_repo_url": {
                        "type": "string",
                        "description": "GitHub URL of the repository containing the workflow"
                    },
                    "profile": {
                        "type": "string",
                        "description": "Nextflow profile to use (e.g., docker, test)",
                        "default": "docker"
                    },
                    "params": {
                        "type": "object",
                        "description": "Key-value pairs for pipeline parameters",
                        "default": {}
                    },
                    "config_file": {
                        "type": "string",
                        "description": "Path to custom Nextflow configuration file"
                    }
                },
                "required": ["workflow_name", "github_repo_url"]
            }
        ),
        Tool(
            name="run_viash_component",
            description="Execute a Viash component with specified parameters",
            inputSchema={
                "type": "object",
                "properties": {
                    "component_name": {
                        "type": "string",
                        "description": "Name of the Viash component"
                    },
                    "component_config_path": {
                        "type": "string",
                        "description": "Path to the Viash config file (.vsh.yaml)"
                    },
                    "engine": {
                        "type": "string",
                        "description": "Execution engine (native, docker)",
                        "default": "docker"
                    },
                    "args": {
                        "type": "object",
                        "description": "Component-specific arguments",
                        "default": {}
                    }
                },
                "required": ["component_name", "component_config_path"]
            }
        ),
        Tool(
            name="build_docker_image",
            description="Build a Docker image from a Dockerfile",
            inputSchema={
                "type": "object",
                "properties": {
                    "dockerfile_path": {
                        "type": "string",
                        "description": "Path to the Dockerfile"
                    },
                    "image_tag": {
                        "type": "string",
                        "description": "Tag for the Docker image"
                    },
                    "context_path": {
                        "type": "string",
                        "description": "Build context directory",
                        "default": "."
                    }
                },
                "required": ["dockerfile_path", "image_tag"]
            }
        ),
        Tool(
            name="analyze_nextflow_log",
            description="Analyze Nextflow execution logs for errors and troubleshooting",
            inputSchema={
                "type": "object",
                "properties": {
                    "log_file_path": {
                        "type": "string",
                        "description": "Path to the .nextflow.log file"
                    }
                },
                "required": ["log_file_path"]
            }
        ),
        Tool(
            name="read_file",
            description="Read contents of a file for analysis or editing",
            inputSchema={
                "type": "object",
                "properties": {
                    "file_path": {
                        "type": "string",
                        "description": "Path to the file to read"
                    }
                },
                "required": ["file_path"]
            }
        ),
        Tool(
            name="write_file",
            description="Write or create a file with specified content",
            inputSchema={
                "type": "object",
                "properties": {
                    "file_path": {
                        "type": "string",
                        "description": "Path to the file to write"
                    },
                    "content": {
                        "type": "string",
                        "description": "Content to write to the file"
                    }
                },
                "required": ["file_path", "content"]
            }
        ),
        Tool(
            name="list_directory",
            description="List contents of a directory",
            inputSchema={
                "type": "object",
                "properties": {
                    "directory_path": {
                        "type": "string",
                        "description": "Path to the directory to list"
                    },
                    "include_hidden": {
                        "type": "boolean",
                        "description": "Include hidden files and directories",
                        "default": False
                    }
                },
                "required": ["directory_path"]
            }
        ),
        Tool(
            name="validate_nextflow_config",
            description="Validate Nextflow configuration and pipeline syntax",
            inputSchema={
                "type": "object",
                "properties": {
                    "config_path": {
                        "type": "string",
                        "description": "Path to nextflow.config file"
                    },
                    "pipeline_path": {
                        "type": "string",
                        "description": "Path to main.nf or pipeline file"
                    }
                },
                "required": ["pipeline_path"]
            }
        ),
        Tool(
            name="check_environment",
            description="Check if required tools and dependencies are installed",
            inputSchema={
                "type": "object",
                "properties": {
                    "tools": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "List of tools to check (nextflow, viash, docker, java, etc.)",
                        "default": ["nextflow", "viash", "docker", "java"]
                    }
                },
                "required": []
            }
        ),
    ]


@server.call_tool()
async def handle_call_tool(name: str, arguments: Dict[str, Any]) -> List[TextContent]:
    """Handle tool execution requests."""
    logger.info(f"Executing tool: {name} with arguments: {arguments}")

    if name == "echo_test":
        message = arguments.get("message", "")
        return [TextContent(type="text", text=f"Echo: {message}")]

    elif name == "list_available_tools":
        tools = await handle_list_tools()
        tool_list = []
        for tool in tools:
            tool_list.append({
                "name": tool.name,
                "description": tool.description,
                "required_params": tool.inputSchema.get("required", [])
            })
        return [TextContent(
            type="text",
            text=json.dumps(tool_list, indent=2)
        )]

    elif name == "run_nextflow_workflow":
        return await _execute_nextflow_workflow(arguments)

    elif name == "run_viash_component":
        return await _execute_viash_component(arguments)

    elif name == "build_docker_image":
        return await _build_docker_image(arguments)

    elif name == "analyze_nextflow_log":
        return await _analyze_nextflow_log(arguments)

    elif name == "read_file":
        return await _read_file(arguments)

    elif name == "write_file":
        return await _write_file(arguments)

    elif name == "list_directory":
        return await _list_directory(arguments)

    elif name == "validate_nextflow_config":
        return await _validate_nextflow_config(arguments)

    elif name == "check_environment":
        return await _check_environment(arguments)

    else:
        raise ValueError(f"Unknown tool: {name}")


async def _execute_nextflow_workflow(arguments: Dict[str, Any]) -> List[TextContent]:
    """Execute a Nextflow workflow."""
    workflow_name = arguments["workflow_name"]
    github_repo_url = arguments["github_repo_url"]
    profile = arguments.get("profile", "docker")
    params = arguments.get("params", {})
    config_file = arguments.get("config_file")

    # Build the command
    cmd = ["nextflow", "run", f"{github_repo_url}/{workflow_name}"]

    if profile:
        cmd.extend(["-profile", profile])

    if config_file:
        cmd.extend(["-c", config_file])

    # Add parameters
    for key, value in params.items():
        cmd.append(f"--{key}")
        cmd.append(str(value))

    try:
        # Execute the command
        logger.info(f"Executing command: {' '.join(cmd)}")
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=3600  # 1 hour timeout
        )

        execution_result = {
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr,
            "status": "completed" if result.returncode == 0 else "failed"
        }

        return [TextContent(
            type="text",
            text=json.dumps(execution_result, indent=2)
        )]

    except subprocess.TimeoutExpired:
        return [TextContent(
            type="text",
            text=json.dumps({
                "command": " ".join(cmd),
                "status": "timeout",
                "error": "Workflow execution timed out after 1 hour"
            }, indent=2)
        )]
    except Exception as e:
        return [TextContent(
            type="text",
            text=json.dumps({
                "command": " ".join(cmd),
                "status": "error",
                "error": str(e)
            }, indent=2)
        )]


async def _execute_viash_component(arguments: Dict[str, Any]) -> List[TextContent]:
    """Execute a Viash component."""
    component_name = arguments["component_name"]
    component_config_path = arguments["component_config_path"]
    engine = arguments.get("engine", "docker")
    args = arguments.get("args", {})

    # Build the command
    cmd = ["viash", "run", component_config_path, "-p", engine]

    # Add component arguments
    if args:
        cmd.append("--")
        for key, value in args.items():
            cmd.append(f"--{key}")
            cmd.append(str(value))

    try:
        logger.info(f"Executing Viash component: {' '.join(cmd)}")
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=1800  # 30 minutes timeout
        )

        execution_result = {
            "component": component_name,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr,
            "status": "completed" if result.returncode == 0 else "failed"
        }

        return [TextContent(
            type="text",
            text=json.dumps(execution_result, indent=2)
        )]

    except subprocess.TimeoutExpired:
        return [TextContent(
            type="text",
            text=json.dumps({
                "component": component_name,
                "command": " ".join(cmd),
                "status": "timeout",
                "error": "Component execution timed out after 30 minutes"
            }, indent=2)
        )]
    except Exception as e:
        return [TextContent(
            type="text",
            text=json.dumps({
                "component": component_name,
                "command": " ".join(cmd),
                "status": "error",
                "error": str(e)
            }, indent=2)
        )]


async def _build_docker_image(arguments: Dict[str, Any]) -> List[TextContent]:
    """Build a Docker image."""
    dockerfile_path = arguments["dockerfile_path"]
    image_tag = arguments["image_tag"]
    context_path = arguments.get("context_path", ".")

    cmd = ["docker", "build", "-t", image_tag, "-f", dockerfile_path, context_path]

    try:
        logger.info(f"Building Docker image: {' '.join(cmd)}")
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=1800  # 30 minutes timeout
        )

        build_result = {
            "image_tag": image_tag,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr,
            "status": "completed" if result.returncode == 0 else "failed"
        }

        return [TextContent(
            type="text",
            text=json.dumps(build_result, indent=2)
        )]

    except subprocess.TimeoutExpired:
        return [TextContent(
            type="text",
            text=json.dumps({
                "image_tag": image_tag,
                "command": " ".join(cmd),
                "status": "timeout",
                "error": "Docker build timed out after 30 minutes"
            }, indent=2)
        )]
    except Exception as e:
        return [TextContent(
            type="text",
            text=json.dumps({
                "image_tag": image_tag,
                "command": " ".join(cmd),
                "status": "error",
                "error": str(e)
            }, indent=2)
        )]


async def _analyze_nextflow_log(arguments: Dict[str, Any]) -> List[TextContent]:
    """Analyze Nextflow execution logs for errors and troubleshooting."""
    log_file_path = arguments["log_file_path"]

    try:
        log_path = Path(log_file_path)
        if not log_path.exists():
            return [TextContent(
                type="text",
                text=json.dumps({
                    "status": "error",
                    "error": f"Log file not found: {log_file_path}"
                }, indent=2)
            )]

        # Read and analyze the log file
        with open(log_path, 'r') as f:
            log_content = f.read()

        analysis = {
            "log_file": str(log_path),
            "file_size": log_path.stat().st_size,
            "issues_found": [],
            "suggestions": [],
        }

        # Common error patterns and their solutions
        error_patterns = {
            "exit status 137": {
                "issue": "Out of memory (OOM) error",
                "suggestion": "Increase memory allocation for the process or implement dynamic resource allocation"
            },
            "exit status 1": {
                "issue": "General execution error",
                "suggestion": "Check process logs for specific error details"
            },
            "command not found": {
                "issue": "Missing command or tool",
                "suggestion": "Ensure required tools are installed in the container or environment"
            },
            "No such file or directory": {
                "issue": "Missing input file",
                "suggestion": "Verify input file paths and ensure proper file staging"
            },
            "Permission denied": {
                "issue": "File permission error",
                "suggestion": "Check file permissions and container user settings"
            },
        }

        # Analyze log content for known patterns
        for pattern, info in error_patterns.items():
            if pattern.lower() in log_content.lower():
                analysis["issues_found"].append({
                    "pattern": pattern,
                    "issue": info["issue"],
                    "suggestion": info["suggestion"]
                })

        # Extract execution statistics if available
        if "Execution completed" in log_content:
            analysis["execution_status"] = "completed"
        elif "Execution cancelled" in log_content:
            analysis["execution_status"] = "cancelled"
        elif "Execution failed" in log_content:
            analysis["execution_status"] = "failed"
        else:
            analysis["execution_status"] = "unknown"

        return [TextContent(
            type="text",
            text=json.dumps(analysis, indent=2)
        )]

    except Exception as e:
        return [TextContent(
            type="text",
            text=json.dumps({
                "status": "error",
                "error": f"Failed to analyze log file: {str(e)}"
            }, indent=2)
        )]


async def _read_file(arguments: Dict[str, Any]) -> List[TextContent]:
    """Read contents of a file for analysis or editing."""
    file_path = arguments["file_path"]

    try:
        with open(file_path, 'r') as f:
            file_content = f.read()
        return [TextContent(type="text", text=file_content)]
    except Exception as e:
        return [TextContent(
            type="text",
            text=json.dumps({
                "status": "error",
                "error": f"Failed to read file: {str(e)}"
            }, indent=2)
        )]


async def _write_file(arguments: Dict[str, Any]) -> List[TextContent]:
    """Write or create a file with specified content."""
    file_path = arguments["file_path"]
    content = arguments["content"]

    try:
        with open(file_path, 'w') as f:
            f.write(content)
        return [TextContent(type="text", text="File written successfully")]
    except Exception as e:
        return [TextContent(
            type="text",
            text=json.dumps({
                "status": "error",
                "error": f"Failed to write file: {str(e)}"
            }, indent=2)
        )]


async def _list_directory(arguments: Dict[str, Any]) -> List[TextContent]:
    """List contents of a directory."""
    directory_path = arguments["directory_path"]
    include_hidden = arguments.get("include_hidden", False)

    try:
        entries = []
        for entry in Path(directory_path).iterdir():
            if include_hidden or not entry.name.startswith('.'):
                entries.append({
                    "name": entry.name,
                    "is_directory": entry.is_dir(),
                    "size": entry.stat().st_size
                })
        return [TextContent(
            type="text",
            text=json.dumps(entries, indent=2)
        )]
    except Exception as e:
        return [TextContent(
            type="text",
            text=json.dumps({
                "status": "error",
                "error": f"Failed to list directory: {str(e)}"
            }, indent=2)
        )]


async def _validate_nextflow_config(arguments: Dict[str, Any]) -> List[TextContent]:
    """Validate Nextflow configuration and pipeline syntax."""
    pipeline_path = arguments["pipeline_path"]
    config_path = arguments.get("config_path")

    validation_results = {
        "pipeline_path": pipeline_path,
        "config_path": config_path,
        "issues": [],
        "warnings": [],
        "status": "valid"
    }

    try:
        # Check if pipeline file exists
        pipeline_file = Path(pipeline_path)
        if not pipeline_file.exists():
            validation_results["issues"].append(f"Pipeline file not found: {pipeline_path}")
            validation_results["status"] = "invalid"
            return [TextContent(type="text", text=json.dumps(validation_results, indent=2))]

        # Read and check pipeline content
        with open(pipeline_file, 'r') as f:
            pipeline_content = f.read()

        # Basic Nextflow syntax checks
        if 'nextflow.enable.dsl=2' not in pipeline_content and 'nextflow { dsl = 2 }' not in pipeline_content:
            validation_results["warnings"].append("DSL2 not explicitly enabled - recommend adding 'nextflow.enable.dsl=2'")

        if 'process ' not in pipeline_content and 'workflow ' not in pipeline_content:
            validation_results["issues"].append("No process or workflow blocks found in pipeline")
            validation_results["status"] = "invalid"

        # Check for common issues
        if 'publishDir' in pipeline_content and 'output:' not in pipeline_content:
            validation_results["warnings"].append("publishDir found but no output block - this may cause issues")

        # Check config file if provided
        if config_path:
            config_file = Path(config_path)
            if not config_file.exists():
                validation_results["warnings"].append(f"Config file not found: {config_path}")
            else:
                with open(config_file, 'r') as f:
                    config_content = f.read()

                # Basic config validation
                if 'process ' in config_content:
                    validation_results["warnings"].append("Config looks good - process configuration found")

        # Try to run nextflow validation if available
        try:
            result = subprocess.run(
                ["nextflow", "config", pipeline_path],
                capture_output=True, text=True, timeout=30
            )
            if result.returncode != 0:
                validation_results["issues"].append(f"Nextflow config validation failed: {result.stderr}")
                validation_results["status"] = "invalid"
        except (subprocess.TimeoutExpired, FileNotFoundError):
            validation_results["warnings"].append("Nextflow not available - performed basic syntax check only")

        return [TextContent(type="text", text=json.dumps(validation_results, indent=2))]

    except Exception as e:
        return [TextContent(
            type="text",
            text=json.dumps({
                "status": "error",
                "error": f"Failed to validate Nextflow configuration: {str(e)}"
            }, indent=2)
        )]


async def _check_environment(arguments: Dict[str, Any]) -> List[TextContent]:
    """Check if required tools and dependencies are installed."""
    tools = arguments.get("tools", ["nextflow", "viash", "docker", "java"])

    environment_status = {
        "overall_status": "ready",
        "tools": {},
        "recommendations": []
    }

    try:
        for tool in tools:
            tool_status = {"available": False, "version": None, "path": None}

            try:
                if tool == "nextflow":
                    result = subprocess.run(["nextflow", "-version"], capture_output=True, text=True, timeout=10)
                    if result.returncode == 0:
                        tool_status["available"] = True
                        tool_status["version"] = result.stdout.strip()
                        tool_status["path"] = subprocess.run(["which", "nextflow"], capture_output=True, text=True).stdout.strip()

                elif tool == "viash":
                    result = subprocess.run(["viash", "--version"], capture_output=True, text=True, timeout=10)
                    if result.returncode == 0:
                        tool_status["available"] = True
                        tool_status["version"] = result.stdout.strip()
                        tool_status["path"] = subprocess.run(["which", "viash"], capture_output=True, text=True).stdout.strip()

                elif tool == "docker":
                    result = subprocess.run(["docker", "--version"], capture_output=True, text=True, timeout=10)
                    if result.returncode == 0:
                        tool_status["available"] = True
                        tool_status["version"] = result.stdout.strip()
                        tool_status["path"] = subprocess.run(["which", "docker"], capture_output=True, text=True).stdout.strip()

                elif tool == "java":
                    result = subprocess.run(["java", "-version"], capture_output=True, text=True, timeout=10)
                    if result.returncode == 0:
                        tool_status["available"] = True
                        tool_status["version"] = result.stderr.strip()  # Java outputs version to stderr
                        tool_status["path"] = subprocess.run(["which", "java"], capture_output=True, text=True).stdout.strip()

                else:
                    # Generic tool check
                    result = subprocess.run([tool, "--version"], capture_output=True, text=True, timeout=10)
                    if result.returncode == 0:
                        tool_status["available"] = True
                        tool_status["version"] = result.stdout.strip()
                        tool_status["path"] = subprocess.run(["which", tool], capture_output=True, text=True).stdout.strip()

            except (subprocess.TimeoutExpired, FileNotFoundError):
                tool_status["available"] = False

            environment_status["tools"][tool] = tool_status

            # Add recommendations for missing tools
            if not tool_status["available"]:
                environment_status["overall_status"] = "incomplete"
                if tool == "nextflow":
                    environment_status["recommendations"].append("Install Nextflow: curl -s https://get.nextflow.io | bash")
                elif tool == "viash":
                    environment_status["recommendations"].append("Install Viash: curl -fsSL get.viash.io | bash")
                elif tool == "docker":
                    environment_status["recommendations"].append("Install Docker: https://docs.docker.com/get-docker/")
                elif tool == "java":
                    environment_status["recommendations"].append("Install Java: sudo apt install openjdk-17-jre-headless")

        return [TextContent(type="text", text=json.dumps(environment_status, indent=2))]

    except Exception as e:
        return [TextContent(
            type="text",
            text=json.dumps({
                "status": "error",
                "error": f"Failed to check environment: {str(e)}"
            }, indent=2)
        )]


async def main():
    """Main entry point for the MCP server."""
    logger.info(f"Starting {SERVER_NAME} v{SERVER_VERSION}")

    async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
        await server.run(
            read_stream,
            write_stream,
            InitializationOptions(
                server_name=SERVER_NAME,
                server_version=SERVER_VERSION,
                capabilities={
                    "resources": {},
                    "tools": {},
                    "prompts": {},
                    "logging": {}
                },
            ),
        )


if __name__ == "__main__":
    asyncio.run(main())