
    ~h1k                    *   U d dl mZ d dl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mZ d dlmZmZmZmZ d d	lmZ d d
lmZmZ d dlmZ d dlmZ  ee      ZdZ edd      Zde d<   ddZ!ddZ" ed       G d d             Z# G d de      Z$y)    )annotationsN)Callable)
ContextVar)	dataclass)EllipsisType)AnyLiteral)EmbeddedResourceImageContentTextContentToolAnnotations)
ConfigDict)ParsedFunctionTool)
get_logger)get_cached_typeadapter._current_tool)defaultz"ContextVar[TransformedTool | None]c                    K   t         j                         }|t        d       |j                  di |  d{   S 7 w)aC  Forward to parent tool with argument transformation applied.

    This function can only be called from within a transformed tool's custom
    function. It applies argument transformation (renaming, validation) before
    calling the parent tool.

    For example, if the parent tool has args `x` and `y`, but the transformed
    tool has args `a` and `b`, and an `transform_args` was provided that maps `x` to
    `a` and `y` to `b`, then `forward(a=1, b=2)` will call the parent tool with
    `x=1` and `y=2`.

    Args:
        **kwargs: Arguments to forward to the parent tool (using transformed names).

    Returns:
        The result from the parent tool execution.

    Raises:
        RuntimeError: If called outside a transformed tool context.
        TypeError: If provided arguments don't match the transformed schema.
    Nz6forward() can only be called within a transformed tool )r   getRuntimeErrorforwarding_fnkwargstools     X/opt/mcp/mcp-sentiment/venv/lib/python3.12/site-packages/fastmcp/tools/tool_transform.pyforwardr      sE     , D|STT $##-f----s   7A >A c                    K   t         j                         }|t        d      |j                  j	                  |        d{   S 7 w)a  Forward directly to parent tool without transformation.

    This function bypasses all argument transformation and validation, calling the parent
    tool directly with the provided arguments. Use this when you need to call the parent
    with its original parameter names and structure.

    For example, if the parent tool has args `x` and `y`, then `forward_raw(x=1,
    y=2)` will call the parent tool with `x=1` and `y=2`.

    Args:
        **kwargs: Arguments to pass directly to the parent tool (using original names).

    Returns:
        The result from the parent tool execution.

    Raises:
        RuntimeError: If called outside a transformed tool context.
    Nz:forward_raw() can only be called within a transformed tool)r   r   r   parent_toolrunr   s     r   forward_rawr"   :   sD     & D|WXX!!%%f----s   A A	AA	T)kw_onlyc                  z    e Zd ZU dZeZded<   eZded<   eZded<   eZ	ded<   eZ
ded	<   d
Zded<   eZded<   d Zy)ArgTransforma  Configuration for transforming a parent tool's argument.

    This class allows fine-grained control over how individual arguments are transformed
    when creating a new tool from an existing one. You can rename arguments, change their
    descriptions, add default values, or hide them from clients while passing constants.

    Attributes:
        name: New name for the argument. Use None to keep original name, or ... for no change.
        description: New description for the argument. Use None to remove description, or ... for no change.
        default: New default value for the argument. Use ... for no change.
        default_factory: Callable that returns a default value. Cannot be used with default.
        type: New type for the argument. Use ... for no change.
        hide: If True, hide this argument from clients but pass a constant value to parent.
        required: If True, make argument required (remove default). Use ... for no change.

    Examples:
        # Rename argument 'old_name' to 'new_name'
        ArgTransform(name="new_name")

        # Change description only
        ArgTransform(description="Updated description")

        # Add a default value (makes argument optional)
        ArgTransform(default=42)

        # Add a default factory (makes argument optional)
        ArgTransform(default_factory=lambda: time.time())

        # Change the type
        ArgTransform(type=str)

        # Hide the argument entirely from clients
        ArgTransform(hide=True)

        # Hide argument but pass a constant value to parent
        ArgTransform(hide=True, default="constant_value")

        # Hide argument but pass a factory-generated value to parent
        ArgTransform(hide=True, default_factory=lambda: uuid.uuid4().hex)

        # Make an optional parameter required (removes any default)
        ArgTransform(required=True)

        # Combine multiple transformations
        ArgTransform(name="new_name", description="New desc", default=None, type=int)
    zstr | EllipsisTypenamedescriptionzAny | EllipsisTyper   z Callable[[], Any] | EllipsisTypedefault_factorytypeFboolhidezLiteral[True] | EllipsisTyperequiredc                R   | j                   t        u}| j                  t        u}|r|rt        d      |r| j                  st        d      | j
                  du r|s|rt        d      | j                  r| j
                  du rt        d      | j
                  du rt        d      y)	zAValidate that only one of default or default_factory is provided.zCannot specify both 'default' and 'default_factory' in ArgTransform. Use either 'default' for a static value or 'default_factory' for a callable.zdefault_factory can only be used with hide=True. Visible parameters must use static 'default' values since JSON schema cannot represent dynamic factories.TzmCannot specify 'required=True' with 'default' or 'default_factory'. Required parameters cannot have defaults.z|Cannot specify both 'hide=True' and 'required=True'. Hidden parameters cannot be required since clients cannot provide them.Fz=Cannot specify 'required=False'. Set a default value instead.N)r   NotSetr(   
ValueErrorr+   r,   )selfhas_defaulthas_factorys      r   __post_init__zArgTransform.__post_init__   s    ll&0**&8;_ 
 tyy6  ==D k[< 
 99$.Z 
 ==E!O  "    N)__name__
__module____qualname____doc__r.   r&   __annotations__r'   r   r(   r)   r+   r,   r3   r   r4   r   r%   r%   T   s[    -^  &D
%&,K#,"(G(8>O5>%D
%D$-3H*3!r4   r%   c                     e Zd ZU dZ edd      Zded<   ded<   ded	<   d
ed<   	 	 	 	 ddZe	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Z	e	 	 	 	 	 	 dd       Z
e	 	 	 	 	 	 	 	 	 	 dd       Ze	 	 	 	 	 	 dd       Zedd       Zy)TransformedToola  A tool that is transformed from another tool.

    This class represents a tool that has been created by transforming another tool.
    It supports argument renaming, schema modification, custom function injection,
    and provides context for the forward() and forward_raw() functions.

    The transformation can be purely schema-based (argument renaming, dropping, etc.)
    or can include a custom function that uses forward() to call the parent tool
    with transformed arguments.

    Attributes:
        parent_tool: The original tool that this tool was transformed from.
        fn: The function to execute when this tool is called (either the forwarding
            function for pure transformations or a custom user function).
        forwarding_fn: Internal function that handles argument transformation and
            validation when forward() is called from custom functions.
    allowT)extraarbitrary_types_allowedr   r    Callable[..., Any]fnr   zdict[str, ArgTransform]transform_argsc                  K   ddl m} |j                         }| j                  j	                  di       }|j                         D ]  \  }}||vsd|v sd}| j                  r| j                  j                         D ]j  \  }}|j                  t        ur|j                  n|}	|	|k(  s,|j                  t        us?t        |j                        sU|j                         ||<   d} n |r|d   ||<    t        j                  |       }
	  | j                  d	i | d{   } ||| j                        t        j                  |
       S 7 -# t        j                  |
       w xY ww)
a  Run the tool with context set for forward() functions.

        This method executes the tool's function while setting up the context
        that allows forward() and forward_raw() to work correctly within custom
        functions.

        Args:
            arguments: Dictionary of arguments to pass to the tool's function.

        Returns:
            List of content objects (text, image, or embedded resources) representing
            the tool's output.
        r   )_convert_to_content
propertiesr   FTN)
serializerr   )fastmcp.tools.toolrC   copy
parametersr   itemsrA   r&   r.   r(   callabler   setr@   rE   reset)r0   	argumentsrC   rD   
param_nameparam_schemahas_factory_default	orig_name	transformtransform_nametokenresults               r   r!   zTransformedTool.run   sg      	; NN$	__((r:
(2(8(8(: 	D$J*yL/H ',#&&040C0C0I0I0K &,	9  )~~V; &NN!* ' +j8 ) 9 9 G  (	(A(AB8A8Q8Q8S	* 56: 3 %&  +,8,CIj)1	D4 !!$'	'"477/Y//F&v$//J& 0 &sU   AE,E,AE,)E,<E,E,-E,E "E#E :E,E E))E,Nc
                   |xs i }t        |j                  j                  di       j                               }
t        |j                               |
z
  }|rAt	        ddj                  t        |             ddj                  t        |
                   | j                  ||      \  }}||}|}n	t        j                  |d      }|}| j                  |      }t        |j                  j                  di       j                               }t        |j                  di       j                               }|se||z
  }|rAt	        ddj                  t        |             ddj                  t        |                   | j                  |j                  |      }n| j                  |j                  |      }|rg }|j                         D ]Q  \  }}|j                  r|j                  t        ur|j!                  |j                         A|j!                  |       S i }|D ]  }|j                  |d	      d
z   ||<    |j                         D cg c]  \  }}|d
kD  s| }}}|r&t	        ddj                  t        |                   ||n|j"                  } | ||||xs |j                  |||xs |j$                  |xs |j&                  |xs |j(                  ||	|	nd      }|S c c}}w )a:  Create a transformed tool from a parent tool.

        Args:
            tool: The parent tool to transform.
            transform_fn: Optional custom function. Can use forward() and forward_raw()
                to call the parent tool. Functions with **kwargs receive transformed
                argument names.
            name: New name for the tool. Defaults to parent tool's name.
            transform_args: Optional transformations for parent tool arguments.
                Only specified arguments are transformed, others pass through unchanged:
                - str: Simple rename
                - ArgTransform: Complex transformation (rename/description/default/drop)
                - None: Drop the argument
            description: New description. Defaults to parent's description.
            tags: New tags. Defaults to parent's tags.
            annotations: New annotations. Defaults to parent's annotations.
            serializer: New serializer. Defaults to parent's serializer.

        Returns:
            TransformedTool with the specified transformations.

                Examples:
            # Transform specific arguments only
            Tool.from_tool(parent, transform_args={"old": "new"})  # Others unchanged

            # Custom function with partial transforms
            async def custom(x: int, y: int) -> str:
                result = await forward(x=x, y=y)
                return f"Custom: {result}"

            Tool.from_tool(parent, transform_fn=custom, transform_args={"a": "x", "b": "y"})

            # Using **kwargs (gets all args, transformed and untransformed)
            async def flexible(**kwargs) -> str:
                result = await forward(**kwargs)
                return f"Got: {kwargs}"

            Tool.from_tool(parent, transform_fn=flexible, transform_args={"a": "x"})
        rD   z%Unknown arguments in transform_args: , z. Parent tool has: F)validatez;Function missing parameters required after transformation: z. Function declares: r      z6Multiple arguments would be mapped to the same names: T)r@   r   r    r&   r'   rH   tagsr   rE   rA   enabled)rK   rH   r   keysr/   joinsorted_create_forwarding_transformr   from_function_function_has_kwargs_merge_schema_with_precedencerI   r+   r&   r.   appendr'   rZ   r   rE   )clsr   r&   r'   rZ   transform_fnrA   r   rE   r[   parent_paramsunknown_argsschemar   final_fnfinal_schema	parsed_fn
has_kwargs	fn_paramstransformed_paramsmissing_params	new_namesold_namerR   name_countsarg_namecount
duplicatesfinal_descriptiontransformed_tools                                 r   	from_toolzTransformedTool.from_tool  s   h (-2 DOO//bAFFHI>..01MA7		&BV8W7X Y$$(IIf].C$D#EG  !$ @ @~ V$H!L '44\ERI#H11,?J I0044\2FKKMNI!$VZZb%A%F%F%H!I "4i!?!$U99VN%;<= >..2iiy8I.J-KM   #@@((&   #@@((& 
 I'5';';'= 3#) ~~ ~~V3!((8!((23 K% I(3!(Dq(HH%I 1<0A0A0C,XuuqyJ   Lyy
!3457 
 ,7+BKHXHX'")#"#7t'7'7!4T__)&2G
  3s   K9)K9c                v   j                   j                  di       j                         }t        j                   j                  dg             }i t               i i |j	                         D ]  \  }}|r
||v r||   }n
t               }|j                  rC|j                  t        uxs |j                  t        u}|s||v rt        d| d      |r||<   k| j                  |||||v       }	|	s|	\  }
}}||
<   ||
<   |sj                  |
        dt              d}fd}||fS )a  Create schema and forwarding function that encapsulates all transformation logic.

        This method builds a new JSON schema for the transformed tool and creates a
        forwarding function that validates arguments against the new schema and maps
        them back to the parent tool's expected arguments.

        Args:
            parent_tool: The original tool to transform.
            transform_args: Dictionary defining how to transform each argument.

        Returns:
            A tuple containing:
            - dict: The new JSON schema for the transformed tool
            - Callable: Async function that validates and forwards calls to the parent tool
        rD   r,   zHidden parameter 'z' has no default value in parent tool and no default or default_factory provided in ArgTransform. Either provide a default or default_factory in ArgTransform or don't hide required parameters.objectr)   rD   r,   c                   K   t        j                               }t        | j                               }||z
  }|r&t        ddj                  t	        |                   |z
  }|r&t        ddj                  t	        |                   i }| j                         D ]  \  }}j                  ||      }|||<    
j                         D ]c  \  }}	|	j                  t        ur|	j                  ||<   (|	j                  t        us;t        |	j                        sQ|	j                         ||<   e j                  |       d {   S 7 w)Nz$Got unexpected keyword argument(s): rW   zMissing required argument(s): )rK   r\   	TypeErrorr]   r^   rI   r   r   r.   r(   rJ   r!   )r   
valid_argsprovided_argsrg   missing_argsparent_argsnew_namevaluerq   rR   hidden_defaults	new_propsnew_required
new_to_oldr    s             r   _forwardz>TransformedTool._create_forwarding_transform.<locals>._forward  sO    Y^^-.J.M(:5L:499VLEY;Z:[\ 
 (-7L4TYYvl?S5T4UV 
 K#)<<> .%%>>(H=(-H%.
 (7'<'<'> L#)$$F2,5,=,=K)..f<	 9 9:090I0I0KH-L %5555s   DEE")EEE)rH   r   rG   rK   rI   r%   r+   r   r.   r(   r/   _apply_single_transformaddlist)rd   r    rA   parent_propsparent_requiredrq   
old_schemarR   has_user_defaulttransform_resultr   
new_schemais_requiredrh   r   r   r   r   r   s    `             @@@@r   r_   z,TransformedTool._create_forwarding_transform  s   . #--11,CHHJk4488RHI	u
$0$6$6$8 '	/ Hj(n"<*84	 )N	 ~~ %%V3 ? 00> ! (H,G$,XJ 7` a 
 $09OH-"::O+	   4D1*k&0	(#'/
8$ $$X.O'	/T #\*
!	6 !	6F xr4   c                   |j                   ry|j                  t        ur|j                  |j                  n| }n| }t        |t              s| }|j                         }|j                  t        ur.|j                  |j                  dd       n|j                  |d<   |j                  t        ur5t        |j                        }|j                  du r|j                  dd       |j                  t        ur|j                  dur|j                  |d<   d}|j                  t        ur4t        |j                        j                         }|j                  |       |||fS )ap  Apply transformation to a single parameter.

        This method handles the transformation of a single argument according to
        the specified transformation rules.

        Args:
            old_name: Original name of the parameter.
            old_schema: Original JSON schema for the parameter.
            transform: ArgTransform object specifying how to transform the parameter.
            is_required: Whether the original parameter was required.

        Returns:
            Tuple of (new_name, new_schema, new_is_required) if parameter should be kept,
            None if parameter should be dropped.
        Nr'   Tr   F)r+   r&   r.   
isinstancestrrG   r'   popr,   r*   r   r)   r   json_schemaupdate)rq   r   rR   r   r   r   type_schemas          r   r   z'TransformedTool._apply_single_transform  s:   , >> >>')2)Cy~~HH (C(H__&
   .$$,}d3,5,A,A
=) V+y112K!!T)y$/ F*y/A/A/M$-$5$5Jy!K >>'0@LLNKk*[00r4   c                   | j                  di       j                         }t        | j                  dg             }|j                  di       }t        |j                  dg             }|j                         D ]F  \  }}||v r*||   j                         }|j	                  |       |||<   4|j                         ||<   H |j                         }	|D ];  }||vr|	j                  |       ||v sd||   vs&||vs+|	j                  |       = |j                         D ]  \  }}d|v s|	j                  |        d|t        |	      dS )a*  Merge two schemas, with the override schema taking precedence.

        Args:
            base_schema: Base schema to start with
            override_schema: Schema that takes precedence for overlapping properties

        Returns:
            Merged schema with override taking precedence
        rD   r,   r   rz   r{   )r   rG   rK   rI   r   r   discardr   )
base_schemaoverride_schemamerged_propsmerged_requiredoverride_propsoverride_requiredrN   rO   
base_paramfinal_requireds
             r   rb   z-TransformedTool._merge_schema_with_precedenceM  sw    #|R8==?kooj"=>(,,\2> 3 3J CD )7(<(<(> 	?$J\))*5::<
!!,/+5Z(+7+<+<+>Z(	? +//1 * 	3J/"":.n,\*%== %66 #&&z2	3 )5(:(:(< 	3$JL(&&z2	3
 &^,
 	
r4   c                    t        j                  |       }t        d |j                  j	                         D              S )ab  Check if function accepts **kwargs.

        This determines whether a custom function can accept arbitrary keyword arguments,
        which affects how schemas are merged during tool transformation.

        Args:
            fn: Function to inspect.

        Returns:
            True if the function has a **kwargs parameter, False otherwise.
        c              3  j   K   | ]+  }|j                   t        j                  j                  k(   - y w)N)kindinspect	ParameterVAR_KEYWORD).0ps     r   	<genexpr>z7TransformedTool._function_has_kwargs.<locals>.<genexpr>  s*      
89AFFg''333
s   13)r   	signatureanyrH   values)r@   sigs     r   ra   z$TransformedTool._function_has_kwargs  s;     # 
=@^^=R=R=T
 
 	
r4   )rM   dict[str, Any]returnz3list[TextContent | ImageContent | EmbeddedResource])NNNNNNNN)r   r   r&   
str | Noner'   r   rZ   zset[str] | Nonere   zCallable[..., Any] | NonerA   dict[str, ArgTransform] | Noner   zToolAnnotations | NonerE   zCallable[[Any], str] | Noner[   zbool | Noner   r;   )r    r   rA   r   r   z)tuple[dict[str, Any], Callable[..., Any]])
rq   r   r   r   rR   r%   r   r*   r   z'tuple[str, dict[str, Any], bool] | None)r   r   r   r   r   r   )r@   r?   r   r*   )r5   r6   r7   r8   r   model_configr9   r!   classmethodrx   r_   staticmethodr   rb   ra   r   r4   r   r;   r;      s   $ GTJL%%++6''6'	<6'p   "& $269=.226#R R  R   	R 
 R  0R  7R  ,R  0R  R  
R  R h q q  7q  
3	q  q f >1>1">1  >1 	>1
 
1>1 >1@ 9
#9
6D9
	9
 9
v 
 
r4   r;   )r   r   )%
__future__r   r   collections.abcr   contextvarsr   dataclassesr   typesr   typingr   r	   	mcp.typesr
   r   r   r   pydanticr   rF   r   r   fastmcp.utilities.loggingr   fastmcp.utilities.typesr   r5   loggerr.   r   r9   r   r"   r%   r;   r   r4   r   <module>r      s    "  $ " !   R R  3 0 :	H		 5?T51 
.<.4 4Y Y Yxh
d h
r4   