File size: 26,523 Bytes
98262e8
7c466d5
 
 
 
 
 
 
 
98262e8
7c466d5
98262e8
d1d50db
162c9ed
7c466d5
 
 
 
a506ee1
9adbb54
927e044
162c9ed
7c466d5
 
 
 
 
98262e8
7c466d5
98262e8
 
7c466d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f9ffee
7c466d5
 
 
 
 
 
a506ee1
7c466d5
 
2f3af13
dd7600a
 
 
7c466d5
 
dd7600a
7c466d5
dd7600a
 
 
 
 
 
 
 
 
7c466d5
 
 
 
 
 
 
 
 
dd7600a
 
 
7c466d5
a506ee1
2f3af13
 
 
 
7c466d5
 
 
98262e8
d1d50db
 
 
 
 
 
 
 
 
 
 
98262e8
7c466d5
 
 
 
 
ad568fb
7c466d5
 
 
 
 
 
 
d1d50db
 
4ef7799
 
 
 
d1d50db
 
 
 
7c466d5
 
98262e8
a4ec518
5f2c09d
98262e8
7c466d5
 
98262e8
 
7c466d5
 
 
 
 
98262e8
7c466d5
 
98262e8
7c466d5
 
6537199
 
98262e8
6537199
 
 
 
 
 
98262e8
6537199
 
 
 
 
 
98262e8
6537199
 
 
 
dd7600a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c466d5
98262e8
 
 
5f2c09d
98262e8
5f2c09d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a506ee1
7c466d5
 
 
 
 
 
 
 
6537199
 
7c466d5
 
 
 
 
5f2c09d
a4ec518
5f2c09d
 
 
 
 
 
 
 
 
 
7c466d5
 
6537199
 
 
 
 
7c466d5
 
 
 
 
 
 
 
 
 
6537199
 
 
 
2f3af13
dd7600a
 
 
 
 
 
 
2f3af13
6537199
7c466d5
 
 
6537199
7c466d5
 
6537199
7c466d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98262e8
a4ec518
5f2c09d
cbb550a
7c466d5
2e1c8b2
98262e8
 
 
7c466d5
 
346a696
 
98262e8
346a696
c9eb71f
346a696
 
 
 
98262e8
 
c9eb71f
346a696
 
798d2ed
 
 
 
 
 
 
346a696
98262e8
 
 
 
346a696
 
2f3af13
 
98262e8
2f3af13
 
98262e8
2f3af13
 
dd7600a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c466d5
98262e8
7c466d5
5f2c09d
1988304
 
 
 
5f2c09d
 
fc7e104
9d2dc87
 
98262e8
 
5f2c09d
c9eb71f
5f2c09d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c466d5
a506ee1
7c466d5
a506ee1
7c466d5
346a696
 
798d2ed
346a696
cbb550a
7c466d5
 
 
5f2c09d
 
 
 
 
 
 
 
dd7600a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4ec518
dd7600a
 
 
 
 
 
cbb550a
dd7600a
 
 
 
 
 
 
 
 
 
 
7c466d5
 
98262e8
 
5f2c09d
98262e8
923cf05
 
98262e8
 
923cf05
 
 
5f2c09d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
923cf05
98262e8
923cf05
98262e8
 
 
923cf05
 
 
 
 
 
5f2c09d
 
923cf05
98262e8
5f2c09d
98262e8
5f2c09d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
923cf05
 
 
 
 
 
 
 
 
 
 
 
 
 
a4ec518
923cf05
98262e8
 
162c9ed
 
923cf05
 
 
 
 
 
162c9ed
923cf05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98262e8
 
5f2c09d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98262e8
 
 
 
 
 
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
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
"""FastMCP CLI tools using Cyclopts."""

import importlib.metadata
import importlib.util
import os
import platform
import subprocess
import sys
from pathlib import Path
from typing import Annotated, Literal

import cyclopts
import pyperclip
from pydantic import TypeAdapter
from rich.console import Console
from rich.table import Table

import fastmcp
from fastmcp.cli import run as run_module
from fastmcp.cli.install import install_app
from fastmcp.server.server import FastMCP
from fastmcp.utilities.inspect import FastMCPInfo, inspect_fastmcp
from fastmcp.utilities.logging import get_logger

logger = get_logger("cli")
console = Console()

app = cyclopts.App(
    name="fastmcp",
    help="FastMCP 2.0 - The fast, Pythonic way to build MCP servers and clients.",
    version=fastmcp.__version__,
)


def _get_npx_command():
    """Get the correct npx command for the current platform."""
    if sys.platform == "win32":
        # Try both npx.cmd and npx.exe on Windows
        for cmd in ["npx.cmd", "npx.exe", "npx"]:
            try:
                subprocess.run(
                    [cmd, "--version"], check=True, capture_output=True, shell=True
                )
                return cmd
            except subprocess.CalledProcessError:
                continue
        return None
    return "npx"  # On Unix-like systems, just use npx


def _parse_env_var(env_var: str) -> tuple[str, str]:
    """Parse environment variable string in format KEY=VALUE."""
    if "=" not in env_var:
        logger.error("Invalid environment variable format. Must be KEY=VALUE")
        sys.exit(1)
    key, value = env_var.split("=", 1)
    return key.strip(), value.strip()


def _build_uv_command(
    server_spec: str,
    with_editable: Path | None = None,
    with_packages: list[str] | None = None,
    no_banner: bool = False,
    python_version: str | None = None,
    with_requirements: Path | None = None,
    project: Path | None = None,
) -> list[str]:
    """Build the uv run command that runs a MCP server through mcp run."""
    cmd = ["uv", "run"]

    # Add Python version if specified
    if python_version:
        cmd.extend(["--python", python_version])

    # Add project if specified
    if project:
        cmd.extend(["--project", str(project)])

    cmd.extend(["--with", "fastmcp"])

    if with_editable:
        cmd.extend(["--with-editable", str(with_editable)])

    if with_packages:
        for pkg in with_packages:
            if pkg:
                cmd.extend(["--with", pkg])

    if with_requirements:
        cmd.extend(["--with-requirements", str(with_requirements)])

    # Add mcp run command
    cmd.extend(["fastmcp", "run", server_spec])

    if no_banner:
        cmd.append("--no-banner")

    return cmd


@app.command
def version(
    *,
    copy: Annotated[
        bool,
        cyclopts.Parameter(
            "--copy",
            help="Copy version information to clipboard",
            negative=False,
        ),
    ] = False,
):
    """Display version information and platform details."""
    info = {
        "FastMCP version": fastmcp.__version__,
        "MCP version": importlib.metadata.version("mcp"),
        "Python version": platform.python_version(),
        "Platform": platform.platform(),
        "FastMCP root path": Path(fastmcp.__file__).resolve().parents[1],
    }

    g = Table.grid(padding=(0, 1))
    g.add_column(style="bold", justify="left")
    g.add_column(style="cyan", justify="right")
    for k, v in info.items():
        g.add_row(k + ":", str(v).replace("\n", " "))

    if copy:
        # Use Rich's plain text rendering for copying
        plain_console = Console(file=None, force_terminal=False, legacy_windows=False)
        with plain_console.capture() as capture:
            plain_console.print(g)
        pyperclip.copy(capture.get())
        console.print("[green]✓[/green] Version information copied to clipboard")
    else:
        console.print(g)


@app.command
async def dev(
    server_spec: str | None = None,
    *,
    with_editable: Annotated[
        Path | None,
        cyclopts.Parameter(
            name=["--with-editable", "-e"],
            help="Directory containing pyproject.toml to install in editable mode",
        ),
    ] = None,
    with_packages: Annotated[
        list[str],
        cyclopts.Parameter(
            "--with",
            help="Additional packages to install",
            negative=False,
        ),
    ] = [],
    inspector_version: Annotated[
        str | None,
        cyclopts.Parameter(
            "--inspector-version",
            help="Version of the MCP Inspector to use",
        ),
    ] = None,
    ui_port: Annotated[
        int | None,
        cyclopts.Parameter(
            "--ui-port",
            help="Port for the MCP Inspector UI",
        ),
    ] = None,
    server_port: Annotated[
        int | None,
        cyclopts.Parameter(
            "--server-port",
            help="Port for the MCP Inspector Proxy server",
        ),
    ] = None,
    python: Annotated[
        str | None,
        cyclopts.Parameter(
            "--python",
            help="Python version to use (e.g., 3.10, 3.11)",
        ),
    ] = None,
    with_requirements: Annotated[
        Path | None,
        cyclopts.Parameter(
            "--with-requirements",
            help="Requirements file to install dependencies from",
        ),
    ] = None,
    project: Annotated[
        Path | None,
        cyclopts.Parameter(
            "--project",
            help="Run the command within the given project directory",
        ),
    ] = None,
) -> None:
    """Run an MCP server with the MCP Inspector for development.

    Args:
        server_spec: Python file to run, optionally with :object suffix, or None to auto-detect fastmcp.json
    """
    # Auto-detect fastmcp.json if no server_spec provided
    if server_spec is None:
        from pathlib import Path

        from fastmcp.utilities.fastmcp_config import FastMCPConfig

        config_path = Path("fastmcp.json")
        if not config_path.exists():
            # Check if fastmcp.json exists in current directory
            found_config = FastMCPConfig.find_config()
            if found_config:
                config_path = found_config
            else:
                logger.error(
                    "No server specification provided and no fastmcp.json found in current directory.\n"
                    "Please specify a server file or create a fastmcp.json configuration."
                )
                sys.exit(1)

        # Load the config to get settings
        config = FastMCPConfig.from_file(config_path)
        entrypoint = config.get_entrypoint(config_path)

        # Convert entrypoint to string format for dev command
        if entrypoint.object:
            server_spec = f"{entrypoint.file}:{entrypoint.object}"
        else:
            server_spec = entrypoint.file

        # Merge environment settings with CLI args (CLI takes precedence)
        if config.environment:
            merged_env = config.environment.merge_with_cli_args(
                python=python,
                with_packages=with_packages,
                with_requirements=with_requirements,
                project=project,
                with_editable=with_editable,
            )
            python = merged_env["python"]
            with_packages = merged_env["with_packages"]
            with_requirements = merged_env["with_requirements"]
            project = merged_env["project"]
            with_editable = merged_env["with_editable"]

        # Get server port from deployment config if not specified
        if config.deployment and config.deployment.port:
            server_port = server_port or config.deployment.port

        logger.info(f"Using configuration from {config_path}")
    file, server_object = run_module.parse_file_path(server_spec)

    logger.debug(
        "Starting dev server",
        extra={
            "file": str(file),
            "server_object": server_object,
            "with_editable": str(with_editable) if with_editable else None,
            "with_packages": with_packages,
            "ui_port": ui_port,
            "server_port": server_port,
        },
    )

    try:
        # Import server to get dependencies
        # TODO: Remove dependencies handling (deprecated in v2.11.4)
        server: FastMCP = await run_module.import_server(file, server_object)
        if server.dependencies:
            import warnings

            warnings.warn(
                f"Server '{server.name}' uses deprecated 'dependencies' parameter (deprecated in FastMCP 2.11.4). "
                "Please migrate to fastmcp.json configuration file. "
                "See https://gofastmcp.com/docs/deployment/server-configuration for details.",
                DeprecationWarning,
                stacklevel=2,
            )
            with_packages = list(set(with_packages + server.dependencies))

        env_vars = {}
        if ui_port:
            env_vars["CLIENT_PORT"] = str(ui_port)
        if server_port:
            env_vars["SERVER_PORT"] = str(server_port)

        # Get the correct npx command
        npx_cmd = _get_npx_command()
        if not npx_cmd:
            logger.error(
                "npx not found. Please ensure Node.js and npm are properly installed "
                "and added to your system PATH."
            )
            sys.exit(1)

        inspector_cmd = "@modelcontextprotocol/inspector"
        if inspector_version:
            inspector_cmd += f"@{inspector_version}"

        uv_cmd = _build_uv_command(
            server_spec,
            with_editable,
            with_packages,
            no_banner=True,
            python_version=python,
            with_requirements=with_requirements,
            project=project,
        )

        # Run the MCP Inspector command with shell=True on Windows
        shell = sys.platform == "win32"
        process = subprocess.run(
            [npx_cmd, inspector_cmd] + uv_cmd,
            check=True,
            shell=shell,
            env=dict(os.environ.items()) | env_vars,
        )
        sys.exit(process.returncode)
    except subprocess.CalledProcessError as e:
        logger.error(
            "Dev server failed",
            extra={
                "file": str(file),
                "error": str(e),
                "returncode": e.returncode,
            },
        )
        sys.exit(e.returncode)
    except FileNotFoundError:
        logger.error(
            "npx not found. Please ensure Node.js and npm are properly installed "
            "and added to your system PATH. You may need to restart your terminal "
            "after installation.",
            extra={"file": str(file)},
        )
        sys.exit(1)


@app.command
async def run(
    server_spec: str | None = None,
    *server_args: str,
    transport: Annotated[
        run_module.TransportType | None,
        cyclopts.Parameter(
            name=["--transport", "-t"],
            help="Transport protocol to use",
        ),
    ] = None,
    host: Annotated[
        str | None,
        cyclopts.Parameter(
            "--host",
            help="Host to bind to when using http transport (default: 127.0.0.1)",
        ),
    ] = None,
    port: Annotated[
        int | None,
        cyclopts.Parameter(
            name=["--port", "-p"],
            help="Port to bind to when using http transport (default: 8000)",
        ),
    ] = None,
    path: Annotated[
        str | None,
        cyclopts.Parameter(
            "--path",
            help="The route path for the server (default: /mcp/ for http transport, /sse/ for sse transport)",
        ),
    ] = None,
    log_level: Annotated[
        Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] | None,
        cyclopts.Parameter(
            name=["--log-level", "-l"],
            help="Log level",
        ),
    ] = None,
    no_banner: Annotated[
        bool,
        cyclopts.Parameter(
            "--no-banner",
            help="Don't show the server banner",
            negative=False,
        ),
    ] = False,
    python: Annotated[
        str | None,
        cyclopts.Parameter(
            "--python",
            help="Python version to use (e.g., 3.10, 3.11)",
        ),
    ] = None,
    with_packages: Annotated[
        list[str],
        cyclopts.Parameter(
            "--with",
            help="Additional packages to install (can be used multiple times)",
            negative=False,
        ),
    ] = [],
    project: Annotated[
        Path | None,
        cyclopts.Parameter(
            "--project",
            help="Run the command within the given project directory",
        ),
    ] = None,
    with_requirements: Annotated[
        Path | None,
        cyclopts.Parameter(
            "--with-requirements",
            help="Requirements file to install dependencies from",
        ),
    ] = None,
) -> None:
    """Run an MCP server or connect to a remote one.

    The server can be specified in several ways:
    1. Module approach: "server.py" - runs the module directly, looking for an object named 'mcp', 'server', or 'app'
    2. Import approach: "server.py:app" - imports and runs the specified server object
    3. URL approach: "http://server-url" - connects to a remote server and creates a proxy
    4. MCPConfig file: "mcp.json" - runs as a proxy server for the MCP Servers in the MCPConfig file
    5. FastMCP config: "fastmcp.json" - runs server using FastMCP configuration
    6. No argument: looks for fastmcp.json in current directory

    Server arguments can be passed after -- :
    fastmcp run server.py -- --config config.json --debug

    Args:
        server_spec: Python file, object specification (file:obj), config file, URL, or None to auto-detect
    """
    # Load configuration if needed
    from pathlib import Path

    from fastmcp.utilities.fastmcp_config import FastMCPConfig

    config = None
    config_path = None

    # Auto-detect fastmcp.json if no server_spec provided
    if server_spec is None:
        config_path = Path("fastmcp.json")
        if not config_path.exists():
            # Check if fastmcp.json exists in current directory
            found_config = FastMCPConfig.find_config()
            if found_config:
                config_path = found_config
            else:
                logger.error(
                    "No server specification provided and no fastmcp.json found in current directory.\n"
                    "Please specify a server file or create a fastmcp.json configuration."
                )
                sys.exit(1)

        server_spec = str(config_path)
        logger.info(f"Using configuration from {config_path}")

    # Load config if server_spec is a fastmcp.json file
    if server_spec.endswith("fastmcp.json"):
        config_path = Path(server_spec)
        if config_path.exists():
            config = FastMCPConfig.from_file(config_path)

            # Merge deployment config with CLI values (CLI takes precedence)
            if config.deployment:
                merged_deploy = config.deployment.merge_with_cli_args(
                    transport=transport,
                    host=host,
                    port=port,
                    path=path,
                    log_level=log_level,
                    server_args=list(server_args) if server_args else None,
                )
                transport = merged_deploy["transport"]
                host = merged_deploy["host"]
                port = merged_deploy["port"]
                path = merged_deploy["path"]
                log_level = merged_deploy["log_level"]
                server_args = merged_deploy["server_args"] or ()

            # Merge environment config with CLI values (CLI takes precedence)
            if config.environment:
                merged_env = config.environment.merge_with_cli_args(
                    python=python,
                    with_packages=with_packages,
                    with_requirements=with_requirements,
                    project=project,
                )
                python = merged_env["python"]
                with_packages = merged_env["with_packages"]
                with_requirements = merged_env["with_requirements"]
                project = merged_env["project"]
    logger.debug(
        "Running server or client",
        extra={
            "server_spec": server_spec,
            "transport": transport,
            "host": host,
            "port": port,
            "path": path,
            "log_level": log_level,
            "server_args": list(server_args),
        },
    )

    # Check if we need to use uv run (either from CLI args or config)
    needs_uv = python or with_packages or with_requirements or project
    if not needs_uv and config and config.environment:
        # Check if config's environment needs uv
        needs_uv = config.environment.needs_uv()

    if needs_uv:
        # Use uv run subprocess - always use run_with_uv which handles output correctly
        try:
            run_module.run_with_uv(
                server_spec=server_spec,
                python_version=python,
                with_packages=with_packages,
                with_requirements=with_requirements,
                project=project,
                transport=transport,
                host=host,
                port=port,
                path=path,
                log_level=log_level,
                show_banner=not no_banner,
            )
        except Exception as e:
            logger.error(
                f"Failed to run: {e}",
                extra={
                    "server_spec": server_spec,
                    "error": str(e),
                },
            )
            sys.exit(1)
    else:
        # Use direct import for backwards compatibility
        try:
            await run_module.run_command(
                server_spec=server_spec,
                transport=transport,
                host=host,
                port=port,
                path=path,
                log_level=log_level,
                server_args=list(server_args),
                show_banner=not no_banner,
            )
        except Exception as e:
            logger.error(
                f"Failed to run: {e}",
                extra={
                    "server_spec": server_spec,
                    "error": str(e),
                },
            )
            sys.exit(1)


@app.command
async def inspect(
    server_spec: str | None = None,
    *,
    output: Annotated[
        Path,
        cyclopts.Parameter(
            name=["--output", "-o"],
            help="Output file path for the JSON report (default: server-info.json)",
        ),
    ] = Path("server-info.json"),
    python: Annotated[
        str | None,
        cyclopts.Parameter(
            "--python",
            help="Python version to use (e.g., 3.10, 3.11)",
        ),
    ] = None,
    with_packages: Annotated[
        list[str],
        cyclopts.Parameter(
            "--with",
            help="Additional packages to install (can be used multiple times)",
            negative=False,
        ),
    ] = [],
    project: Annotated[
        Path | None,
        cyclopts.Parameter(
            "--project",
            help="Run the command within the given project directory",
        ),
    ] = None,
    with_requirements: Annotated[
        Path | None,
        cyclopts.Parameter(
            "--with-requirements",
            help="Requirements file to install dependencies from",
        ),
    ] = None,
) -> None:
    """Inspect an MCP server and generate a JSON report.

    This command analyzes an MCP server and generates a comprehensive JSON report
    containing information about the server's name, instructions, version, tools,
    prompts, resources, templates, and capabilities.

    Examples:
        fastmcp inspect server.py
        fastmcp inspect server.py -o report.json
        fastmcp inspect server.py:mcp -o analysis.json
        fastmcp inspect path/to/server.py:app -o /tmp/server-info.json
        fastmcp inspect fastmcp.json
        fastmcp inspect  # auto-detect fastmcp.json

    Args:
        server_spec: Python file to inspect, optionally with :object suffix, or fastmcp.json
    """
    # Load configuration if needed
    from pathlib import Path

    from fastmcp.utilities.fastmcp_config import FastMCPConfig

    config = None
    config_path = None

    # Auto-detect fastmcp.json if no server_spec provided
    if server_spec is None:
        config_path = Path("fastmcp.json")
        if not config_path.exists():
            # Check if fastmcp.json exists in current directory
            found_config = FastMCPConfig.find_config()
            if found_config:
                config_path = found_config
            else:
                logger.error(
                    "No server specification provided and no fastmcp.json found in current directory.\n"
                    "Please specify a server file or create a fastmcp.json configuration."
                )
                sys.exit(1)

        server_spec = str(config_path)
        logger.info(f"Using configuration from {config_path}")

    # Load config if server_spec is a fastmcp.json file
    if server_spec.endswith("fastmcp.json"):
        config_path = Path(server_spec)
        if config_path.exists():
            config = FastMCPConfig.from_file(config_path)
            # Get the actual entrypoint with resolved paths
            entrypoint = config.get_entrypoint(config_path)

            if entrypoint.object:
                server_spec = f"{entrypoint.file}:{entrypoint.object}"
            else:
                server_spec = entrypoint.file

            # Merge environment settings from config with CLI (CLI takes precedence)
            if config.environment:
                merged_env = config.environment.merge_with_cli_args(
                    python=python,
                    with_packages=with_packages,
                    with_requirements=with_requirements,
                    project=project,
                )
                python = merged_env["python"]
                with_packages = merged_env["with_packages"]
                with_requirements = merged_env["with_requirements"]
                project = merged_env["project"]

    # Check if we need to use uv run
    needs_uv = python or with_packages or with_requirements or project
    if not needs_uv and config and config.environment:
        needs_uv = config.environment.needs_uv()

    if needs_uv:
        # Build and run uv command
        if config and config.environment:
            # Use environment config's run_with_uv method
            inspect_command = [
                "fastmcp",
                "inspect",
                server_spec,
                "--output",
                str(output),
            ]
            config.environment.run_with_uv(inspect_command)
        else:
            # Build an EnvironmentConfig from CLI args for consistency
            from fastmcp.utilities.fastmcp_config import (
                EnvironmentConfig,
            )

            env_config = EnvironmentConfig(
                python=python,
                dependencies=with_packages,
                requirements=str(with_requirements) if with_requirements else None,
                project=str(project) if project else None,
            )

            inspect_command = [
                "fastmcp",
                "inspect",
                server_spec,
                "--output",
                str(output),
            ]
            env_config.run_with_uv(inspect_command)

    # Direct import path (no uv needed)
    # Parse the server specification
    file, server_object = run_module.parse_file_path(server_spec)

    logger.debug(
        "Inspecting server",
        extra={
            "file": str(file),
            "server_object": server_object,
            "output": str(output),
        },
    )

    try:
        # Import the server
        server = await run_module.import_server(file, server_object)

        # Get server information - using native async support
        info = await inspect_fastmcp(server)

        info_json = TypeAdapter(FastMCPInfo).dump_json(info, indent=2)

        # Ensure output directory exists
        output.parent.mkdir(parents=True, exist_ok=True)

        # Write JSON report (always pretty-printed)
        with output.open("w", encoding="utf-8") as f:
            f.write(info_json.decode("utf-8"))

        logger.info(f"Server inspection complete. Report saved to {output}")

        # Print summary to console
        console.print(
            f"[bold green]✓[/bold green] Inspected server: [bold]{info.name}[/bold]"
        )
        console.print(f"  Tools: {len(info.tools)}")
        console.print(f"  Prompts: {len(info.prompts)}")
        console.print(f"  Resources: {len(info.resources)}")
        console.print(f"  Templates: {len(info.templates)}")
        console.print(f"  Report saved to: [cyan]{output}[/cyan]")

    except Exception as e:
        logger.error(
            f"Failed to inspect server: {e}",
            extra={
                "server_spec": server_spec,
                "error": str(e),
            },
        )
        console.print(f"[bold red]✗[/bold red] Failed to inspect server: {e}")
        sys.exit(1)


@app.command
def generate_schema(
    *,
    output: Annotated[
        Path | None,
        cyclopts.Parameter(
            name=["--output", "-o"],
            help="Output file path for the JSON schema",
        ),
    ] = None,
) -> None:
    """Generate JSON schema for fastmcp.json configuration files.

    This generates a JSON schema that can be used by IDEs and validators
    to provide auto-completion and validation for fastmcp.json files.

    Examples:
        fastmcp generate-schema
        fastmcp generate-schema -o schema.json
    """
    import json

    from fastmcp.utilities.fastmcp_config import (
        generate_schema as gen_schema,
    )

    schema = gen_schema()
    schema_json = json.dumps(schema, indent=2)

    if output:
        output.parent.mkdir(parents=True, exist_ok=True)
        output.write_text(schema_json)
        logger.info(f"Schema written to {output}")
    else:
        console.print(schema_json)


# Add install subcommands using proper Cyclopts pattern
app.command(install_app)


if __name__ == "__main__":
    app()