o
    iq                  %   @   s  d Z ddlZddlZddlZddlZddlZddlZddlZddl	m
Z
 ddlmZ ddlmZmZ ddlZddlZddlmZ ddlmZ ddlZddlmZ dd	lmZ dd
lmZ ddlmZm Z  ddl!m"Z"m#Z#m$Z$ ddl%m&Z& ddl'm(Z( ddl)m*Z* e&dZ+e Z,ej-ddej.dZ/dd Z0de1de2e1e1f fddZ3e
de4e1 dB fddZ5e/j6dddee7ej8d d!d"d#f fd$d%Z9e/j6	dxddddddddd&d'e1dB d(ee4e dB ej8d)d*d"d#f d+ee4e1 dB ej8d,d-d"d#f d.ee1dB ej8d/d0d1f d2ee:dB ej8d3d4d1f d5ee:dB ej8d6d7d1f d8ee1dB ej8d9d:d1f d;eedB ej8d<d=d1f d>eedB ej8d?d@d1f ddfdAdBZ;e/j6	dxdddddddddddddCd'e1dB dDe1dEeej<dB ej8dFdGgdHdIf dJee1dB ej8dKdLd1f dMee:dB ej8dNdOgdPdIf dQee1dB ej8dRdSd1f dTeedU dB ej8dVdWgdXdIf dYee7ej8dZd[d"d#f d8ee1dB ej8d9d:d1f d+ee4e1 dB ej8d,d-d"d#f d>eedB ej8d?d@d1f d;eedB ej8d<d=d1f d\ee7ej8d]d^d"d#f d_ee7ej8d`dad"d#f ddfdbdcZe/j6	dxdddddddddd'e1dB deee"dB ej8dfdggdhdIf dieedB ej8djdkgdldIf d8ee1dB ej8d9d:d1f d+ee4e1 dB ej8d,d-d"d#f d>eedB ej8d?d@d1f d;eedB ej8d<d=d1f d_ee7ej8d`dad"d#f ddfdmdnZ=ej-d>dodIZ>e>j6			dydpee1dB ej8dqd1f dree1dB ej8dsd1f d\ee7ej8dtd1f ddfdudvZ?e/6e> e/6e e@dwkre/  dS dS )zz!FastMCP CLI tools using Cyclopts.    N)contextmanagerPath)	AnnotatedLiteral)Console)Table)run)install_app)FastMCP)is_already_in_uv_subprocessload_and_merge_config)InspectFormatformat_infoinspect_fastmcp)
get_logger)MCPServerConfig)UVEnvironmentclifastmcpzFFastMCP 2.0 - The fast, Pythonic way to build MCP servers and clients.)namehelpversionc               	   C   sN   t jdkr%dD ]} ztj| dgddd | W   S  tjy"   Y qw dS dS )z5Get the correct npx command for the current platform.win32)znpx.cmdznpx.exenpxz	--versionT)checkcapture_outputNr   )sysplatform
subprocessr	   CalledProcessError)cmd r"   U/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/fastmcp/cli/cli.py_get_npx_command+   s   

r$   env_varreturnc                 C   s<   d| vrt d td | dd\}}| | fS )z6Parse environment variable string in format KEY=VALUE.=z6Invalid environment variable format. Must be KEY=VALUE   )loggererrorr   exitsplitstrip)r%   keyvaluer"   r"   r#   _parse_env_var9   s
   

r0   argsc                 c   sP    | dur#t jdd }zt jd g| t _dV  W |t _dS |t _w dV  dS )a:  Temporarily replace sys.argv if args provided.

    This context manager is used at the CLI boundary to inject
    server arguments when needed, without mutating sys.argv deep
    in the source loading logic.

    Args are provided without the script name, so we preserve sys.argv[0]
    and replace the rest.
    Nr   )r   argv)r1   originalr"   r"   r#   	with_argvB   s   
r4   F)copyr5   z--copyz%Copy version information to clipboard )r   negativec                 C   s   t jtjdt t tt j	 j
d d}tjdd}|jddd |jd	d
d | D ]\}}||d t|dd q1| rttdddd}| }|| W d   n1 saw   Y  t|  td dS t| dS )z1Display version information and platform details.mcpr(   )zFastMCP versionzMCP versionzPython versionPlatformzFastMCP root path)r   r(   )paddingboldleft)stylejustifycyanright:
 NF)fileforce_terminallegacy_windowsu:   [green]✓[/green] Version information copied to clipboard)r   __version__	importlibmetadatar   r   python_versionr   __file__resolveparentsr   grid
add_columnitemsadd_rowstrreplacer   captureprint	pyperclipr5   getconsole)r5   infogkvplain_consolerT   r"   r"   r#   r   Y   s&   

r   )with_editablewith_packagesinspector_versionui_portserver_portpythonwith_requirementsprojectserver_specr^   z--with-editablez\Directory containing pyproject.toml to install in editable mode (can be used multiple times)r_   z--withz;Additional packages to install (can be used multiple times)r`   z--inspector-versionz#Version of the MCP Inspector to use)r   ra   z	--ui-portzPort for the MCP Inspector UIrb   z--server-portz'Port for the MCP Inspector Proxy serverrc   z--pythonz(Python version to use (e.g., 3.10, 3.11)rd   z--with-requirementsz.Requirements file to install dependencies fromre   z	--projectz2Run the command within the given project directoryc             
      sT  z t | ||pg |||rdd |D nd|d\}	} |s |	jj}W n ty/   td Y nw tjd| |	jj	|	jj
||dd z|	sNtd	 td |	dusTJ |	j I dH }
|
j
rd
dl}|jd|
j dtdd |	jj
pug }tt||
j
 }|	jst|d|	_n||	j_
i }|rt||d< |rt||d< t }|std td d}|r|d| 7 }|	jdd| dg}ttj |B ddiB }tj||g|d|d}t|j W dS  tjy } ztjdt| t||jdd t|j W Y d}~dS d}~w ty)   tjddt| id td Y dS w ) zRun 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
    c                 S   s   g | ]}t |qS r"   )rR   ).0pr"   r"   r#   
<listcomp>   s    zdev.<locals>.<listcomp>N)rc   r_   rd   re   editableportr(   zStarting dev server)rf   r^   r_   ra   rb   extraNo configuration availabler   zServer 'z' 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.   )
stacklevel)dependenciesCLIENT_PORTSERVER_PORTzbnpx not found. Please ensure Node.js and npm are properly installed and added to your system PATH.z@modelcontextprotocol/inspector@r   r	   --no-bannerFASTMCP_UV_SPAWNED1Tr   envzDev server failed)rD   r*   
returncodeznpx 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.rD   ) r   
deploymentrk   FileNotFoundErrorr   r+   r)   debugenvironmentrj   rq   r*   sourceload_serverwarningswarnr   DeprecationWarninglistsetr   rR   r$   build_commanddictosenvironrP   r   r	   rz   r    )rf   r^   r_   r`   ra   rb   rc   rd   re   configserverr   env_depsall_depsenv_varsnpx_cmdinspector_cmduv_cmdry   processer"   r"   r#   dev   s   E






r   )	transporthostrk   path	log_level	no_bannerrc   r_   re   rd   skip_sourceskip_envserver_argsr   --transportz-tzTransport protocol to use)r   r   r   --hostz>Host to bind to when using http transport (default: 127.0.0.1)rk   --portz-pz9Port to bind to when using http transport (default: 8000)r   --pathzZThe route path for the server (default: /mcp/ for http transport, /sse/ for sse transport)r   )DEBUGINFOWARNINGERRORCRITICAL--log-levelz-lz	Log levelr   ru   zDon't show the server bannerr   z--skip-sourcezBSkip source preparation step (use when source is already prepared)r   
--skip-envzRSkip environment configuration (for internal use when already in a uv environment)c                   s  |st  rd}zt| ||pg |
|	||||||rt|ndd\}} W n ty1   td Y nw |p7|jj}|p=|jj}|pC|jj	}|pI|jj
}|pO|jj}|pU|jj}|rZ|ntjj }tjd| ||||||rnt|ng dd dg}|j||ko| }|r+d	d
| g}|r|d|g |dkr|r|d|g |r|dt|g |r|d|g |r|d|g |r|d |d |r|d || |j|}tjddiB }tdd|  ztj|d|d}t|j W dS  tjy* } ztjd| | t||jdd t|j W Y d}~dS d}~ww ztj | ||||||r;t|ng | |d	I dH  W dS  t!yo } ztjd| | t|dd td W Y d}~dS d}~ww )aa  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
    TN)
rc   r_   rd   re   r   r   rk   r   r   r   r(   zRunning server or client)rf   r   r   rk   r   r   r   rl   testr   r	   r   stdior   r   r   r   ru   r   z--rv   rw   zRunning command: rC   rx   zFailed to run: )rf   r*   rz   )	rf   r   r   rk   r   r   r   show_bannerr   rf   r*   )"r   r   r   r|   r   r+   r{   r   r   rk   r   r   r1   r   settingsshow_cli_bannerr)   r}   r~   r   extendrR   appendr   r   joinr   r	   rz   r    	exception
run_modulerun_command	Exception)rf   r   r   rk   r   r   r   rc   r_   re   rd   r   r   r   r   final_transport
final_host
final_port
final_pathfinal_log_levelfinal_server_argsfinal_no_bannertest_cmdneeds_uv	inner_cmdr!   ry   r   r   r"   r"   r#   r	   1  s   
o




r	   )formatoutputrc   r_   re   rd   r   r   --formatz-fzXOutput format: fastmcp (FastMCP-specific) or mcp (MCP protocol). Required when using -o.r   --outputz-ozbOutput file path for the JSON report. If not specified, outputs to stdout when format is provided.c             
      sv  |st  rd}zPt| ||pg ||d\}} | drW|du rWz+tt| }	t|	}
W d   n1 s6w   Y  d|
v rItd t	
d W n tjtfyV   Y nw W n tyf   t	
d Y nw dg}|j||kot| }|rd	d
| dg}|r|d|jg |r|dt|g ddl}|j|}tjddiB }|j|d|d}t	
|j tjd| ||rt|nddd zG|std t	
d |dusJ |j I dH }t|I dH }|r|std td t	
d |du rt  td td|j  |jrtd|j  |jr)td|j  |j r8tdt!|j   td|j"  |j#rNtd|j#  t  td td t!|j$  td!t!|j%  td"t!|j&  td#t!|j'  t  td$ td%|j(  td&|j)  t  td' W dS t*|||I dH }|r |j+j,ddd( |d)}	|	-| W d   n	1 sw   Y  t.d*|  td+| d, td-|j d. td/|j  W dS t|/d0 W dS  t0y: } z#tj1d1| | t|d2d td3|  t	
d W Y d}~dS d}~ww )4a  Inspect an MCP server and display information or generate a JSON report.

    This command analyzes an MCP server. Without flags, it displays a text summary.
    Use --format to output complete JSON data.

    Examples:
        # Show text summary
        fastmcp inspect server.py

        # Output FastMCP format JSON to stdout
        fastmcp inspect server.py --format fastmcp

        # Save MCP protocol format to file (format required with -o)
        fastmcp inspect server.py --format mcp -o manifest.json

        # Inspect from fastmcp.json configuration
        fastmcp inspect fastmcp.json
        fastmcp inspect  # auto-detect fastmcp.json

    Args:
        server_spec: Python file to inspect, optionally with :object suffix, or fastmcp.json
    T)rc   r_   rd   re   z.jsonN
mcpServersz4MCPConfig files are not supported by inspect commandr(   r   r   inspectr   r   r   r   rv   rw   rx   zInspecting server)rf   r   r   rl   rn   zG[bold red]Error:[/bold red] --format is required when using -o/--outputzL[dim]Use --format fastmcp or --format mcp to specify the output format[/dim]z[bold]Server[/bold]z  Name:         z  Version:      z  Website:      z  Icons:        z  Generation:   z  Instructions: z[bold]Components[/bold]z  Tools:        z  Prompts:      z  Resources:    z  Templates:    z[bold]Environment[/bold]z  FastMCP:      z  MCP:          z?[dim]Use --format \[fastmcp|mcp] for complete JSON output[/dim])rM   exist_okwbz,Server inspection complete. Report saved to u?   [bold green]✓[/bold green] Server inspection saved to: [cyan][/cyan]z  Server: [bold]z[/bold]z
  Format: zutf-8zFailed to inspect server: r   u3   [bold red]✗[/bold red] Failed to inspect server: )2r   r   endswithopenr   jsonloadr)   r*   r   r+   JSONDecodeErrorr|   r~   r   r   r/   rR   r   r   r   r	   rz   r}   r   r   r   rX   rU   r   r   website_urliconslenserver_generationinstructionstoolsprompts	resources	templatesfastmcp_versionmcp_versionr   parentmkdirwriterY   decoder   r   )rf   r   r   rc   r_   re   rd   r   r   fdatar   r   inspect_commandr   r!   ry   r   r   rY   formatted_jsonr   r"   r"   r#   r     s   
P
	

	







r   zManage FastMCP projectsconfig_pathz'Path to fastmcp.json configuration file
output_dirz1Directory to create the persistent environment inz)Skip source preparation (e.g., git clone)c           	   
      s2  ddl m} |du rtd td | du r6t }|r,t|} t	d|   n
td td || }|
 sKtd|   td ||}z!t|}|j||d	I dH  td
| d|  d| d W dS  ty } ztd|  td|  td W Y d}~dS d}~ww )a  Prepare a FastMCP project by creating a persistent uv environment.

    This command creates a persistent uv project with all dependencies installed:
    - Creates a pyproject.toml with dependencies from the config
    - Installs all Python packages into a .venv
    - Prepares the source (git clone, download, etc.) unless --skip-source

    After running this command, you can use:
    fastmcp run <config> --project <output-dir>

    This is useful for:
    - CI/CD pipelines with separate build and run stages
    - Docker images where you prepare during build
    - Production deployments where you want fast startup times

    Example:
        fastmcp project prepare myserver.json --output-dir ./prepared-env
        fastmcp run myserver.json --project ./prepared-env
    r   r   NzbThe --output-dir parameter is required.
Please specify where to create the persistent environment.r(   zUsing configuration from zxNo configuration file specified and no fastmcp.json found.
Please specify a configuration file or create a fastmcp.json.zConfiguration file not found: )r   r   u>   [bold green]✓[/bold green] Project prepared successfully in z7!
You can now run the server with:
  [cyan]fastmcp run z --project r   zFailed to prepare project: u4   [bold red]✗[/bold red] Failed to prepare project: )pathlibr   r)   r*   r   r+   r   find_configrR   rY   exists	from_filepreparerX   rU   r   )	r   r   r   r   found_configconfig_fileoutput_pathr   r   r"   r"   r#   r     sP   "




r   __main__)N)NNF)A__doc__importlib.metadatarH   importlib.utilr   r   r   r   r   
contextlibr   r   r   typingr   r   cycloptsrV   rich.consoler   
rich.tabler   r   fastmcp.clir	   r   fastmcp.cli.installr
   fastmcp.server.serverr   fastmcp.utilities.clir   r   fastmcp.utilities.inspectr   r   r   fastmcp.utilities.loggingr   #fastmcp.utilities.mcp_server_configr   6fastmcp.utilities.mcp_server_config.v1.environments.uvr   r)   rX   ApprG   appr$   rR   tupler0   r   r4   commandbool	Parameterr   intr   TransportTyper   project_appr   __name__r"   r"   r"   r#   <module>   s   	
%


!(/6= 2	

&.5
=DKS[ j	

 '.6 r

	

V


