
    ~h                       d Z ddlm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mZ ddlZdd	l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 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* ddl+m,Z,m-Z-m.Z. erddl/m0Z0  e*e1      Z2ed   Z3d*dZ4e
e,dgdf   Z5e
e,dgdf   Z6 G d dejn                        Z8 G d dejn                        Z9 ed       G d d             Z: e:e8jv                         gZ<	 	 	 	 	 	 d+d!Z= G d" d#e%      Z> G d$ d%e      Z? G d& d'e      Z@ G d( d)e#      ZAy),z6FastMCP server implementation for OpenAPI integration.    )annotationsN)Counter)Callable)	dataclassfield)Pattern)TYPE_CHECKINGAnyLiteral)EmbeddedResourceImageContentTextContentToolAnnotations)AnyUrl)	ToolError)ResourceResourceTemplate)get_http_headers)FastMCP)Tool_convert_to_content)openapi)
get_logger)	HTTPRoute_combine_schemas!format_description_with_responses)Context)GETPOSTPUTPATCHDELETEOPTIONSHEADc                    | syt        j                  dd|       }t        j                  dd|      }t        j                  dd|      }|j                  d      }|S )z
    Convert text to a URL-friendly slug format that only contains lowercase
    letters, uppercase letters, numbers, and underscores.
     z	[\s\-\.]+_z[^a-zA-Z0-9_]z_+)resubstrip)textslugs     R/opt/mcp/mcp-sentiment/venv/lib/python3.12/site-packages/fastmcp/server/openapi.py_slugifyr.   (   s[    
  66,T*D 66"B-D 66%d#D ::c?DK    MCPTypeMCPType | Nonez7OpenAPITool | OpenAPIResource | OpenAPIResourceTemplatec                       e Zd ZdZdZdZdZdZy)r0   a  Type of FastMCP component to create from a route.

    Enum values:
        TOOL: Convert the route to a callable Tool
        RESOURCE: Convert the route to a Resource (typically GET endpoints)
        RESOURCE_TEMPLATE: Convert the route to a ResourceTemplate (typically GET with path params)
        EXCLUDE: Exclude the route from being converted to any MCP component
        IGNORE: Deprecated, use EXCLUDE instead
    TOOLRESOURCERESOURCE_TEMPLATEEXCLUDEN)__name__
__module____qualname____doc__r3   r4   r5   r6    r/   r-   r0   r0   J   s     DH+Gr/   c                       e Zd ZdZdZdZdZdZy)	RouteTypez
    Deprecated: Use MCPType instead.

    This enum is kept for backward compatibility and will be removed in a future version.
    r3   r4   r5   IGNOREN)r7   r8   r9   r:   r3   r4   r5   r>   r;   r/   r-   r=   r=   ]   s     DH+Fr/   r=   T)kw_onlyc                      e Zd ZU dZ ed      Zded<    ed      Zded<    ed	      Zd
ed<    ee	ddi      Z
ded<    ed	ddi      Zded<    ee	ddi      Zded<   d Zy	)RouteMapzAMapping configuration for HTTP routes to FastMCP component types.*)defaultzlist[HttpMethod] | Literal['*']methodsz.*zPattern[str] | strpatternNzRouteType | MCPType | None
route_typedescriptionz,A set of tags to match. All tags must match.)default_factorymetadataset[str]tagsz(The type of FastMCP component to create.)rC   rI   r1   mcp_typez:A set of tags to apply to the generated FastMCP component.mcp_tagsc                r   | j                   | j                  t        j                  dt        d       t        | j                  t              rt        j                  dt        d       | j                  t        j                  k(  rt        j                  dt        d       t        | j                  t              r3| j                  j                  }|dk(  rd}t        t        |      | _         n)| j                  | _         n| j                   t        d	      | j                  | j                   | _        yy)
z8Validate and process the route map after initialization.NzThe 'route_type' parameter is deprecated and will be removed in a future version. Use 'mcp_type' instead with the appropriate MCPType value.   )
stacklevelz_The RouteType class is deprecated and will be removed in a future version. Use MCPType instead.zdRouteType.IGNORE is deprecated and will be removed in a future version. Use MCPType.EXCLUDE instead.r>   r6   z`mcp_type` must be provided)rL   rF   warningswarnDeprecationWarning
isinstancer=   r>   namegetattrr0   
ValueError)selfroute_type_names     r-   __post_init__zRouteMap.__post_init__   s     == T__%@MMM"	 $//95+& 	 )"2"223& 	 $//95"&//"6"6"h.&/O ' A $]]":;; ??""mmDO #r/   )r7   r8   r9   r:   r   rD   __annotations__rE   rF   setrK   rL   rM   rZ   r;   r/   r-   rA   rA   j   s    K/4S/AG,A"'"6G6-24-@J*@!OPD(   %!KL Hn  W
Hh ',r/   rA   rL   c           	        |D ]/  }|j                   dk(  s| j                  |j                   v s,t        |j                  t              r&|j                  j                  | j                        }n*t        j
                  |j                  | j                        }|s|j                  r5t        | j                  xs g       }|j                  j                  |      s|j                  J t        j                  d| j                   d| j                   d|j                  j                          |c S  t        t         j"                        S )a'  
    Determines the FastMCP component type based on the route and mappings.

    Args:
        route: HTTPRoute object
        mappings: List of RouteMap objects in priority order

    Returns:
        The RouteMap that matches the route, or a catchall "Tool" RouteMap if no match is found.
    rB   Route  z matched mapping to r]   )rD   methodrT   rE   r   searchpathr(   rK   r\   issubsetrL   loggerdebugrU   rA   r0   r3   )routemappings	route_mappattern_matchesroute_tags_sets        r-   _determine_route_typerl      s     !	#u||y7H7H'H)++W5"+"3"3":":5::"F"$))I,=,=uzz"J >>%()9r%:N$>>22>B  !))555U\\N!EJJ<7KIL^L^LcLcKde ! 1!6 W\\**r/   c                  h     e Zd ZdZ	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZddZ	 	 	 	 ddZ xZS )	OpenAPIToolz*Tool implementation for OpenAPI endpoints.c
                r    t         
|   ||||xs
 t               ||	       || _        || _        || _        y )N)rU   rG   
parametersrK   r   
serializer)super__init__r\   _client_route_timeout)rX   clientrg   rU   rG   rp   rK   timeoutr   rq   	__class__s             r-   rs   zOpenAPITool.__init__   sF     	#!#! 	 	
 r/   c                ~    d| j                   d| j                  j                   d| j                  j                   dS )@Custom representation to prevent recursion errors when printing.zOpenAPITool(name=z	, method=, path=))rU   ru   ra   rc   rX   s    r-   __repr__zOpenAPITool.__repr__   s;    "499-y9K9K8LGTXT_T_TdTdSeefggr/   c                  K   | j                   j                  }| j                   j                  D ci c]`  }|j                  dk(  rO|j                  |v rA|j                  |j                        &|j                  |j                  |j                        b }}| j                   j                  D ch c])  }|j                  dk(  r|j                  r|j                  + }}||j                         z
  }|rt        d|       |j                         D ]q  \  }t        fd| j                   j                  D        d      }|r t        |t              r|j                  }	|	j                  d      dk(  }
|
rt        d |D              r-|j                  d d	d
j!                  d |D                    }n	 g }|D ]}  }t        |t"              rQg }|j                         D ]  \  }}|j%                  | d|         |j%                  dj!                  |             d|j%                  t'        |              d
j!                  |      }|j                  d d	|      }S|j                  d d	t'        |            }t i }| j                   j                  D ]  }|j                  dk(  s|j                  |v s#|j                  |j                        ?|j                  |j                        dk7  s^|j                  |j                        }t        |t              r+|j                  j                  d      dk(  r|j                  j                  dd      }|r|||j                  <   t        d |D              r'd
j!                  d |D              ||j                  <   	 g }|D ]}  }t        |t"              rQg }|j                         D ]  \  }}|j%                  | d|         |j%                  dj!                  |             d|j%                  t'        |              d
j!                  |      ||j                  <   |||j                  <    i }i }| j                   j                  D ]d  }|j                  dk(  s|j                  |v s"||j                     2t'        ||j                           ||j                  j/                         <   f |j1                  |       t3               }|j1                  |       d}| j                   j4                  r| j                   j4                  j6                  rk| j                   j                  D ch c]  }|j                  dv r|j                   }}|j                         D ci c]  \  }}||vr|dk7  r|| }}}|r|}	 | j8                  j;                  | j                   j<                  ||||| j>                         d{   }|jA                          	 |jC                         }tK        |      S c c}w c c}w # t(        $ r}t*        j-                  d d|        t'        |      j                  dd      j                  dd      j                  dd      j                  dd      }|j                  d d	|      }Y d}~\d}~ww xY w# t(        $ r?}t*        j-                  d|j                   d|        |||j                  <   Y d}~kd}~ww xY wc c}w c c}}w 7 $# tB        jD                  tF        f$ r |jH                  }Y )w xY w# tL        jN                  $ r}d|jP                  jR                   d |jP                  jT                   }	 |jP                  jC                         }|d!| z  }tG        |      # tB        jD                  tF        f$ r? |jP                  jH                  r|d!|jP                  jH                   z  }Y tG        |      w xY wd}~wtL        jV                  $ r}tG        d"t'        |             d}~ww xY ww)#z:Execute the HTTP request based on the route configuration.rc   Nz"Missing required path parameters: c              3  B   K   | ]  }|j                   k(  s|  y wN)rU   ).0p
param_names     r-   	<genexpr>z"OpenAPITool.run.<locals>.<genexpr>  s     Kqaff
6JKs   typearrayc              3  f   K   | ])  }t        |t        t        z  t        z  t        z         + y wr   rT   strintfloatboolr   items     r-   r   z"OpenAPITool.run.<locals>.<genexpr>)  s-        #4sU):T)AB   /1{},c              3  2   K   | ]  }t        |        y wr   r   r   vs     r-   r   z"OpenAPITool.run.<locals>.<genexpr>/  s     9VQ#a&9V   :.z/Failed to format complex array path parameter 'z': [r&   ]'"queryexplodeTc              3  f   K   | ])  }t        |t        t        z  t        z  t        z         + y wr   r   r   s     r-   r   z"OpenAPITool.run.<locals>.<genexpr>o  s-       $ 'tS3Y->-EFr   c              3  2   K   | ]  }t        |        y wr   r   r   s     r-   r   z"OpenAPITool.run.<locals>.<genexpr>s  s     ;XqCF;Xr   z0Failed to format complex array query parameter 'header)rc   r   r   context)ra   urlparamsheadersjsonrx   HTTP error :  - Request error: ),ru   rc   rp   locationrU   getrequiredkeysr   itemsnextrT   listschema_allreplacejoindictappendr   	Exceptionre   warninglowerupdater   request_bodycontent_schemart   requestra   rv   raise_for_statusr   JSONDecodeErrorrW   r+   r   httpxHTTPStatusErrorresponsestatus_codereason_phraseRequestError) rX   	argumentsrc   r   path_paramsrequired_path_paramsmissing_paramsparam_value
param_infoschemais_arrayformatted_partsr   
item_partskr   formatted_valuee	str_valuequery_paramsr   r   openapi_headersmcp_headers	json_datapath_query_header_paramsbody_paramsr   resulterror_message
error_datar   s                                   @r-   runzOpenAPITool.run   s     {{ [[++
zzV#)#aff%1	 FFIMM!&&))
 
 [[++ 
zzV#

 FF 
  

 .0@0@0BB@@PQRR'2'8'8': :	G#J KDKK22KTJ jd;#++!::f-8  $/ 
  $|| B/9V+9V1V 
P.0O(3 	F#-dD#913J04

 %F1(2(9(9QCq*(E%F$3$:$:388J;O$P %4$:$:3t9$E	F /2hh.GO#'<<"ZL0C_#UD  <<"ZL 3S5EFDu:	Gz '' 4	7A

g%FFi'MM!&&)5MM!&&)R/'mmAFF3 k40QYY]]65Jg5U  iimmIt<G 0;QVV,  (3  4788;XK;X3XL0C24,7 !JD'1$'=57
48JJL )JDAq,6,=,=1QCj,I)J(7(>(>sxx
?S(T(7(>(>s4y(I!J 8;xx7PQVV 4 ,7L(i4	7n  '' 	IA

h&FFi'aff%125i6G2H/	I 	' '({# 	;;##(@(@(O(O //(::!<< ($ ( &OO-Aq44i 1K  '	%	9!\\11{{))# 2  H %%''! 'v..}
 
f  ) P"NN"QR\Q]]`ab`c d
 !$K 0!(b!1!(b!1!(b!1!(b!1 & $(<<"ZL0CY#ODP@ $- C &&VWXW]W]V^^abcad$e!" 8CQVV 4C@(
 ((*5 '!'
 $$ 	, ajj445R

8P8P7QR =ZZ__.
3zl!33
 ]++	 ((*5 =::??!s1::??*;%<<M]++	= !! 	9s1vh788	9sG  /aA%X,a1.X1Ca:B+X6%Aa5aa a?B2a2B"[	A aa$a4B1a%!\a\1a9A] ;\<] \" !
] +a6	[?A<[;a[a		\4\a\a] "%]] 
]] a!0`"^?4`?A`
```a0aaa)NNNN)rw   httpx.AsyncClientrg   openapi.HTTPRouterU   r   rG   r   rp   dict[str, Any]rK   set[str] | Nonerx   float | Noner   zToolAnnotations | Nonerq   zCallable[[Any], str] | Nonereturnr   )r   r   r   z3list[TextContent | ImageContent | EmbeddedResource])r7   r8   r9   r:   rs   r   r   __classcell__ry   s   @r-   rn   rn      s    4 !% $.226 !  !  	 
   #      ,  0 0h[9'[9	<[9r/   rn   c                  d     e Zd ZdZd e       df	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZddZd	dZ xZS )
OpenAPIResourcez.Resource implementation for OpenAPI endpoints.application/jsonNc	                j    t         	|   t        |      ||||       || _        || _        || _        y )N)urirU   rG   	mime_typerK   )rr   rs   r   rt   ru   rv   )
rX   rw   rg   r   rU   rG   r   rK   rx   ry   s
            r-   rs   zOpenAPIResource.__init__  sA     	s# 	 	
 r/   c                j    d| j                   d| j                  d| j                  j                   dS )r{   zOpenAPIResource(name=z, uri=r|   r}   )rU   r   ru   rc   r~   s    r-   r   zOpenAPIResource.__repr__  s1    &tyym6$((WT[[M]M]L^^_``r/   c                  K   	 | j                   j                  }t        | j                        }d|v rd|v r|j	                  d      }t        |      dkD  ri }t        j                  d|      }|rF|j                  d       t        |      dz
  }t        |      D ]  \  }}||k  s|d|z
     }	|	||<    |j                         D ]$  \  }}	|j                  d| dt        |	            }& i }
| j                   j                  D ]]  }|j                  d	k(  st        | d
|j                         s-t!        | d
|j                         }|I|dk7  sO||
|j                  <   _ i }t#               }|j%                  |       | j&                  j)                  | j                   j*                  ||
|| j,                         d{   }|j/                          |j0                  j3                  dd      j5                         dv r%|j7                         }t7        j8                  |      S t;        fddD              r|j<                  S |j>                  S 7 # t@        jB                  $ r}d|jD                  jF                   d|jD                  jH                   }	 |jD                  j7                         }|d| z  }tM        |      # t6        jJ                  tL        f$ r? |jD                  j<                  r|d|jD                  j<                   z  }Y tM        |      w xY wd}~wt@        jN                  $ r}tM        dt        |             d}~ww xY ww)z2Fetch the resource data by making an HTTP request.r   r   /   z\{([^}]+)\}T)reverser   r'   Nr&   )ra   r   r   r   rx   zcontent-typer   c              3  &   K   | ]  }|v  
 y wr   r;   )r   ctcontent_types     r-   r   z'OpenAPIResource.read.<locals>.<genexpr>:  s     OBR<'Os   )ztext/zapplication/xmlr   r   r   r   )(ru   rc   r   r   splitlenr(   findallsort	enumerater   r   rp   r   hasattrrU   rV   r   r   rt   r   ra   rv   r   r   r   r   r   dumpsanyr+   contentr   r   r   r   r   r   rW   r   )rX   rc   resource_uripartsr   param_matchesexpected_param_countir   r   r   paramvaluer   r   r   r   r   r   r   r   s                       @r-   readzOpenAPIResource.read  s5    U	9;;##Dtxx=L d{sd{$**3/u:>"$K %'JJ~t$DM$%**4*8/25zA~, .7}-E FMAz #77.3BFm:EJ 7F 4?3D3D3F S/
K#||bB,?[AQRS L// 9>>W,5::,?O1P#DAejj\*:;E(Ub[38UZZ0	9 G*,KNN;'!\\11{{))# 2  H %%' $++//CIIKL!\1!zz&))O2NOO}}$'''), $$ 	, ajj445R

8P8P7QR =ZZ__.
3zl!33
 ]++	 ((*5 =::??!s1::??*;%<<M]++	= !! 	9s1vh788	9s   MB"I (A0I I 3I I A/I IA&I +M,I MI MI M-0L&"K L&AL#L&"L##L&&M<MMM)rw   r   rg   r   r   r   rU   r   rG   r   r   r   rK   rJ   rx   r   r   )r   zstr | bytes)	r7   r8   r9   r:   r\   rs   r   r
  r   r   s   @r-   r   r     sr    8 , $ !  !  	 
          ,aW9r/   r   c                  t     e Zd ZdZ e       df	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZddZ	 d	 	 	 	 	 	 	 d	dZ xZS )
OpenAPIResourceTemplatez7Resource template implementation for OpenAPI endpoints.Nc	                X    t         	|   |||||       || _        || _        || _        y )N)uri_templaterU   rG   rp   rK   )rr   rs   rt   ru   rv   )
rX   rw   rg   r  rU   rG   rp   rK   rx   ry   s
            r-   rs   z OpenAPIResourceTemplate.__init__U  s=     	%#! 	 	
 r/   c                j    d| j                   d| j                  d| j                  j                   dS )r{   zOpenAPIResourceTemplate(name=z, uri_template=r|   r}   )rU   r  ru   rc   r~   s    r-   r   z OpenAPIResourceTemplate.__repr__k  s8    .tyym?4K\K\J__fgkgrgrgwgwfxxyzzr/   c                  K   g }|j                         D ]  \  }}|j                  | d|         t        | j                  | j                  || j
                   ddj                  |       | j                  xs d| j                  j                   dt        | j                  j                  xs g       | j                        S w)z,Create a resource with the given parameters.=-zResource for r   )rw   rg   r   rU   rG   r   rK   rx   )r   r   r   rt   ru   rU   r   rG   rc   r\   rK   rv   )rX   r   r   r   	uri_partskeyr	  s          r-   create_resourcez'OpenAPIResourceTemplate.create_resourceo  s      	 ,,. 	/JCuAeW-.	/ <<++II;a 345((NmDKK<L<L;M,N(T[[%%+,MM	
 		
s   CC)rw   r   rg   r   r  r   rU   r   rG   r   rp   r   rK   rJ   rx   r   r   r   )r   r   r   r   r   zContext | Noner   r   )	r7   r8   r9   r:   r\   rs   r   r  r   r   s   @r-   r  r  R  s    A  $ !  !  	 
     #     ,{ #'	

 
  	

 

r/   r  c                       e Zd ZdZ	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	 fdZ	 d
	 	 	 	 	 ddZ	 	 	 	 	 	 ddZ	 	 	 	 	 	 ddZ	 	 	 	 	 	 ddZ	 	 	 	 	 	 ddZ	 xZ
S )FastMCPOpenAPIa  
    FastMCP server implementation that creates components from an OpenAPI schema.

    This class parses an OpenAPI specification and creates appropriate FastMCP components
    (Tools, Resources, ResourceTemplates) based on route mappings.

    Example:
        ```python
        from fastmcp.server.openapi import FastMCPOpenAPI, RouteMap, MCPType
        import httpx

        # Define custom route mappings
        custom_mappings = [
            # Map all user-related endpoints to ResourceTemplate
            RouteMap(
                methods=["GET", "POST", "PATCH"],
                pattern=r".*/users/.*",
                mcp_type=MCPType.RESOURCE_TEMPLATE
            ),
            # Map all analytics endpoints to Tool
            RouteMap(
                methods=["GET"],
                pattern=r".*/analytics/.*",
                mcp_type=MCPType.TOOL
            ),
        ]

        # Create server with custom mappings and route mapper
        server = FastMCPOpenAPI(
            openapi_spec=spec,
            client=httpx.AsyncClient(),
            name="API Server",
            route_maps=custom_mappings,
        )
        ```
    c
                   t        |   dd|xs di|
 || _        |	| _        || _        t               t               t               t               d| _        t        j                  |      }|xs g t        z   }|D ]v  }t        ||      }|j                  J |j                  }|J	  |||      }|>|}t        j                  d|j                   d|j                   d|j                           | j'                  ||      }t)        |j*                        |j,                  z  |xs
 t)               z  }|t.        j0                  k(  r| j3                  |||       |t.        j4                  k(  r| j7                  |||       
|t.        j8                  k(  r| j;                  |||       3|t.        j<                  k(  sHt        j?                  d|j                   d|j                          y t        j?                  dtA        |       d       y# t"        $ r>}t        j%                  d|j                   d|j                   d	| d
       Y d}~id}~ww xY w)a  
        Initialize a FastMCP server from an OpenAPI schema.

        Args:
            openapi_spec: OpenAPI schema as a dictionary or file path
            client: httpx AsyncClient for making HTTP requests
            name: Optional name for the server
            route_maps: Optional list of RouteMap objects defining route mappings
            route_map_fn: Optional callable for advanced route type mapping.
                Receives (route, mcp_type) and returns MCPType or None.
                Called on every route, including excluded ones.
            mcp_component_fn: Optional callable for component customization.
                Receives (route, component) and can modify the component in-place.
                Called on every created component.
            mcp_names: Optional dictionary mapping operationId to desired component names.
                If an operationId is not in the dictionary, falls back to using the
                operationId up to the first double underscore. If no operationId exists,
                falls back to slugified summary or path-based naming.
                All names are truncated to 56 characters maximum.
            tags: Optional set of tags to add to all components. Components always receive any tags
                from the route.
            timeout: Optional timeout (in seconds) for all requests
            **settings: Additional settings for FastMCP
        rU   zOpenAPI FastMCP)toolresourceresource_templatepromptNr_   r`   z* mapping customized by route_map_fn: type=zError in route_map_fn for r   z. Using default values.)rK   zExcluding route: z$Created FastMCP OpenAPI server with z routesr;   )!rr   rs   rt   rv   _mcp_component_fnr   _used_namesr   parse_openapi_to_http_routesDEFAULT_ROUTE_MAPPINGSrl   rL   re   rf   ra   rc   rU   r   r   _generate_default_namer\   rK   rM   r0   r3   _create_openapi_toolr4   _create_openapi_resourcer5   _create_openapi_templater6   infor   )rX   openapi_specrw   rU   
route_mapsroute_map_fnmcp_component_fn	mcp_namesrK   rx   settingshttp_routesrg   ri   rF   r   r   component_name
route_tagsry   s                      r-   rs   zFastMCPOpenAPI.__init__  sH   J 	Dd7&7D8D!1 I	!(i	
 ::<H !&B*@@
  $	ME-eZ@I %%111"++J ')%<F)%+
$U\\N!EJJ< @$$.OO#46 "88	JNUZZ9+=+==OJW\\)))%j)Qw///--e^*-Uw888--e^*-Uw./~QuzzlKLI$	ML 	:3{;K:LGTU) ! NN4U\\N!EJJ<rRSQT U0 1 s   )A	H	I "3II c                6   d}|xs i }|j                   r=|j                   |v r||j                      }nH|j                   j                  d      d   }n)|j                  xs |j                   d|j                   }t        |      }t        |      dkD  r|dd }|S )zEGenerate a default name from the route using the configured strategy.r&   __r   r'   8   N)operation_idr   summaryra   rc   r.   r   )rX   rg   mcp_names_maprU   s       r-   r!  z%FastMCPOpenAPI._generate_default_name  s     %+ !!]2$U%7%78 ))//5a8==Bu||nAejj\$BD~ t9r>9Dr/   c           	         | j                   |   |xx   dz  cc<   | j                   |   |   dk(  r|S | d| j                   |   |    }t        j                  d| d|dd  d| d       |S )	a4  
        Ensure the name is unique within its component type by appending numbers if needed.

        Args:
            name: The proposed name
            component_type: The type of component ("tools", "resources", or "templates")

        Returns:
            str: A unique name for the component
        r   r'   zName collision detected: 'z' already exists as a Nr   z	. Using 'z
' instead.)r  re   rf   )rX   rU   component_typenew_names       r-   _get_unique_namezFastMCPOpenAPI._get_unique_name&  s      	(.!3.N+D1Q6K q!1!1.!A$!G HIHLL,TF2HX[Y[I\H] ^":/
 r/   c                   t        |      }| j                  |d      }|j                  xs* |j                  xs d|j                   d|j
                   }t        ||j                  |j                  |j                        }t        | j                  ||||t        |j                  xs g       |z  | j                        }| j                  ,	 | j                  ||       t         j#                  d| d       || j(                  j*                  |<   t         j#                  d| d|j                   d|j
                   d|j                          y# t$        $ r&}	t         j'                  d	| d
|	 d       Y d}	~	d}	~	ww xY w)z?Creates and registers an OpenAPITool with enhanced description.r  z	Executes r`   base_description	responsesrp   r   )rw   rg   rU   rG   rp   rK   rx   NzTool  customized by component_fnzError in component_fn for tool r   . Using component as-is.zRegistered TOOL:  () with tags: )r   r8  rG   r3  ra   rc   r   r<  rp   r   rn   rt   r\   rK   rv   r  re   rf   r   r   _tool_manager_tools)
rX   rg   rU   rK   combined_schema	tool_namer;  enhanced_descriptionr  r   s
             r-   r"  z#FastMCPOpenAPI._create_openapi_toolD  s    +51 ))$7	  7}}75<<.%**6 	  A-oo''++	 
 <<,&UZZ%2&-MM
 !!-&&ud3uYK/JKL 04!!),	{"U\\N!EJJ<}UZU_U_T`a	
  5i[1# F- . s   +E 	FE>>Fc                   | j                  |d      }d| }|j                  xs |j                  xs d|j                   }t	        ||j
                  |j                  |j                        }t        | j                  ||||t        |j                  xs g       |z  | j                        }| j                  ,	 | j                  ||       t        j                  d| d       || j$                  j&                  t)        |j*                        <   t        j                  d| d|j,                   d|j                   d|j                          y# t         $ r&}	t        j#                  d	| d
|	 d       Y d}	~	d}	~	ww xY w)zCCreates and registers an OpenAPIResource with enhanced description.r  resource://zRepresents r:  )rw   rg   r   rU   rG   rK   rx   Nz	Resource r=  z#Error in component_fn for resource r   r>  zRegistered RESOURCE: r?  r`   r@  )r8  rG   r3  rc   r   r<  rp   r   r   rt   r\   rK   rv   r  re   rf   r   r   _resource_manager
_resourcesr   r   ra   )
rX   rg   rU   rK   resource_namer  r;  rE  r  r   s
             r-   r#  z'FastMCPOpenAPI._create_openapi_resourcey  s~    --dJ?$]O4LLK

|2L 	
  A-oo''++	 
 #<<,UZZ%2&-MM
 !!-&&uh7y6QRS @H))#hll*;<#L>ELL>5::,m\a\f\f[gh	
  9,r! M- . s   =+E 	FE>>Fc                   | j                  |d      }|j                  D cg c]  }|j                  dk(  s|j                    }}|j	                          d| }|r|ddj                  d |D              z   z  }|j                  xs |j                  xs d|j                   }t        ||j                  |j                  |j                        }	d|j                  D ci c]  }|j                  dk(  r|j                  i t        |j                  t              r|j                  j                         ni |j                  r6t        |j                  t              rd	|j                  v sd	|j                  ini  c}|j                  D cg c]+  }|j                  dk(  s|j                   s |j                  - c}d
}
t#        | j$                  ||||	|
t'        |j(                  xs g       |z  | j*                        }| j,                  ,	 | j-                  ||       t.        j1                  d| d       || j6                  j8                  |<   t.        j1                  d| d|j:                   d|j                   d|j(                          yc c}w c c}w c c}w # t2        $ r&}t.        j5                  d| d| d       Y d}~d}~ww xY w)zKCreates and registers an OpenAPIResourceTemplate with enhanced description.r  rc   rG  r   c              3  (   K   | ]
  }d | d  yw)r   r   Nr;   )r   r   s     r-   r   z:FastMCPOpenAPI._create_openapi_template.<locals>.<genexpr>  s     .OaA3bz.Os   zTemplate for r:  objectrG   )r   
propertiesr   )rw   rg   r  rU   rG   rp   rK   rx   Nz	Template r=  z#Error in component_fn for template r   r>  zRegistered TEMPLATE: r?  r`   r@  )r8  rp   r   rU   r   r   rG   r3  rc   r   r<  r   rT   r   r   copyr   r  rt   r\   rK   rv   r  re   rf   r   r   rH  
_templatesra   )rX   rg   rU   rK   template_namer   r   uri_template_strr;  rE  template_params_schematemplater   s                r-   r$  z'FastMCPOpenAPI._create_openapi_template  s    --d4GH','7'7P!1::;OqvvPP(8chh.O;.O&O OO NNM%**2N 	
  A-oo''++	 
  )) ::'  
+5aii+Fqyy~~'B
 ==&qyy$7MQYY<V '6
  
 
  !& 0 0AJJ&4HQZZ#"
, +<<),-UZZ%2&-MM	
 !!-&&uh7y)9(::UVW ?G))*:;#$4#5R~QuzzlR_`e`j`j_kl	
C Q**  9:J9K2aS Q- . s;   JJ"BJJ $J 1J +J% %	K.KK)NNNNNNN)r&  r   rw   r   rU   z
str | Noner'  zlist[RouteMap] | Noner(  zRouteMapFn | Noner)  zComponentFn | Noner*  dict[str, str] | NonerK   r   rx   r   r+  r
   r   )rg   r   r4  rU  r   r   )rU   r   r6  z:Literal['tool', 'resource', 'resource_template', 'prompt']r   r   )rg   r   rU   r   rK   rJ   )r7   r8   r9   r:   rs   r!  r8  r"  r#  r$  r   r   s   @r-   r  r    sM   #R  ,0*./3+/ $ $]V$]V "]V 	]V
 *]V (]V -]V )]V ]V ]V ]V@ PT&7L	2 S 
	<3
 3
 3
 	3
j0
 0
 0
 	0
dM
 M
 M
 	M
r/   r  )r+   r   r   r   )rg   r   rh   zlist[RouteMap]r   rA   )Br:   
__future__r   enumr   r(   rQ   collectionsr   collections.abcr   dataclassesr   r   r   typingr	   r
   r   r   	mcp.typesr   r   r   r   pydantic.networksr   fastmcp.exceptionsr   fastmcp.resourcesr   r   fastmcp.server.dependenciesr   fastmcp.server.serverr   fastmcp.tools.toolr   r   fastmcp.utilitiesr   fastmcp.utilities.loggingr   fastmcp.utilities.openapir   r   r   fastmcp.serverr   r7   re   
HttpMethodr.   
RouteMapFnComponentFnEnumr0   r=   rA   r3   r   rl   rn   r   r  r  r;   r/   r-   <module>rk     s[   < "   	   $ (  . .  R R $ ( 8 8 ) 8 % 0  &	H	OP
0 y),.>>?
A 		
dii &
		 
 4<, <, <,D gll# 
*+*+*+ *+Zz9$ z9zt9h t9n3
. 3
lp
W p
r/   