
    kKj=                        U 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Zddl	m
Z
 ddlmZ ddlmZmZ ddlmZ ddlmZmZ ddlZddlmZmZ dd	lmZ dd
lmZ ddlmZ  ed      Zed   Z ed   Z!h dZ"e#e$   e%d<   de$de&fdZ'de$defdZ(deded   fdZ)dedefdZ*	 	 	 	 	 	 	 	 	 	 d4de$de dz  de$dz  de+dz  de$dz  de!dz  de,e$   dz  d e&d!e&d"e&d#e&ddfd$Z-ddd%d&e$d'e
e,e$   ge,e$   f   dz  d(e,e$   dz  ddfd)Z.	 	 	 d5d*ede$dz  de+dz  de dz  ddf
d+Z/d,ede$de&fd-Z0d.ej                  jb                  ddfd/Z2	 	 d6d0e,e$   d1e,e   dz  d2e&ddfd3Z3y)7z<FastMCP run command implementation with enhanced type hints.    N)Callable)Path)AnyLiteral)FastMCP)Changeawatch)r   create_proxy)
get_logger)MCPServerConfig)FileSystemSourcezcli.run)stdiohttpssestreamable-http)DEBUGINFOWARNINGERRORCRITICAL>%   .js.md.py.ts.css.eot.gif.gql.ico.jpg.jsx.mdx.mp3.mp4.png.svg.tsx.ttf.txt.vue.wav.xml.yml.html.jpeg.less.sass.scss.toml.webm.webp.woff.yaml.woff2.svelte.graphql.jsonWATCHED_EXTENSIONSpathreturnc                 `    t        j                  d      }t        |j                  |             S )zCheck if a string is a URL.z
^https?://)recompileboolmatch)r=   url_patterns     `/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/fastmcp/cli/run.pyis_urlrF   T   s&    **]+K!!$'((    urlc                     	 ddl } |j                  |       }t        |      }|S # t        $ r:}t        j                  d|  d|        t        j                  d       Y d}~yd}~ww xY w)zCreate a FastMCP server from a client URL.

    Args:
        url: The URL to connect to

    Returns:
        A FastMCP server instance
    r   Nz Failed to create client for URL z:    )fastmcpClientr
   	Exceptionloggererrorsysexit)rH   rK   clientserveres        rE   create_client_serverrU   Z   s`    $f% 7uBqcBCs   "% 	A(0A##A(mcp_config_pathc                     | j                         5 }t        j                  |      }ddd       t              }|S # 1 sw Y   xY w)z)Create a FastMCP server from a MCPConfig.N)openjsonloadr
   )rV   src
mcp_configrS   s       rE   create_mcp_config_serverr]   n   s<    				3YYs^
 
  *%FM	 
 	s	   <Aconfig_pathc                 f    t        j                  |       }|j                  j                  |        |S )zLoad a FastMCP configuration from a fastmcp.json file.

    Args:
        config_path: Path to fastmcp.json file

    Returns:
        MCPServerConfig object
    )r   	from_file
deploymentapply_runtime_settings)r^   configs     rE   load_mcp_server_configrd   w   s/     &&{3F ,,[9MrG   server_spec	transporthostport	log_levelserver_argsshow_banneruse_direct_importskip_source	statelessc                   K   t        |       r%t        |       }t        j                  d|         n7| j	                  d      rxt        |       }t        |      5 }t        j                  |      }ddd       dv rt        |      }nt        |      }||n|j                  j                  }||n|j                  j                  }||n|j                  j                  }||n|j                  j                  }||n|j                  j                   }||n|j                  j"                  }|	s|j%                          d{   nd ddlm} ddlm} |r ||      n |       }|5  |j.                  j1                          d{   }ddd       t        j                  dj2                   d	|        nt5        | 
      }t7        |      }|	s|j%                          d{   nd ddlm} ddlm} |r ||      n |       }|5  |j.                  j1                          d{   }ddd       t        j                  dj2                   d|j                          t9        |t:              rt=        ||||       d{    yi }|||d<   ||nt>        j@                  j                  }|dk7  r|||d<   |||d<   |||d<   |||d<   |
rd|d<   |sd|d<   	  |jB                  di | d{    y# 1 sw Y   xY w7 7 # 1 sw Y   xY w7 :7 # 1 sw Y   xY w7 7 8# tD        $ r7}t        jG                  d|        tI        jJ                  d       Y d}~yd}~ww xY ww)a  Run a MCP server or connect to a remote one.

    Args:
        server_spec: Python file, object specification (file:obj), config file, or URL
        transport: Transport protocol to use
        host: Host to bind to when using http transport
        port: Port to bind to when using http transport
        path: Path to bind to when using http transport
        log_level: Log level
        server_args: Additional arguments to pass to the server
        show_banner: Whether to show the server banner
        use_direct_import: Whether to use direct import instead of subprocess
        skip_source: Whether to skip source preparation step
        stateless: Whether to run in stateless mode (no session)
    z Created client proxy server for r;   N
mcpServersr   )nullcontext)	with_argvzFound server "z" from config )r=   )sourcez" in )rg   rh   rf   rf   r   rg   rh   r=   ri   Trn   Frk   zFailed to run server: rJ    )&rF   rU   rN   debugendswithr   rX   rY   rZ   r]   rd   ra   rf   rg   rh   r=   ri   argsprepare_source
contextlibrq   fastmcp.cli.clirr   rs   load_servernamer   r   
isinstance	FastMCP1xrun_v1_server_asyncrK   settings	run_asyncrM   rO   rP   rQ   )re   rf   rg   rh   r=   ri   rj   rk   rl   rm   rn   rS   r^   fdatarc   rq   rr   argv_contextrs   kwargseffective_transportrT   s                          rE   run_commandr      s\    : k%k27}EF			g	&;'+!99Q<D  4-k:F ,K8F '2	8I8I8S8S   +41B1B1G1GD+41B1B1G1GD+41B1B1G1GD&2	8I8I8S8S   +6F<M<M<R<R 
 2=&'')))$ /1 6A9[1kmL%}}88::  LL>&++n[MRS "{3 / .9f##%%%d 	+- 2=y-+-!==4466F  	~fkk]%}EF
 &)$!&t$)TTTF'{
 *	0@0@0J0J  g%!F6N!F6N!F6N'{"{ %}f(((({ 4 * ;  	& 7 \ 	U8 	) -aS12s   AM<L1CM<L%M<,L
LLAM<*L$+%M<L).L'/L)3AM<L5AM<)L9 >L7?L9 M<L		M<LL!	M<'L))L2.M<7L9 9	M9-M4/M<4M99M<)env_command_builder
extra_argsmodule_namer   r   c                   |dnt         j                  }|d| g}|r|j                  |       | ||      }t        j	                  ddj                  |              	 t        j                  |d      }t        j                  |j                         y# t        j                  $ rN}t        j                  d|  d	|j                          t        j                  |j                         Y d}~yd}~ww xY w)
a  Run a Python module directly using ``python -m <module>``.

    When ``-m`` is used, the module manages its own server startup.
    No server-object discovery or transport overrides are applied.

    Args:
        module_name: Dotted module name (e.g. ``my_package``).
        env_command_builder: An optional callable that wraps a command list
            with environment setup (e.g. ``UVEnvironment.build_command``).
        extra_args: Extra arguments forwarded after the module name.
    Npythonz-mzRunning module:  T)checkzModule z exited with code )rP   
executableextendrN   ru   join
subprocessrunrQ   
returncodeCalledProcessErrorrO   )r   r   r   r   cmdprocessrT   s          rE   run_module_commandr     s    ( -8XcnnFdK0C

: &!#&
LL#CHHSM?34..D1##$(( w{m+=all^LMs   6B C7)AC22C7rS   c                 8  K   ||| j                   _        ||| j                   _        |xdk(  r | j                          d{    yxxdk(  rnxdk(  rnxn n  | j	                          d{    ydk(  r| j                          d{    yy7 P7 %7 
w)zRun a FastMCP 1.x server using async methods.

    Args:
        server: FastMCP 1.x server instance
        host: Host to bind to
        port: Port to bind to
        transport: Transport protocol to use
    Nr   r   r   r   )r   rg   rh   run_stdio_asyncrun_streamable_http_asyncrun_sse_async)rS   rg   rh   rf   s       rE   r   r   7  s      ##
((***.V'$.22444&&(((  +4(s6   ABB,B0B1BBBBB_changec                 4    t        fdt        D              S )z,Filter for files that should trigger reload.c              3   @   K   | ]  }j                  |        y w)N)rv   ).0extr=   s     rE   	<genexpr>z _watch_filter.<locals>.<genexpr>U  s     @-?ct}}S!-?s   )anyr<   )r   r=   s    `rE   _watch_filterr   S  s    @-?@@@rG   r   c                   K   | j                   y| j                  }t        j                  dk7  rt	        j
                  t        t              5  t        j                  t        j                  |      t        j                         ddd       	 t        j                  | j                         d       d{    y| j%                          | j                          d{    y# 1 sw Y   axY w7 :# t        j                   $ r Y nw xY wt	        j
                  t        t              5  t        j                  t        j                  |      t        j"                         ddd       # 1 sw Y   xY w7 w)zTerminate a subprocess and all its children.

    Sends SIGTERM to the process group first for graceful shutdown,
    then falls back to SIGKILL if the process doesn't exit in time.
    Nwin32g      @)timeout)r   pidrP   platformry   suppressProcessLookupErrorOSErroroskillpggetpgidsignalSIGTERMasynciowait_forwaitTimeoutErrorSIGKILLkill)r   r   s     rE   _terminate_processr   X  s      %
++C
||w  !3W=IIbjjov~~6 >	""7<<>3??? 	
,,.! >=
 @## 		   !3W=IIbjjov~~6 >==
 sx   AE98C%E9(C3 6C17C3 ;$E9E7 E9%C.*E91C3 3D	E9D		!E9*8E+"	E9+E40E9r   reload_dirsis_stdioc                 	  K   |xs t        j                         g}d}|rt        j                  d       nt        j                  d       t	        j
                         t	        j                         }dfd}t        j                  dk7  r@|j                  t        j                  |       |j                  t        j                  |       	 j                         st	        j                  | dddt        j                  dk7  d d{   }t	        j                  t!        t#        t%        |dt&        i                  }t	        j                  |j)                               }t	        j                  j)                               }	t	        j(                  |||	gt        j*                         d{   \  }
}|D ]H  }|j-                          t/        j0                  t        j2                        5  | d{    ddd       J |	|
v rn||
v r5|j5                         }|d	k7  rt        j7                  d
| d       nt        j                  d       t	        j                  t!        t#        t%        |dt&        i                  }t	        j                  j)                               }	t	        j(                  ||	gt        j*                         d{   \  }
}|D ]H  }|j-                          t/        j0                  t        j2                        5  | d{    ddd       J |	|
v rnmt        j                  d       nE|j5                         }t        j                  dt9        |       d       t;        |       d{    j                         st        j                  dk7  r>|j?                  t        j                         |j?                  t        j                         |r!|j@                  t;        |       d{    yyy7 7 d7 !# 1 sw Y   jxY w7 R7 # 1 sw Y   XxY w7 # t<        $ r t        j                  d       Y w xY w7 V# t        j                  dk7  r>|j?                  t        j                         |j?                  t        j                         |r"|j@                  t;        |       d{  7   w w w xY ww)zRun a command with file watching and auto-reload.

    Args:
        cmd: Command to run as subprocess (should include --no-reload)
        reload_dirs: Directories to watch for changes (default: cwd)
        is_stdio: Whether this is stdio transport
    Nz.Reload mode enabled (using stateless sessions)zReload mode enabled (using stateless HTTP). Some features requiring bidirectional communication (like elicitation) are not available.c                  P    t         j                  d        j                          y )N%Received shutdown signal, stopping...)rN   infoset)shutdown_events   rE   signal_handlerz'run_with_reload.<locals>.signal_handler  s    ;<rG   r   )stdinstdoutstderrstart_new_sessionwatch_filter)return_whenr   zServer exited with code z, waiting for file change...z)Server exited, waiting for file change...zDetected changes, restarting...zDetected changes in z file(s), restarting...r   )r>   N)!r   cwdrN   r   r   Eventget_running_looprP   r   add_signal_handlerr   r   SIGINTis_setcreate_subprocess_execcreate_taskanextaiterr	   r   r   FIRST_COMPLETEDcancelry   r   CancelledErrorresultrO   lenr   KeyboardInterruptremove_signal_handlerr   )r   r   r   watch_pathsr   loopr   
watch_task	wait_taskshutdown_taskdonependingtaskcodechangesr   s                  @rE   run_with_reloadr   x  s     -$((*K15GDE4	
 ]]_N##%D
 ||w?~>L. '')#::"%,,'"9 G !,,eFKLmLMNJ  ++GLLN;I#//0C0C0EFM"),,Y6#33# MD'
  (()?)?@JJ A@  
 $D  '')19LL24&8TU KK KL %00% P- PQR
 !( 3 3N4G4G4I J&-ll/ ' 7 7' !g $DKKM#,,W-C-CD"

 ED $ !D(=> %++-*3w<.8OP )111 !'')N <<7"&&v~~6&&v}}5w))1$W--- 27S   A@,! # ED 2 =;<= .	 <<7"&&v~~6&&v}}5w))1$W--- 27s   C
S!=Q PB)Q 5P6?Q 5P;P<P CQ P,?Q P2 P/!P2%A%Q 
P?Q !A-S!Q%S!Q Q PP)	$	Q /P22P<	7	Q Q"Q' !Q""Q' %S!'A.SSSS!)
NNNNNNTFFF)NNN)NF)4__doc__r   ry   rY   r   r@   r   r   rP   collections.abcr   pathlibr   typingr   r   mcp.server.fastmcpr   r~   
watchfilesr   r	   rK   fastmcp.server.serverr
   fastmcp.utilities.loggingr   #fastmcp.utilities.mcp_server_configr   9fastmcp.utilities.mcp_server_config.v1.sources.filesystemr   rN   TransportTypeLogLevelTyper<   r   str__annotations__rB   rF   rU   r]   rd   intlistr   r   r   r   Processr   r   rt   rG   rE   <module>r      s   B    	 	   
 $   3 %  7 0 W	I	 ABFG0  CH 0f) ) )c c (d wt}   & '+%)$(#EEt#E *E *	E
 *E d"E cT!E E E E E 
EV DH#'	$$ "49+tCy"89D@$ S	D 	$
 
$R &*	))
*) *) t#	)
 
)8A6 A A A
g&8&8&@&@ T D &*q.	cq.dd"q. q. 
	q.rG   