
    jKj8                    <   d Z ddlmZ ddlZddlZddlmZmZmZ ddl	m
Z ddlmZmZmZ ddlmZmZmZ ddlmZmZmZmZmZmZmZmZmZmZ dd	lm Z  dd
l!m"Z" ddl#m$Z%m&Z&m'Z' dZ(ddZ)ddZ*dd	 	 	 	 	 	 	 	 	 ddZ+	 	 	 	 	 	 	 	 ddZ,ddZ-ddZ.ddZ/ddZ0ddZ1y)u  Low-level ``mcp.server.Server`` adapter.

The low-level server keeps its handlers in a public ``request_handlers`` dict, so
we wrap the ``CallToolRequest`` and ``ListToolsRequest`` entries directly. Unlike
FastMCP, the low-level ``call_tool`` handler catches exceptions and returns a
``CallToolResult`` with ``isError=True`` rather than raising — so we detect errors
from the result, not a ``try/except``. Session and client info are read from the
server's ``request_context`` contextvar (the handler receives only the request).
    )annotationsN)AnyOptionalTuple   )add_context_parameter_to_schemaget_context_descriptionis_context_enabled)add_conversation_id_to_schemabuild_prompt_backresolve_conversation_id)
_to_jsonableappend_get_more_toolsbuild_tool_call_requestextract_toolsprepare_requestread_tool_categoryrecord_missing_capabilityrecord_tool_callrecord_tools_listrequest_to_dict)MCPAnalyticsData)log)GET_MORE_TOOLS_NAMEget_more_tools_result_text$resolve_missing_capability_tool_name__posthog_mcp_wrapped__c                    t        | dd      |_        t        | dd      |_        t        | |d       t	        | |d       y)u   Instrument a raw ``mcp.server.Server``. ``context`` is injected as an
    optional schema property and NOT stripped — that schema is also the call's
    validation schema, and a typical ``(name, arguments)`` handler ignores extra keys.nameNversionF)strip_injectedcontext_required)getattrserver_nameserver_version_wrap_call_tool_wrap_list_tools)serverdatas     q/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/posthog/mcp/_instrument_lowlevel.pyinstrument_low_levelr,   8   s>     vvt4D!&)T:DFD7VTE:    c                    t        | dd      }|t        d       yt        | dd      xs t        |dd      |_        t        | dd      xs t        |dd      |_        t	        ||d|        t        ||d       y)	u  Instrument jlowin's standalone ``fastmcp.FastMCP`` (FastMCP 2.0). It exposes a
    ``_mcp_server`` (a subclass of the official low-level Server) with the same
    ``request_handlers`` seam, but validates tool args against the function
    signature and rejects unexpected kwargs — so we STRIP the injected
    ``context``/``conversation_id`` before dispatch (like the official FastMCP path)._mcp_serverNz?Warning: fastmcp.FastMCP has no _mcp_server; cannot instrument.r   r    T)r!   
high_levelr"   )r$   r   r%   r&   r'   r(   )r)   r*   	low_levels      r+   instrument_fastmcp_v2r2   B   s     t4IMNvvt4X	6SW8XD!&)T: g9d?D ItDVLYt<r-   )r0   c                     j                   }|j                  t        j                        t	        t
        d      ry d fd}t        |t
        d       ||t        j                  <   y )NFc                  K   | j                   j                  }t        | j                   j                  xs i       }t	              \  }}t              }t        ||      }d|i}t        |||||       d {   }t        j                        }	j                  j                  rw||	k(  rrt        ||	|j                  d      ||||       d {    t        j                  t        j                  t        j                   dt#                     gd            S t%        j                  j&                  |||	      \  }
}r\| j                   j                  rFt)        |       d {   }d	D ]-  }||vs| j                   j                  j+                  |d        / t-        j.                         }	  |        d {   }t-        j.                         |z
  d
z  }t5        |d|      }|
}|ra|
r_t5        |dd       }t5        |dd      sCt7        |t8              r3|j;                  t        j                   dt=        |
      d                nd }t3        |||||||||
       d {    |S 7 7 7 7 # t0        $ r@}t3        ||||t-        j.                         |z
  d
z  |||rd n|
|
       d {  7    d }~ww xY w7 ]w)N
session_idmcp_session_idclient_nameclient_versionrequestextracontext)	tool_namer<   	argumentsr8   r9   r;   text)typer?   F)contentisErrorr<   conversation_id  )r   r>   errorduration_msr8   r9   rD   r;   rootrA   rB   )r   r>   resultrG   r8   r9   rD   r;   )paramsr   dictr>   _client_info_mcp_session_idr   r   r   optionsreport_missingr   get	mcp_typesServerResultCallToolResultTextContentr   r   enable_conversation_id_tool_owned_injected_keyspoptime	monotonic	Exceptionr   r$   
isinstancelistappendr   )reqr   r>   r8   r9   r7   r:   r;   r5   missing_namerD   mintedownedkeystartrI   rF   rG   call_resultdelivered_conversation_idrA   r*   r0   originalr)   r!   s                        r+   handlerz _wrap_call_tool.<locals>.handler\   s    zz--34	&26&:#^(0)$	:~.*)#)
 

 <DLLI<<&&4<+?+&!i0#'-	 	 	 ))((!--!'.H.J
 "	 	 #:LL//D,#
 cjj223JEEE5e#JJ((,,S$7 6  	#C=(F( ~~'%/47 fff5
 %4!ok9d;G;	59jRV>W))#*;O*LV*T -1)##)5
 	
 	
 Q
	B F ) 	 ##!^^-5='-(.O   %	P	
s   A7K:I4;AKI7BK-I:.K<<K9I? I=I? 	B$K-K.K7K:K=I? ?	K4K<J?=KKKTr^   r   returnr   )request_handlersrP   rQ   CallToolRequestr$   _WRAPPED_FLAGsetattr)r)   r*   r!   r0   handlersrg   rf   s   ````  @r+   r'   r'   T   sc     &&H||I556H78]EBp pd G]D)*1HY&&'r-   c                     j                   }|j                  t        j                        t	        t
        d      ry d fd}t        |t
        d       ||t        j                  <   y )NFc                  K   |  |        d {   S t              \  }}t              }t        |       }d|i}t        |||||       d {   }t	        j
                         }	  |        d {   }t	        j
                         |z
  dz  }
t        |      }g }|D ]t  }|j                  |j                         t        |dd       r#|j                  j                  |j                  <   t        |      }|s\|j                  |j                  <   v t!        |      dk(  }t#        j$                  j&                        }t)        j$                  j&                        }|D ]  }|j                  t*        k(  rt        |dd       }|r%t-        |d	      st/        ||j                  |
      }j$                  j0                  r"t-        |d      st3        ||j                        }|t        |dd       us	 ||_         j$                  j8                  rFt;        j$                        t=        fd|D              st?        |       |j                         t        |||tA        |      |
||rdnd |||       d {    |S 7 7 A7 # t        $ r<}	t        |g |t	        j
                         |z
  dz  d|	|||
       d {  7    d }	~	ww xY w# t        $ r t7        d|j                          Y w xY w7 w)Nr5   r6   rE   T)namesr:   rG   is_errorrF   r8   r9   r;   descriptionr   inputSchemar<   )requiredrD   z(WARN: could not set inputSchema on tool c              3  <   K   | ]  }|j                   k(    y wN)r   ).0tr_   s     r+   	<genexpr>z4_wrap_list_tools.<locals>.handler.<locals>.<genexpr>(  s     =u!qvv-us   ztools/list returned no tools)	rq   r:   responserG   rr   rF   r8   r9   r;   )!rL   rM   r   r   rX   rY   rZ   r   r   r]   r   r$   rs   tool_descriptionsr   tool_categorieslenr
   rN   r<   r	   _GET_MORE_TOOLS_NAME_schema_has_paramr   rU   r   rt   r   rO   r   anyr   r   )r^   r8   r9   r7   r:   r;   r5   rc   rI   rF   rG   toolsrq   toolcategoryemptycontext_enabledrs   schemar_   r#   r*   rf   r)   s                      @r+   rg   z!_wrap_list_tools.<locals>.handler   s     ;!#&&&26&:#^(0!#&~. +)#)
 

  	#C=(F ~~'%/47f%DLL#t]D1484D4D&&tyy1)$/H2:$$TYY/  E
a,T\\-A-AB-dll.B.BCDyy00T=$7F '8'K8DII{=M ||22;L)< 7vtyyIWT=$??P'-D$! ( <<&&?ML=u==%fl;\*!&)#490t#)
 	
 	
 y '
 ) 	#!^^-5='-   	b ! PB499+NOP	
s   LJA LJL-J 8J9J =BLC;L?K"BL
L
LLJ 	K#0KKKKL"!LLLLTrh   )rj   rP   rQ   ListToolsRequestr$   rl   rm   )r)   r*   r#   rn   rg   rf   s   ```  @r+   r(   r(      sc     &&H||I667H78]EB` `D G]D)+2HY''(r-   c                v    t        | t              xr( t        | j                  d      t              xr || d   v S )N
properties)r[   rK   rP   )r   r   s     r+   r   r   @  s;    64  	)vzz,/6	)F<((r-   c                B  K   | 
t               S 	 | j                  |       d{   }t        |dd      }|(t        t        j                  |      j
                        n	t               }dD ch c]	  }||v s| c}S 7 Zc c}w # t        $ r t               cY S w xY ww)uI  Which of (``context``, ``conversation_id``) the jlowin FastMCP tool declares
    itself, read from its function signature. These are real tool arguments we must
    not strip. On any lookup failure, return empty (strip both) — same as the prior
    unconditional behaviour, so a flaky introspection never leaks an injected key.NfnrC   )setget_toolr$   inspect	signature
parametersrZ   )r0   r   r   r   rJ   ks         r+   rV   rV   H  s     
 u((..T4&:<.W&&r*556ce9I9aQ&[9II / J usQ   BB A?A	B .	B8B<B >B?B B BBBBc                F    	 | j                   S # t        t        f$ r Y y w xY wrw   )request_contextLookupErrorAttributeError)r)   s    r+   _request_contextr   X  s*    %%%( s      c                    t        |       }	 |j                  j                  }|r8|j                  r,|j                  j                  |j                  j
                  fS y# t        $ r Y yw xY w)N)NN)r   sessionclient_params
clientInfor   r    rZ   )r)   ctxr   s      r+   rL   rL   _  sj    
6
"C11]55 ++00-2J2J2R2RRR   s   AA 	A*)A*c                    t        |       }	 t        |dd       }t        |dd       }||j                  d      S 	 y # t        $ r Y y w xY w)Nr:   headerszmcp-session-id)r   r$   rP   rZ   )r)   r   r:   r   s       r+   rM   rM   j  sd    
6
"C#y$/'9d3;;/00    s   ,< 	AA)r)   r   r*   r   ri   None)
r)   r   r*   r   r!   boolr0   r   ri   r   )r)   r   r*   r   r#   r   ri   r   )r   r   r   strri   r   )r0   r   r   r   ri   r   )r)   r   ri   r   )r)   r   ri   z#Tuple[Optional[str], Optional[str]])r)   r   ri   zOptional[str])2__doc__
__future__r   r   rX   typingr   r   r   	mcp.typestypesrQ   _context_parametersr   r	   r
   _conversation_idr   r   r   _instrumentationr   r   r   r   r   r   r   r   r   r   	_internalr   loggerr   r   r   r   r   r   rl   r,   r2   r'   r(   r   rV   r   rL   rM    r-   r+   <module>r      s   
 #   ' '  
 
   (   *;=& UY{2{2'{2<@{2NQ{2	{2|k3k3'k3>Bk3	k3\ 	r-   