
    "<i5[                        d Z ddlmZ ddlmZ ddlmZmZmZ  ee	          Z
dedz  dedz  fd	Z	 dd
eeef         dedz  deeef         fdZdeeef         deeef         fdZ	 ddededeeeef         eeeeef         f         f         fdZdedeeef         fdZ	 	 ddeeef         deeef         dz  dedz  deeef         dz  fdZg dZdS )z5Schema manipulation utilities for OpenAPI operations.    )Any)
get_logger   )	HTTPRoute
JsonSchemaResponseInfoschemaNreturnc                 ,   | rt          | t                    s| S |                                 }g d}|D ]}||v r|                    |           d|v rDd |d                                         D             |d<   |d         s|                    d           d|v r5t          |d                   |d<   |d         s|                    d           d|v r?t          |d         t                    rt          |d                   |d<   n|d         du r	 |S )zW
    Clean up a schema dictionary for display by removing internal/complex fields.
    )allOfanyOfoneOfnotnullablediscriminatorreadOnly	writeOnly
deprecatedxmlexternalDocs
propertiesc                 4    i | ]\  }}|t          |          S  )clean_schema_for_display).0kvs      /Users/kimhansen/Desktop/03 Workspace/ceo-agents/chl-effectiveness/mcp-servers/whoop/.venv/lib/python3.11/site-packages/fastmcp/utilities/openapi/schemas.py
<dictcomp>z,clean_schema_for_display.<locals>.<dictcomp>0   s4     !
 !
 !
/3q!A'**!
 !
 !
    itemsadditionalPropertiesT)
isinstancedictcopypopr!   r   )r	   cleanedfields_to_removefields       r   r   r      st     FD11  kkmmG  & "  GKK w!
 !
7>|7L7R7R7T7T!
 !
 !
 |$ 	&KK%%%'3GG4DEEw 	!KK   ((g45t<< 	.F.// /G*++ +,44Nr    infodescriptionc                    |                                  }|                    d          x}rwt          |t                    ra|                    d          r$|                    d          d         }d| |d<   n|                    d          st          d| d          ny|                    d	          x}r9d|v rt          |          |d	<   nKd
 |                                D             |d	<   n)|                    d          x}rt          |          |d<   dD ]C}t          |                    |g                     D ]\  }}	t          |	          ||         |<   D|                    d          x}
r't          |
t                    st          |
          |d<   |                     d|          r|                    d          s||d<   |S )a  
    Replace openapi $ref with jsonschema $defs recursively.

    Examples:
    - {"type": "object", "properties": {"$ref": "#/components/schemas/..."}}
    - {"type": "object", "additionalProperties": {"$ref": "#/components/schemas/..."}, "properties": {...}}
    - {"$ref": "#/components/schemas/..."}
    - {"items": {"$ref": "#/components/schemas/..."}}
    - {"anyOf": [{"$ref": "#/components/schemas/..."}]}
    - {"allOf": [{"$ref": "#/components/schemas/..."}]}
    - {"oneOf": [{"$ref": "#/components/schemas/..."}]}

    Args:
        info: dict[str, Any]
        description: str | None

    Returns:
        dict[str, Any]
    $refz#/components/schemas//#/$defs/z#/z/External or non-local reference not supported: z. FastMCP only supports local schema references starting with '#/'. Please include all schema definitions within the OpenAPI document.r   c                 4    i | ]\  }}|t          |          S r   )_replace_ref_with_defs)r   	prop_nameprop_schemas      r   r   z*_replace_ref_with_defs.<locals>.<dictcomp>p   s7     $ $ $*I{ 1+>>$ $ $r    r!   )r   r   r   r"   r+   )r%   getr#   str
startswithsplit
ValueErrorr2   r!   	enumeratebool)r*   r+   r	   ref_pathschema_namer   item_schemasectioniitemr"   s              r   r2   r2   J   s.   , YY[[F::f%%%x >h$$ 		""#:;; &nnS11"5!9K!9!9v((..  Zh Z Z Z  
 zz,//	/ 	>Z#9*#E#EF<  $ $.8.>.>.@.@$ $ $F<   

7++	+ >0==w. > > GR!8!899 	> 	>GAt!7!=!=F7OA	>%zz*@AAA .55 	-C$. .F)* xx{++ ,FJJ}4M4M , +}Mr    c                 0   d| v sd| v sd| v r| S t          |                     d          t                    rd| d         v r| S d| v rN| d         }t          |t                    r0|dv r|dk    rJd| v rF|                                 }g d	}i }|D ]}||v r|                    |          ||<   |ddig|d<   |S |d
k    rJd| v rF|                                 }g d	}i }|D ]}||v r|                    |          ||<   |ddig|d<   |S i }|                                 }g d	}|D ]}||v r|                    |          ||<   |ddig|d<   |S g d	}i }|                                 }|D ]}||v r|                    |          ||<   |ddig|d<   |S | S )z
    Make an optional parameter schema nullable to allow None values.

    For optional parameters, we need to allow null values in addition to the
    specified type to handle cases where None is passed for optional parameters.
    r   r   r   typenull)arrayobjectrE   r!   )defaultr+   titleexamplerF   r   )r#   r5   listr6   r%   r&   )r	   original_typearray_schematop_level_fieldsnullable_schemar)   object_schemaoriginal_schemas           r   !_make_optional_parameter_nullablerQ      s}    &Gv--F1B1B &**V$$d++ &.0H0H vmS)) 7	' 333 !G++60A0A#);;==L'U'U'U$&(O "2 M M L005A5E5Ee5L5LOE20<vv>N/OOG,**"h..<63I3I$*KKMMM'U'U'U$&(O "2 N N M115B5F5Fu5M5MOE20=?O/POG,** ')O&,kkmmO'U'U'U$!1 P P O335D5H5H5O5OOE20?&&AQ/ROG,** $R#Q#Q "$"(++--- L LE//1@1D1DU1K1K.,;ff=M+N(&&Mr    Trouteconvert_refsc                 0   !" i }g }i }t                      t                      t                      t                      d}i }| j        D ]'}||j                                     |j                   (| j        rj| j        j        r]t          t          | j        j                            }|r t          | j        j        |                   }	n| j        j        |         }	| j        j
        r$|	                    d          s| j        j
        |	d<   d|	v rt          |	d         t                    ri }
g }|	d         D ]U}t          |t                    r>d|v r|
                    |d                    d|v r|                    |d                    V|
|	d<   |rt                      !!fd|D             |	d<   |	                    dd           |	                    di           }t                      }|                                D ]}|                    |           t          |                                          }||z  }| j        D ]}|j        |v r|j         d|j         }|j        r|                    |           |j        |j        d	||<   |rt          |j        |j
                  }n?|j                                        }|j
        r|                    d          s
|j
        |d<   |                    dd
          }d|j                                         d}|r| d| |d<   n||d<   |||<   |j        r|                    |j                   |j        |j        d	||j        <   |rt          |j        |j
                  }n?|j                                        }|j
        r|                    d          s
|j
        |d<   |||j        <   | j        r0| j        j        r#d|	v r1|s/|	|d<   | j        j        r|                    d           ddd	|d<   n|r]|                                D ]\  }}|||<   d|d	||<   | j        j        r)|                    |	                    dg                      n|	                    dd                                          }ddl}|                    dd|          }|r|d                                         rd}|	||<   | j        j        r|                    |           d|d	||<   d||d}| j        }|r|r|                                }|                                D ],\  }}t          |t                    rt          |          ||<   -t                      " "fd   |           "rrd}|sKt?          "          }t          "          D ]}||v r  ||                    t?          "          |k    }|K"fd|                                D             |d<   n||d<   ||fS )a  
    Combines parameter and request body schemas into a single schema.
    Handles parameter name collisions by adding location suffixes.
    Also returns parameter mapping for request director.

    Args:
        route: HTTPRoute object

    Returns:
        Tuple of (combined schema dictionary, parameter mapping)
        Parameter mapping format: {'flat_arg_name': {'location': 'path', 'openapi_name': 'id'}}
    )pathqueryheadercookier+   r   r   requiredc                 F    g | ]}|v                      |          |S r   )add)r   xseens     r   
<listcomp>z3_combine_schemas_and_map_params.<locals>.<listcomp>  s3     + + +qDyyDHHQKKyAyyyr    N__)locationopenapi_name (z parameter) r-   bodyrH   r   z[^a-zA-Z0-9_]_	body_datarF   )rC   r   rY   c                    t          | t                    rd| v rft          | d         t                    rK| d         }|                    d          r.                    |                    d          d                    |                                 D ]} |           dS t          | t                    r| D ]} |           dS dS )z%Recursively find all $ref references.r-   r0   r.   r/   N)r#   r$   r6   r7   r[   r8   valuesrJ   )valuerefr   rA   find_refs_in_value	used_refss       r   rl   z;_combine_schemas_and_map_params.<locals>.find_refs_in_value  s    eT** 	1:eFmS+I+I#Fm>>*55 >%MM#))C..*<==="\\^^ . .**1----. .t,, 1 % 1 1**400001 11 1r    Fc                 $    i | ]\  }}|v 	||S r   r   )r   name
def_schemarm   s      r   r   z3_combine_schemas_and_map_params.<locals>.<dictcomp>  s4     # # #(jy(( *(((r    $defs) set
parametersr`   r[   ro   request_bodycontent_schemanextiterr2   r+   r5   r#   rJ   r$   updateextendr&   ri   keysrY   appendschema_r%   
capitalizer!   lowerresubisdigitrequest_schemaslen)#rR   rS   r   rY   parameter_mapparam_names_by_location
body_propsparamcontent_typebody_schemamerged_propsmerged_required
sub_schemaall_non_body_paramslocation_paramsbody_param_namescolliding_paramssuffixed_nameparam_schemaoriginal_desclocation_descr3   r4   
param_namer   resultschema_defsall_defsro   r	   collected_allinitial_countrl   r]   rm   s#                                   @@@r   _combine_schemas_and_map_paramsr      s     JHM %%%%	  J! @ @/33EJ???? '7e0? '7D!3!BCCDD  	J0"1,? KK  ,;LIK) 	H+//-2P2P 	H).);)GK& k!!jW1Et&L&L!L O)'2 G G
j$// G#z11$++J|,DEEE!Z//'..z*/EFFF )5K% uu+ + + +.+ + +J' OOGT*** __\266
 %%299;; 4 4""?3333:??,,--*-== ! 52 52:)))$z==U^==M~ /... "N %
, ,M-(  D5emUEVWW$}1133$ D\-=-=m-L-L D272CL/(,,]B??MH 9 9 ; ;HHHM <1>.P.P.P.P]++.;]+
 )5J}%% ~ ,
+++ "N %
) )M%*%  D5emUEVWW$}1133$ D\-=-=m-L-L D272CL/
 &2Juz""  &Ye0? &Y[    "-Jv!* ('''17$P$PM&!! 	Y*4*:*:*<*<  &	;(3
9% !'$-, ,i((
 !* A
B ? ?@@@ %&99??AAJ III 0#zBBJ )A!6!6!8!8 )(
%0Jz"!* ,
+++5;Z(X(XM*%   F 'K -* ,	*"''))H ( 0 0 D Dffd++ D%;F%C%CHTN I1 1 1 1 1 1 z***   %' D$'	NNM $Y ? ?8++..x~>>>$'	NNm$CM ( D# # # #,4NN,<,<# # #w *F7O=  r    c                 *    t          |           \  }}|S )a@  
    Combines parameter and request body schemas into a single schema.
    Handles parameter name collisions by adding location suffixes.

    This is a backward compatibility wrapper around _combine_schemas_and_map_params.

    Args:
        route: HTTPRoute object

    Returns:
        Combined schema dictionary
    )r   )rR   r	   rf   s      r   _combine_schemasr     s     066IFAMr    	responsesschema_definitionsopenapi_versionc                    | sdS g d}d}|D ]}|| v r
| |         } n|3|                                  D ]\  }}|                    d          r|} n||j        sdS g d}d}|D ]}	|	|j        v r|j        |	         } n|R|j        rKt          t	          |j                            }
|j        |
         }t
                              d|
            |rt          |t                    sdS t          |          }d|v rS|rQ|d         }|                    d          r4|
                    d          d	         }||v rt          ||                   }|r'|                    d
          rddlm}  |||          }|                    d          dk    rdd|idgdd}|}|r|                                }|                                 D ],\  }}t          |t                    rt          |          ||<   -|rT|                    d
          r?ddlm} t          |                                          D ]} |||         |          ||<   ||d<   |S )a  
    Extract output schema from OpenAPI responses for use as MCP tool output schema.

    This function finds the first successful response (200, 201, 202, 204) with a
    JSON-compatible content type and extracts its schema. If the schema is not an
    object type, it wraps it to comply with MCP requirements.

    Args:
        responses: Dictionary of ResponseInfo objects keyed by status code
        schema_definitions: Optional schema definitions to include in the output schema
        openapi_version: OpenAPI version string, used to optimize nullable field handling

    Returns:
        dict: MCP-compliant output schema with potential wrapping, or None if no suitable schema found
    N)2002012022042)zapplication/jsonzapplication/vnd.api+jsonzapplication/hal+jsonzapplication/ld+jsonz	text/jsonz/Using non-JSON content type for output schema: r-   r0   r.   r/   z3.0r   )%convert_openapi_schema_to_json_schemarC   rF   r   T)rC   r   rY   zx-fastmcp-wrap-resultrq   )r!   r7   ru   rv   rw   loggerdebugr#   r$   r2   r8   json_schema_converterr   r5   r%   rJ   rz   )r   r   r   success_codesresponse_infostatus_code	resp_infojson_compatible_typesr	   r   first_content_typeoutput_schemar<   r=   r   wrapped_schemaprocessed_defsro   def_names                      r   $extract_output_schema_from_responsesr     sf   (  t 100M M$  )##%k2ME $
 &/oo&7&7 	 	"K%%c**  ) M$@t   F-  =777"1,?FE 8
 ~-6~!$}'C"D"DEE-.@AR>PRR	
 	
 	
  FD11 t +622M #5 (z** 	X"..--b1K000 67I+7V W W  
?55e<< 
PPPPPP==?
 
   H,, #]3!
%)	
 
 '  0+0022*0022 	F 	FLD&&$'' F'=f'E'Et$  	99%@@ 	TTTTTT !4!4!6!677  +P+P"8,o, ,x(( "0gr    )r   r   rQ   r   r   )N)T)NN)__doc__typingr   fastmcp.utilities.loggingr   modelsr   r   r   __name__r   r   r$   r6   r2   rQ   r;   tupler   r   r   __all__r   r    r   <module>r      s(   ; ;       0 0 0 0 0 0 7 7 7 7 7 7 7 7 7 7	H		;Z$%6 ;:;L ; ; ; ;~ 596 6
sCx.6'*Tz6	#s(^6 6 6 6rKd38n Kc3h K K K K` h! h!h!h! 4S>4T#s(^ 3445h! h! h! h!VI $sCx.    & 15"&z zC%&zS#X-z 4Zz 
#s(^d	z z z z|  r    