
    ^sjE                        U d Z ddlZddlZddlZddlmZmZ ddlmZm	Z	 ddl
mZmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ  ej:                  e      Z ej@                  d      Z!ej@                  ee      e"d<    G d d      Z# G d d      Z$dejJ                  dejL                  fdZ'y)a  
MCP Server Module

This module provides a framework for creating an MCP (Model Context Protocol) server.
It allows you to easily define and handle various types of requests and notifications
in an asynchronous manner.

Usage:
1. Create a Server instance:
   server = Server("your_server_name")

2. Define request handlers using decorators:
   @server.list_prompts()
   async def handle_list_prompts() -> list[types.Prompt]:
       # Implementation

   @server.get_prompt()
   async def handle_get_prompt(
       name: str, arguments: dict[str, str] | None
   ) -> types.GetPromptResult:
       # Implementation

   @server.list_tools()
   async def handle_list_tools() -> list[types.Tool]:
       # Implementation

   @server.call_tool()
   async def handle_call_tool(
       name: str, arguments: dict | None
   ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
       # Implementation

3. Define notification handlers if needed:
   @server.progress_notification()
   async def handle_progress(
       progress_token: str | int, progress: float, total: float | None
   ) -> None:
       # Implementation

4. Run the server:
   async def main():
       async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
           await server.run(
               read_stream,
               write_stream,
               InitializationOptions(
                   server_name="your_server_name",
                   server_version="your_version",
                   capabilities=server.get_capabilities(
                       notification_options=NotificationOptions(),
                       experimental_capabilities={},
                   ),
               ),
           )

   asyncio.run(main())

The Server class provides methods to register handlers for various MCP requests and
notifications. It automatically manages the request context and handles incoming
messages from the client.
    N)	AwaitableCallable)AnySequence)MemoryObjectReceiveStreamMemoryObjectSendStream)AnyUrl)InitializationOptions)ServerSession)stdio_server)RequestContext)McpError)RequestResponderrequest_ctxc                   (    e Zd Z	 	 	 ddededefdZy)NotificationOptionsprompts_changedresources_changedtools_changedc                 .    || _         || _        || _        y N)r   r   r   )selfr   r   r   s       F/root/.hermes/venv/lib/python3.12/site-packages/mcp/server/__init__.py__init__zNotificationOptions.__init__X   s      /!2*    N)FFF)__name__
__module____qualname__boolr    r   r   r   r   W   s.     !&"'#	++  + 	+r   r   c            	       B   e Zd ZdefdZ	 	 ddedz  deeeeef   f   dz  defdZ	dedeeeeef   f   de
j                  fdZedee   fd	       Zd
 Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z	 ddee
j:                  ez     dee
j:                     dede fdZ!y)Servernamec                     || _         t        j                  t        i| _        i | _        t               | _        t        j                  d| d       y )NzInitializing server '')
r#   typesPingRequest_ping_handlerrequest_handlersnotification_handlersr   notification_optionsloggerdebug)r   r#   s     r   r   zServer.__init__d   sP    	 }
 	
 RT"$7$9!,TF!45r   Nr+   experimental_capabilitiesreturnc           	          dt         dt         fd}t        | j                   |d      | j                  |xs
 t	               |xs i             S )z8Create initialization options from this server instance.packager/   c                 J    	 ddl m}  ||       }||S 	 y# t        $ r Y yw xY w)Nr   )versionunknown)importlib.metadatar3   	Exception)r1   r3   vs      r   pkg_versionz9Server.create_initialization_options.<locals>.pkg_versionv   s?    6G$=H !
   s    	""mcp)server_nameserver_versioncapabilities)strr
   r#   get_capabilitiesr   )r   r+   r.   r8   s       r   create_initialization_optionsz$Server.create_initialization_optionso   sU    
	 
	 
	 %		&u-..$=(;(=)/R
 	
r   c                    d}d}d}d}t         j                  | j                  v r t        j                  |j                        }t         j
                  | j                  v r!t        j                  d|j                        }t         j                  | j                  v r t        j                  |j                        }t         j                  | j                  v rt        j                         }t        j                  |||||      S )z9Convert existing handlers to a ServerCapabilities object.N)listChangedF)	subscriberA   )prompts	resourcestoolsloggingexperimental)r&   ListPromptsRequestr)   PromptsCapabilityr   ListResourcesRequestResourcesCapabilityr   ListToolsRequestToolsCapabilityr   SetLevelRequestLoggingCapabilityServerCapabilities)r   r+   r.   prompts_capabilityresources_capabilitytools_capabilitylogging_capabilitys          r   r>   zServer.get_capabilities   s     "#! ##t'<'<<!&!8!80@@"
 %%)>)>>#(#<#<-A-S-S$ 
 !!T%:%::$440>> 
   D$9$99!&!8!8!:''&*"&2
 	
r   c                 *    t         j                         S )zFIf called outside of a request context, this will raise a LookupError.)r   get)r   s    r   request_contextzServer.request_context   s       r   c                 b     dt         g t        t        t        j                        f   f fd}|S )Nfuncc                      t         j                  d       dt        f fd}|j                  t        j
                  <    S )Nz)Registering handler for PromptListRequest_c                    K            d {   }t        j                  t        j                  |            S 7 -w)N)rC   )r&   ServerResultListPromptsResult)r[   rC   rY   s     r   handlerz7Server.list_prompts.<locals>.decorator.<locals>.handler   s1      $,))%*A*A'*RSS '   ><.>)r,   r-   r   r)   r&   rH   rY   r_   r   s   ` r   	decoratorz&Server.list_prompts.<locals>.decorator   s<    LLDET T ?FD!!%":":;Kr   )r   r   listr&   Promptr   rb   s   ` r   list_promptszServer.list_prompts   s/    	HR43E)F%FG 	 r   c                      dt         t        t        t        t        f   d z  gt        t        j
                     f   f fd}|S )NrY   c                      t         j                  d       dt        j                  f fd}|j                  t        j                  <    S )Nz(Registering handler for GetPromptRequestreqc                    K    | j                   j                  | j                   j                         d {   }t        j                  |      S 7 wr   )paramsr#   	argumentsr&   r]   )ri   
prompt_getrY   s     r   r_   z5Server.get_prompt.<locals>.decorator.<locals>.handler   s?     #'

9M9M#NN
))*55 Os   5AAA)r,   r-   r&   GetPromptRequestr)   ra   s   ` r   rb   z$Server.get_prompt.<locals>.decorator   sB    
 LLCD65#9#9 6 =DD!!%"8"89Kr   )r   r=   dictr   r&   GetPromptResultre   s   ` r   
get_promptzServer.get_prompt   sB    	d38nt+,i8M8M.NN	 r   c                 b     dt         g t        t        t        j                        f   f fd}|S )NrY   c                      t         j                  d       dt        f fd}|j                  t        j
                  <    S )Nz,Registering handler for ListResourcesRequestr[   c                    K            d {   }t        j                  t        j                  |            S 7 -w)N)rD   )r&   r]   ListResourcesResult)r[   rD   rY   s     r   r_   z9Server.list_resources.<locals>.decorator.<locals>.handler   s6     "&&L	))--	B  )r`   )r,   r-   r   r)   r&   rJ   ra   s   ` r   rb   z(Server.list_resources.<locals>.decorator   s;    LLGH  AHD!!%"<"<=Kr   )r   r   rc   r&   Resourcere   s   ` r   list_resourceszServer.list_resources   s/    
	HR43G)H%HI 
	 r   c                 X     dt         t        gt        t        t        z     f   f fd}|S )NrY   c                      t         j                  d       dt        j                  f fd}|j                  t        j                  <    S )Nz+Registering handler for ReadResourceRequestri   c                   K    | j                   j                         d {   }|xt        dx1\  } t        j                  | j                   j                  |d      }n\ t
        dxQ\  }dd l}t        j                  | j                   j                  |j                  |      j                         d      }n t        j                  t        j                  g            S 7 ƭw)Nr    z
text/plain)uritextmimeTyper   zapplication/octet-stream)r{   blobr}   )contents)rk   r{   r=   r&   TextResourceContentsbytesbase64BlobResourceContentsurlsafe_b64encodedecoder]   ReadResourceResult)ri   resultscontentbr   rY   s         r   r_   z8Server.read_resource.<locals>.decorator.<locals>.handler   s     #CJJNN33"'"<"< #

!"%1#   %"'"<"< #

!'!9!9!!<!C!C!E%?# " )),,") # 4s    C,C*CC,)r,   r-   r&   ReadResourceRequestr)   ra   s   ` r   rb   z'Server.read_resource.<locals>.decorator   sA    LLFG5#<#< 0 @GD!!%";";<Kr   )r   r	   r   r=   r   re   s   ` r   read_resourcezServer.read_resource   s,    	HfXyu/E%EF 	< r   c                 V     dt         t        j                  gt        d    f   f fd}|S )NrY   c                      t         j                  d       dt        j                  f fd}|j                  t        j                  <    S )Nz'Registering handler for SetLevelRequestri   c                    K    | j                   j                         d {    t        j                  t        j                               S 7 +wr   )rk   levelr&   r]   EmptyResultri   rY   s    r   r_   z<Server.set_logging_level.<locals>.decorator.<locals>.handler  s>     3::++,,,))%*;*;*=>> -    AA,A)r,   r-   r&   rN   r)   ra   s   ` r   rb   z+Server.set_logging_level.<locals>.decorator  s@    LLBC?5#8#8 ? <CD!!%"7"78Kr   )r   r&   LoggingLevelr   re   s   ` r   set_logging_levelzServer.set_logging_level  s.    	He&8&8%99T?%JK 	 r   c                 B     dt         t        gt        d    f   f fd}|S )NrY   c                      t         j                  d       dt        j                  f fd}|j                  t        j                  <    S )Nz(Registering handler for SubscribeRequestri   c                    K    | j                   j                         d {    t        j                  t        j                               S 7 +wr   rk   r{   r&   r]   r   r   s    r   r_   z=Server.subscribe_resource.<locals>.decorator.<locals>.handler  <     3::>>***))%*;*;*=>> +r   )r,   r-   r&   SubscribeRequestr)   ra   s   ` r   rb   z,Server.subscribe_resource.<locals>.decorator  s@    LLCD?5#9#9 ? =DD!!%"8"89Kr   r   r	   r   re   s   ` r   subscribe_resourcezServer.subscribe_resource  '    	HfXy%>? 	 r   c                 B     dt         t        gt        d    f   f fd}|S )NrY   c                      t         j                  d       dt        j                  f fd}|j                  t        j                  <    S )Nz*Registering handler for UnsubscribeRequestri   c                    K    | j                   j                         d {    t        j                  t        j                               S 7 +wr   r   r   s    r   r_   z?Server.unsubscribe_resource.<locals>.decorator.<locals>.handler%  r   r   )r,   r-   r&   UnsubscribeRequestr)   ra   s   ` r   rb   z.Server.unsubscribe_resource.<locals>.decorator"  s@    LLEF?5#;#; ? ?FD!!%":":;Kr   r   re   s   ` r   unsubscribe_resourcezServer.unsubscribe_resource!  r   r   c                 b     dt         g t        t        t        j                        f   f fd}|S )NrY   c                      t         j                  d       dt        f fd}|j                  t        j
                  <    S )Nz(Registering handler for ListToolsRequestr[   c                    K            d {   }t        j                  t        j                  |            S 7 -w)N)rE   )r&   r]   ListToolsResult)r[   rE   rY   s     r   r_   z5Server.list_tools.<locals>.decorator.<locals>.handler2  s1     "f))%*?*?e*LMM %r`   )r,   r-   r   r)   r&   rL   ra   s   ` r   rb   z$Server.list_tools.<locals>.decorator/  s<    LLCDN N =DD!!%"8"89Kr   )r   r   rc   r&   Toolre   s   ` r   
list_toolszServer.list_tools.  s/    	HR4

3C)D%DE 	 r   c                      dt         dt        t        t        j                  t        j
                  z  t        j                  z        f   f fd}|S )NrY   .c                      t         j                  d       dt        j                  f fd}|j                  t        j                  <    S )Nz'Registering handler for CallToolRequestri   c                   K   	  | j                   j                  | j                   j                  xs i        d {   }t        j                  t        j
                  t        |      d            S 7 7# t        $ rS}t        j                  t        j
                  t        j                  dt        |            gd            cY d }~S d }~ww xY ww)NF)r   isErrorr|   )typer|   T)
rk   r#   rl   r&   r]   CallToolResultrc   r6   TextContentr=   )ri   resultserY   s      r   r_   z4Server.call_tool.<locals>.decorator.<locals>.handlerH  s     $(3::;O;O;USU$WWG --,,T']ER  X !  --,,%*%6%6FQ%P$Q$( sE   C8A7 A56A7 4C5A7 7	C ACC	CCC)r,   r-   r&   CallToolRequestr)   ra   s   ` r   rb   z#Server.call_tool.<locals>.decorator<  sB     LLBC5#8#8  <CD!!%"7"78Kr   )r   r   r   r&   r   ImageContentEmbeddedResourcere   s   ` r   	call_toolzServer.call_tool;  sT    	))E,>,>>AWAWW	: r   c                 j     dt         t        t        z  t        t        d z  gt        d    f   f fd}|S )NrY   c                      t         j                  d       dt        j                  f fd}|j                  t        j                  <    S )Nz,Registering handler for ProgressNotificationri   c                    K    | j                   j                  | j                   j                  | j                   j                         d {    y 7 wr   )rk   progressTokenprogresstotalr   s    r   r_   z@Server.progress_notification.<locals>.decorator.<locals>.handlera  s>     JJ,,cjj.A.A3::CSCS  s   A
AAA)r,   r-   r&   ProgressNotificationr*   ra   s   ` r   rb   z/Server.progress_notification.<locals>.decorator\  sC     LLGH5#=#= 
 FMD&&u'A'ABKr   )r   r=   intfloatr   re   s   ` r   progress_notificationzServer.progress_notification[  s5    	C#Iuedl;Yt_LM	 r   c                      dt         t        j                  t        j                  z  t        j                  gt
        t        j                  dz     f   f fd}|S )z7Provides completions for prompts and resource templatesrY   Nc                      t         j                  d       dt        j                  f fd}|j                  t        j                  <    S )Nz'Registering handler for CompleteRequestri   c           	        K    | j                   j                  | j                   j                         d {   }t        j                  t        j
                  ||            S t        j                  g d d                   S 7 Pw)N)valuesr   hasMore)
completion)rk   refargumentr&   r]   CompleteResult
Completion)ri   r   rY   s     r   r_   z5Server.completion.<locals>.decorator.<locals>.handlery  s}     #'



8K8K#LL
))((%1 $.  #--RtTR  Ms   5BB	AB)r,   r-   r&   CompleteRequestr)   ra   s   ` r   rb   z$Server.completion.<locals>.decoratorn  sB     LLBC5#8#8  <CD!!%"7"78Kr   )r   r&   PromptReferenceResourceReferenceCompletionArgumentr   r   re   s   ` r   r   zServer.completionk  sY    	))E,C,CC,, %**T12	4	0 r   read_streamwrite_streaminitialization_optionsraise_exceptionsc           
      N  K   t        j                  d      5 }t        |||      4 d {   }|j                  2 3 d {   }t        j                  d|        |xt        d xj\  t        j                  d xT\  } t        j                  dt        |      j                          t        |      | j                  v r| j                  t        |         }	t        j                  dt        |      j                          d }
	 t        j                  t        |j                   |j"                  |            }
 |	|       d {   }|
t        j/                  |
       	 |j1                  |       d {    n<|j1                  t        j*                  t        j2                  d
             d {    t        j                  d       n t        j4                  d x\  }t        |      | j6                  v rot        |      | j6                  v sJ | j6                  t        |         }	t        j                  dt        |      j                          	  |	|       d {    n |D ];  }t        j                  d|j8                  j                   d|j:                          = v7 7 u7 n# t$        $ r}|j&                  }Y d }~d }~wt(        $ r0}|r|t        j*                  dt-        |      d 	      }Y d }~d }~ww xY w# |
t        j/                  |
       w w xY w7 7 }7 # t(        $ r"}t        j'                  d|        Y d }~d }~ww xY w6 d d d       d {  7   n# 1 d {  7  sw Y   nxY wd d d        y # 1 sw Y   y xY ww)NT)recordzReceived message: request)rootzProcessing request of type zDispatching request of type r   )codemessagedatazMethod not found)r   r   zResponse sentz!Dispatching notification of type z,Uncaught exception in notification handler: z	Warning: z: )warningscatch_warningsr   incoming_messagesr,   r-   r   r&   ClientRequestinfor   r   r)   r   setr   
request_idrequest_metar   errorr6   	ErrorDatar=   resetrespondMETHOD_NOT_FOUNDClientNotificationr*   categoryr   )r   r   r   r   r   wsessionr   ri   r_   tokenresponseerrnotifywarnings                  r   runz
Server.run  sR     $$D1 J	Q$\+A I I%,%>%> F F'LL#5gY!?@!T-Te6I6I6ST"KK"=d3i>P>P=Q R  $CyD,A,AA*.*?*?S	*J &&B49CUCUBV$W!" )-!A -8OO(6,3,>,>,3,@,@,3)*-&E 6=S\/AH (-'8(3(9(9%(@&-ooh&? ? ?&-oo$)OO-2-C-C0B%&'" !" !" #LL9Y UZ #55B#F|t/I/II'+F|t7Q7Q'Q Q'Q*.*D*DT&\*R &&G'+F|'<'<&=%?!"
!&*1&/$9$9 C$ $% '(8(8(A(A'B"W__DUVMIF2 0B'/ !9/2yyH'0 !&'7.1	/4-.Ct0&H!& (-'8(3(9(9%(@ (9 !@!"& %:'0 !&$*LL*V+.%)1%& %&!&{ &?I I I I IJ	 J	 J	s/  N%NJ2NM;M( J5
M(CM;?J;
J8
J;,M;;L2
<<M;8L5
9B$M;L:)L8
*L:.AM;2N5M(8J;;	L	K	LL	"%L	LL	LL/	/M;5M;8L::	M%	M 	M; M%	%M;)N4M75N;N	NN		N	N%N"N%)NN)F)"r   r   r   r=   r   r   ro   r   r
   r?   r&   rP   r>   propertyr   r   rW   rf   rq   rw   r   r   r   r   r   r   r   r   r   JSONRPCMessager6   r   r   r   r    r   r   r"   r"   c   s8   	6S 	6 <@FJ
1D8
 $(T#s(^(;#<t#C
 
	
8'
1'
 $(T#s(^(;#<'
 
	!	!	'
R !!> ! !"B@ L "'U.u/C/Ci/OPU -U-A-ABU !6	U Ur   r"   r   r/   c                 X   K   t        j                  t        j                               S wr   )r&   r]   r   r   s    r   r(   r(     s      e//122s   (*)(__doc__contextvarsrF   r   collections.abcr   r   typingr   r   anyio.streams.memoryr   r   pydanticr	   	mcp.typesr&   mcp.server.modelsr
   mcp.server.sessionr   mcp.server.stdior   mcp.shared.contextr   mcp.shared.exceptionsr   mcp.shared.sessionr   	getLoggerr   r,   
ContextVarr   __annotations__r   r"   r'   r]   r(   r    r   r   <module>r     s   <|    /   R   3 , 9 - * /			8	$ K=) [##N=$AB 
	+ 	+z zz3!2!2 3u7I7I 3r   