File size: 21,963 Bytes
d9bc96c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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
import subprocess
import tempfile
from pathlib import Path
from typing import List, Optional

# This is a placeholder for the MCP decorator.
# In a real MCP environment, this would be provided by the MCP framework.
def tool(func):
    """A dummy decorator to stand in for @mcp.tool()."""
    return func

mcp = type("mcp", (), {"tool": tool})


from mcp.server.fastmcp import FastMCP

SERVER_NAME = 'local_bedtools'
mcp = FastMCP(SERVER_NAME)

@mcp.tool()
def intersect(
    a: Path,
    b: List[Path],
    output: Optional[Path] = None,
    wa: bool = False,
    wb: bool = False,
    loj: bool = False,
    wo: bool = False,
    wao: bool = False,
    u: bool = False,
    c: bool = False,
    v: bool = False,
    ubam: bool = False,
    s: bool = False,
    S: bool = False,
    f: float = 1e-9,
    F: float = 1e-9,
    r: bool = False,
    e: bool = False,
    split: bool = False,
    g: Optional[Path] = None,
    header: bool = False,
    bed: bool = False,
    sorted: bool = False,
    names: Optional[str] = None,
    filenames: bool = False,
    nonamecheck: bool = False,
):
    """
    Find overlapping intervals in two or more BED/GFF/VCF/BAM files.

    This tool allows one to screen for overlaps between two sets of genomic features.
    """
    # Input validation
    if not a.exists():
        raise FileNotFoundError(f"Input file -a does not exist: {a}")
    for b_file in b:
        if not b_file.exists():
            raise FileNotFoundError(f"Input file in -b list does not exist: {b_file}")
    if g and not g.exists():
        raise FileNotFoundError(f"Genome file -g does not exist: {g}")

    exclusive_flags = [u, c, v, wo, wao]
    if sum(exclusive_flags) > 1:
        raise ValueError("Options -u, -c, -v, -wo, -wao are mutually exclusive.")
    if s and S:
        raise ValueError("Options -s and -S are mutually exclusive.")
    if f < 0.0 or f > 1.0:
        raise ValueError("-f (fraction) must be between 0.0 and 1.0.")
    if F < 0.0 or F > 1.0:
        raise ValueError("-F (fraction) must be between 0.0 and 1.0.")
    if sorted and not g:
        raise ValueError("The -sorted option requires a genome file (-g).")

    # Command construction
    cmd = ["bedtools", "intersect", "-a", str(a), "-b"]
    cmd.extend([str(p) for p in b])

    if wa: cmd.append("-wa")
    if wb: cmd.append("-wb")
    if loj: cmd.append("-loj")
    if wo: cmd.append("-wo")
    if wao: cmd.append("-wao")
    if u: cmd.append("-u")
    if c: cmd.append("-c")
    if v: cmd.append("-v")
    if ubam: cmd.append("-ubam")
    if s: cmd.append("-s")
    if S: cmd.append("-S")
    if f != 1e-9: cmd.extend(["-f", str(f)])
    if F != 1e-9: cmd.extend(["-F", str(F)])
    if r: cmd.append("-r")
    if e: cmd.append("-e")
    if split: cmd.append("-split")
    if g: cmd.extend(["-g", str(g)])
    if header: cmd.append("-header")
    if bed: cmd.append("-bed")
    if sorted: cmd.append("-sorted")
    if names: cmd.extend(["-names", names])
    if filenames: cmd.append("-filenames")
    if nonamecheck: cmd.append("-nonamecheck")

    # Subprocess execution
    command_executed = " ".join(cmd)
    output_files = []
    stdout_capture, stderr_capture = "", ""

    try:
        if output:
            output_files.append(str(output))
            with open(output, "w") as f_out:
                result = subprocess.run(
                    cmd, check=True, text=True, stdout=f_out, stderr=subprocess.PIPE
                )
            stderr_capture = result.stderr
        else:
            result = subprocess.run(
                cmd, check=True, text=True, capture_output=True
            )
            stdout_capture = result.stdout
            stderr_capture = result.stderr
    except subprocess.CalledProcessError as e:
        return {
            "command_executed": command_executed,
            "stdout": e.stdout or "",
            "stderr": e.stderr or "CalledProcessError with no stderr.",
            "output_files": [],
            "return_code": e.returncode,
        }

    return {
        "command_executed": command_executed,
        "stdout": stdout_capture,
        "stderr": stderr_capture,
        "output_files": output_files,
    }


@mcp.tool()
def merge(
    i: Path,
    output: Optional[Path] = None,
    s: bool = False,
    S: Optional[str] = None,
    d: int = 0,
    c: Optional[str] = None,
    o: Optional[str] = None,
    header: bool = False,
    delim: str = ";",
    n: bool = False,
    nms: bool = False,
    scores: Optional[str] = None,
    bed: bool = False,
    prec: int = 5,
):
    """
    Merge overlapping features in a BED/GFF/VCF file.

    This tool combines overlapping or "book-ended" features into a single feature.
    """
    # Input validation
    if not i.exists():
        raise FileNotFoundError(f"Input file -i does not exist: {i}")
    if S and S not in ["+", "-"]:
        raise ValueError("Option -S must be either '+' or '-'.")
    if s and S:
        raise ValueError("Options -s and -S are mutually exclusive.")
    if d < 0:
        raise ValueError("Option -d (distance) must be a non-negative integer.")
    if (c and not o) or (o and not c):
        raise ValueError("Options -c and -o must be used together.")
    if c and o:
        if len(c.split(',')) != len(o.split(',')):
            raise ValueError("The number of columns in -c must match the number of operations in -o.")

    # Command construction
    cmd = ["bedtools", "merge", "-i", str(i)]

    if s: cmd.append("-s")
    if S: cmd.extend(["-S", S])
    if d > 0: cmd.extend(["-d", str(d)])
    if c: cmd.extend(["-c", c])
    if o: cmd.extend(["-o", o])
    if header: cmd.append("-header")
    if delim != ";": cmd.extend(["-delim", delim])
    if n: cmd.append("-n")
    if nms: cmd.append("-nms")
    if scores: cmd.extend(["-scores", scores])
    if bed: cmd.append("-bed")
    if prec != 5: cmd.extend(["-prec", str(prec)])

    # Subprocess execution
    command_executed = " ".join(cmd)
    output_files = []
    stdout_capture, stderr_capture = "", ""

    try:
        if output:
            output_files.append(str(output))
            with open(output, "w") as f_out:
                result = subprocess.run(
                    cmd, check=True, text=True, stdout=f_out, stderr=subprocess.PIPE
                )
            stderr_capture = result.stderr
        else:
            result = subprocess.run(
                cmd, check=True, text=True, capture_output=True
            )
            stdout_capture = result.stdout
            stderr_capture = result.stderr
    except subprocess.CalledProcessError as e:
        return {
            "command_executed": command_executed,
            "stdout": e.stdout or "",
            "stderr": e.stderr or "CalledProcessError with no stderr.",
            "output_files": [],
            "return_code": e.returncode,
        }

    return {
        "command_executed": command_executed,
        "stdout": stdout_capture,
        "stderr": stderr_capture,
        "output_files": output_files,
    }


@mcp.tool()
def subtract(
    a: Path,
    b: List[Path],
    output: Optional[Path] = None,
    f: float = 1e-9,
    F: float = 1e-9,
    r: bool = False,
    e: bool = False,
    s: bool = False,
    S: bool = False,
    A: bool = False,
    B: bool = False,
    N: bool = False,
    header: bool = False,
    g: Optional[Path] = None,
):
    """
    Remove overlapping intervals from a BED/GFF/VCF file.

    This tool removes portions of features in file A that are overlapped by features in file(s) B.
    """
    # Input validation
    if not a.exists():
        raise FileNotFoundError(f"Input file -a does not exist: {a}")
    for b_file in b:
        if not b_file.exists():
            raise FileNotFoundError(f"Input file in -b list does not exist: {b_file}")
    if g and not g.exists():
        raise FileNotFoundError(f"Genome file -g does not exist: {g}")
    if A and B:
        raise ValueError("Options -A and -B are mutually exclusive.")
    if s and S:
        raise ValueError("Options -s and -S are mutually exclusive.")

    # Command construction
    cmd = ["bedtools", "subtract", "-a", str(a), "-b"]
    cmd.extend([str(p) for p in b])

    if f != 1e-9: cmd.extend(["-f", str(f)])
    if F != 1e-9: cmd.extend(["-F", str(F)])
    if r: cmd.append("-r")
    if e: cmd.append("-e")
    if s: cmd.append("-s")
    if S: cmd.append("-S")
    if A: cmd.append("-A")
    if B: cmd.append("-B")
    if N: cmd.append("-N")
    if header: cmd.append("-header")
    if g: cmd.extend(["-g", str(g)])

    # Subprocess execution
    command_executed = " ".join(cmd)
    output_files = []
    stdout_capture, stderr_capture = "", ""

    try:
        if output:
            output_files.append(str(output))
            with open(output, "w") as f_out:
                result = subprocess.run(
                    cmd, check=True, text=True, stdout=f_out, stderr=subprocess.PIPE
                )
            stderr_capture = result.stderr
        else:
            result = subprocess.run(
                cmd, check=True, text=True, capture_output=True
            )
            stdout_capture = result.stdout
            stderr_capture = result.stderr
    except subprocess.CalledProcessError as e:
        return {
            "command_executed": command_executed,
            "stdout": e.stdout or "",
            "stderr": e.stderr or "CalledProcessError with no stderr.",
            "output_files": [],
            "return_code": e.returncode,
        }

    return {
        "command_executed": command_executed,
        "stdout": stdout_capture,
        "stderr": stderr_capture,
        "output_files": output_files,
    }


@mcp.tool()
def slop(
    i: Path,
    g: Path,
    output: Optional[Path] = None,
    b: int = 0,
    l: int = 0,
    r: int = 0,
    s: bool = False,
    pct: bool = False,
    header: bool = False,
):
    """
    Increase the size of features in a BED/GFF/VCF file.

    This tool will increase the size of each feature in a feature file by a user-defined number of bases.
    """
    # Input validation
    if not i.exists():
        raise FileNotFoundError(f"Input file -i does not exist: {i}")
    if not g.exists():
        raise FileNotFoundError(f"Genome file -g does not exist: {g}")
    if b != 0 and (l != 0 or r != 0):
        raise ValueError("Option -b cannot be used with -l or -r.")

    # Command construction
    cmd = ["bedtools", "slop", "-i", str(i), "-g", str(g)]

    if b != 0: cmd.extend(["-b", str(b)])
    if l != 0: cmd.extend(["-l", str(l)])
    if r != 0: cmd.extend(["-r", str(r)])
    if s: cmd.append("-s")
    if pct: cmd.append("-pct")
    if header: cmd.append("-header")

    # Subprocess execution
    command_executed = " ".join(cmd)
    output_files = []
    stdout_capture, stderr_capture = "", ""

    try:
        if output:
            output_files.append(str(output))
            with open(output, "w") as f_out:
                result = subprocess.run(
                    cmd, check=True, text=True, stdout=f_out, stderr=subprocess.PIPE
                )
            stderr_capture = result.stderr
        else:
            result = subprocess.run(
                cmd, check=True, text=True, capture_output=True
            )
            stdout_capture = result.stdout
            stderr_capture = result.stderr
    except subprocess.CalledProcessError as e:
        return {
            "command_executed": command_executed,
            "stdout": e.stdout or "",
            "stderr": e.stderr or "CalledProcessError with no stderr.",
            "output_files": [],
            "return_code": e.returncode,
        }

    return {
        "command_executed": command_executed,
        "stdout": stdout_capture,
        "stderr": stderr_capture,
        "output_files": output_files,
    }


@mcp.tool()
def getfasta(
    fi: Path,
    bed: Path,
    fo: Optional[Path] = None,
    s: bool = False,
    split: bool = False,
    name: bool = False,
    name_plus: bool = False,
    tab: bool = False,
    full_header: bool = False,
):
    """
    Extract DNA sequences from a FASTA file based on BED/GFF/VCF coordinates.
    """
    # Input validation
    if not fi.exists():
        raise FileNotFoundError(f"FASTA input file -fi does not exist: {fi}")
    if not bed.exists():
        raise FileNotFoundError(f"BED/GFF/VCF file -bed does not exist: {bed}")
    if name and name_plus:
        raise ValueError("Options -name and -name+ are mutually exclusive.")

    # Command construction
    cmd = ["bedtools", "getfasta", "-fi", str(fi), "-bed", str(bed)]

    if s: cmd.append("-s")
    if split: cmd.append("-split")
    if name: cmd.append("-name")
    if name_plus: cmd.append("-name+")
    if tab: cmd.append("-tab")
    if full_header: cmd.append("-fullHeader")
    if fo: cmd.extend(["-fo", str(fo)])

    # Subprocess execution
    command_executed = " ".join(cmd)
    output_files = []
    stdout_capture, stderr_capture = "", ""

    try:
        # getfasta is unique in that it has a dedicated -fo parameter
        # and doesn't typically write to stdout if -fo is used.
        result = subprocess.run(
            cmd, check=True, text=True, capture_output=True
        )
        stdout_capture = result.stdout
        stderr_capture = result.stderr
        if fo:
            output_files.append(str(fo))

    except subprocess.CalledProcessError as e:
        return {
            "command_executed": command_executed,
            "stdout": e.stdout or "",
            "stderr": e.stderr or "CalledProcessError with no stderr.",
            "output_files": [],
            "return_code": e.returncode,
        }

    return {
        "command_executed": command_executed,
        "stdout": stdout_capture,
        "stderr": stderr_capture,
        "output_files": output_files,
    }


@mcp.tool()
def sort(
    i: Path,
    output: Optional[Path] = None,
    header: bool = False,
    g: Optional[Path] = None,
    faidx: Optional[Path] = None,
    sizeA: bool = False,
    sizeD: bool = False,
    chrThenSizeA: bool = False,
    chrThenSizeD: bool = False,
    chrThenScoreA: bool = False,
    chrThenScoreD: bool = False,
):
    """
    Sort a BED/GFF/VCF file by chromosome and then by start position.
    """
    # Input validation
    if not i.exists():
        raise FileNotFoundError(f"Input file -i does not exist: {i}")
    if g and not g.exists():
        raise FileNotFoundError(f"Genome file -g does not exist: {g}")
    if faidx and not faidx.exists():
        raise FileNotFoundError(f"FASTA index file -faidx does not exist: {faidx}")

    sort_flags = [sizeA, sizeD, chrThenSizeA, chrThenSizeD, chrThenScoreA, chrThenScoreD]
    if sum(sort_flags) > 1:
        raise ValueError("Multiple sorting order flags were provided, but only one is allowed.")

    # Command construction
    cmd = ["bedtools", "sort", "-i", str(i)]

    if header: cmd.append("-header")
    if g: cmd.extend(["-g", str(g)])
    if faidx: cmd.extend(["-faidx", str(faidx)])
    if sizeA: cmd.append("-sizeA")
    if sizeD: cmd.append("-sizeD")
    if chrThenSizeA: cmd.append("-chrThenSizeA")
    if chrThenSizeD: cmd.append("-chrThenSizeD")
    if chrThenScoreA: cmd.append("-chrThenScoreA")
    if chrThenScoreD: cmd.append("-chrThenScoreD")

    # Subprocess execution
    command_executed = " ".join(cmd)
    output_files = []
    stdout_capture, stderr_capture = "", ""

    try:
        if output:
            output_files.append(str(output))
            with open(output, "w") as f_out:
                result = subprocess.run(
                    cmd, check=True, text=True, stdout=f_out, stderr=subprocess.PIPE
                )
            stderr_capture = result.stderr
        else:
            result = subprocess.run(
                cmd, check=True, text=True, capture_output=True
            )
            stdout_capture = result.stdout
            stderr_capture = result.stderr
    except subprocess.CalledProcessError as e:
        return {
            "command_executed": command_executed,
            "stdout": e.stdout or "",
            "stderr": e.stderr or "CalledProcessError with no stderr.",
            "output_files": [],
            "return_code": e.returncode,
        }

    return {
        "command_executed": command_executed,
        "stdout": stdout_capture,
        "stderr": stderr_capture,
        "output_files": output_files,
    }


@mcp.tool()
def coverage(
    a: Path,
    b: List[Path],
    output: Optional[Path] = None,
    s: bool = False,
    S: bool = False,
    f: float = 1e-9,
    F: float = 1e-9,
    r: bool = False,
    e: bool = False,
    split: bool = False,
    d: bool = False,
    counts: bool = False,
    hist: bool = False,
    mean: bool = False,
    g: Optional[Path] = None,
    header: bool = False,
    sorted: bool = False,
):
    """
    Compute the coverage of features in file A on features in file(s) B.
    """
    # Input validation
    if not a.exists():
        raise FileNotFoundError(f"Input file -a does not exist: {a}")
    for b_file in b:
        if not b_file.exists():
            raise FileNotFoundError(f"Input file in -b list does not exist: {b_file}")
    if g and not g.exists():
        raise FileNotFoundError(f"Genome file -g does not exist: {g}")
    if s and S:
        raise ValueError("Options -s and -S are mutually exclusive.")
    if sorted and not g:
        raise ValueError("The -sorted option requires a genome file (-g).")

    # Command construction
    cmd = ["bedtools", "coverage", "-a", str(a), "-b"]
    cmd.extend([str(p) for p in b])

    if s: cmd.append("-s")
    if S: cmd.append("-S")
    if f != 1e-9: cmd.extend(["-f", str(f)])
    if F != 1e-9: cmd.extend(["-F", str(F)])
    if r: cmd.append("-r")
    if e: cmd.append("-e")
    if split: cmd.append("-split")
    if d: cmd.append("-d")
    if counts: cmd.append("-counts")
    if hist: cmd.append("-hist")
    if mean: cmd.append("-mean")
    if g: cmd.extend(["-g", str(g)])
    if header: cmd.append("-header")
    if sorted: cmd.append("-sorted")

    # Subprocess execution
    command_executed = " ".join(cmd)
    output_files = []
    stdout_capture, stderr_capture = "", ""

    try:
        if output:
            output_files.append(str(output))
            with open(output, "w") as f_out:
                result = subprocess.run(
                    cmd, check=True, text=True, stdout=f_out, stderr=subprocess.PIPE
                )
            stderr_capture = result.stderr
        else:
            result = subprocess.run(
                cmd, check=True, text=True, capture_output=True
            )
            stdout_capture = result.stdout
            stderr_capture = result.stderr
    except subprocess.CalledProcessError as e:
        return {
            "command_executed": command_executed,
            "stdout": e.stdout or "",
            "stderr": e.stderr or "CalledProcessError with no stderr.",
            "output_files": [],
            "return_code": e.returncode,
        }

    return {
        "command_executed": command_executed,
        "stdout": stdout_capture,
        "stderr": stderr_capture,
        "output_files": output_files,
    }


@mcp.tool()
def genomecov(
    i: Path,
    g: Path,
    output: Optional[Path] = None,
    d: bool = False,
    dz: bool = False,
    bga: bool = False,
    bg: bool = False,
    scale: float = 1.0,
    pc: bool = False,
    fs: bool = False,
    split: bool = False,
    strand: Optional[str] = None,
    max: int = 0,
    trackline: bool = False,
    trackopts: Optional[str] = None,
):
    """
    Compute genome-wide coverage of a feature file.
    """
    # Input validation
    if not i.exists():
        raise FileNotFoundError(f"Input file -i does not exist: {i}")
    if not g.exists():
        raise FileNotFoundError(f"Genome file -g does not exist: {g}")
    if strand and strand not in ["+", "-"]:
        raise ValueError("Option -strand must be either '+' or '-'.")
    if max < 0:
        raise ValueError("Option -max must be a non-negative integer.")
    output_modes = [d, dz, bga, bg]
    if sum(output_modes) > 1:
        raise ValueError("Output format flags (-d, -dz, -bga, -bg) are mutually exclusive.")

    # Command construction
    cmd = ["bedtools", "genomecov", "-i", str(i), "-g", str(g)]

    if d: cmd.append("-d")
    if dz: cmd.append("-dz")
    if bga: cmd.append("-bga")
    if bg: cmd.append("-bg")
    if scale != 1.0: cmd.extend(["-scale", str(scale)])
    if pc: cmd.append("-pc")
    if fs: cmd.append("-fs")
    if split: cmd.append("-split")
    if strand: cmd.extend(["-strand", strand])
    if max > 0: cmd.extend(["-max", str(max)])
    if trackline: cmd.append("-trackline")
    if trackopts: cmd.extend(["-trackopts", trackopts])

    # Subprocess execution
    command_executed = " ".join(cmd)
    output_files = []
    stdout_capture, stderr_capture = "", ""

    try:
        if output:
            output_files.append(str(output))
            with open(output, "w") as f_out:
                result = subprocess.run(
                    cmd, check=True, text=True, stdout=f_out, stderr=subprocess.PIPE
                )
            stderr_capture = result.stderr
        else:
            result = subprocess.run(
                cmd, check=True, text=True, capture_output=True
            )
            stdout_capture = result.stdout
            stderr_capture = result.stderr
    except subprocess.CalledProcessError as e:
        return {
            "command_executed": command_executed,
            "stdout": e.stdout or "",
            "stderr": e.stderr or "CalledProcessError with no stderr.",
            "output_files": [],
            "return_code": e.returncode,
        }

    return {
        "command_executed": command_executed,
        "stdout": stdout_capture,
        "stderr": stderr_capture,
        "output_files": output_files,
    }

if __name__ == "__main__":
    mcp.run(transport="stdio")