
    iU                        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	 ddl
mZmZmZmZmZmZmZ ej$                  dk\  rddl
mZ ddl
mZ nddlmZ ddlmZ dd	lmZ d
dlmZmZmZmZmZ d
dlm Z  d
dl!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z* d
dl+m,Z,m-Z- d
dl.m/Z/ d
dl0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z: d
dl;m<Z< d
dl=m>Z> d
dl?m@Z@ d
dlAmAZA d
dlmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZbmcZcmdZdmeZemfZfmgZgmhZhmiZimjZjmkZkmlZlmmZmmnZnmoZompZpmqZqmrZrmsZsmtZtmuZumvZvmwZwmxZxmyZymzZzm{Z{m|Z|m}Z}m~Z~mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ  ej0                  e      Z ed      Ze	 G d dee                Z	 d'dededeeeef   z  dedz  deeegeeeef      f   gee   f   f
dZdedeeef   fd Zd!edeeef   fd"Z	 d(ded#ed$eee      dz  deQfd%Zg d&Zy))zClaude SDK for Python.    N)	AwaitableCallable)	dataclass)	AnnotatedAnyGenericTypeVarUnionget_args
get_origin)      )get_type_hints)is_typeddict)ToolAnnotations   )ClaudeSDKErrorCLIConnectionErrorCLIJSONDecodeErrorCLINotFoundErrorProcessError)import_session_to_store)	ForkSessionResultdelete_sessiondelete_session_via_storefork_sessionfork_session_via_storerename_sessionrename_session_via_storetag_sessiontag_session_via_store)InMemorySessionStoreproject_key_for_directory)fold_session_summary)
get_session_infoget_session_info_from_storeget_session_messagesget_session_messages_from_storeget_subagent_messages get_subagent_messages_from_storelist_sessionslist_sessions_from_storelist_subagentslist_subagents_from_store)	Transport)__version__)ClaudeSDKClient)query)VAgentDefinitionAssistantMessageBaseHookInput
CanUseToolClaudeAgentOptionsContentBlockContextUsageCategoryContextUsageResponseDeferredToolUseHookCallbackHookContextHookEventMessage	HookInputHookJSONOutputHookMatcherMcpSdkServerConfigMcpServerConfigMcpServerConnectionStatusMcpServerInfoMcpServerStatusMcpServerStatusConfigMcpStatusResponseMcpToolAnnotationsMcpToolInfoMessageMirrorErrorMessageNotificationHookInputNotificationHookSpecificOutputPermissionModePermissionRequestHookInput#PermissionRequestHookSpecificOutputPermissionResultPermissionResultAllowPermissionResultDenyPermissionUpdatePostToolUseFailureHookInput$PostToolUseFailureHookSpecificOutputPostToolUseHookInputPreCompactHookInputPreToolUseHookInputRateLimitEventRateLimitInfoRateLimitStatusRateLimitTypeResultMessageSandboxIgnoreViolationsSandboxNetworkConfigSandboxSettingsSdkBetaSdkPluginConfigSDKSessionInfoServerToolNameServerToolResultBlockServerToolUseBlock
SessionKeySessionListSubkeysKeySessionMessageSessionStoreSessionStoreEntrySessionStoreFlushModeSessionStoreListEntrySessionSummaryEntrySettingSourceStopHookInputStreamEventSubagentStartHookInputSubagentStartHookSpecificOutputSubagentStopHookInputSystemMessage
TaskBudgetTaskNotificationMessageTaskNotificationStatusTaskProgressMessageTaskStartedMessage	TaskUsage	TextBlockThinkingBlockThinkingConfigThinkingConfigAdaptiveThinkingConfigDisabledThinkingConfigEnabledToolPermissionContextToolResultBlockToolUseBlockUserMessageUserPromptSubmitHookInputTc                       e Zd ZU dZeed<   eed<   ee   eee	f   z  ed<   e
egeeee	f      f   ed<   dZedz  ed<   y)
SdkMcpToolzDefinition for an SDK MCP tool.namedescriptioninput_schemahandlerNannotations)__name__
__module____qualname____doc__str__annotations__typer   dictr   r   r   r   r        `/volume1/homes/robertsu/coba/app/.venv/lib/python3.12/site-packages/claude_agent_sdk/__init__.pyr   r      sU    )
Iq'DcN**qc9T#s(^4455*.K4'.r   r   r   r   r   r   returnc                      dt         t        gt        t        t        t        f      f   dt
        t           f fd}|S )a+	  Decorator for defining MCP tools with type safety.

    Creates a tool that can be used with SDK MCP servers. The tool runs
    in-process within your Python application, providing better performance
    than external MCP servers.

    Args:
        name: Unique identifier for the tool. This is what Claude will use
            to reference the tool in function calls.
        description: Human-readable description of what the tool does.
            This helps Claude understand when to use the tool.
        input_schema: Schema defining the tool's input parameters.
            Can be either:
            - A dictionary mapping parameter names to types (e.g., {"text": str})
            - A TypedDict class for more complex schemas
            - A JSON Schema dictionary for full validation
            Use ``Annotated[type, "description"]`` to add a description to a
            parameter in either dict-style or TypedDict schemas.

    Returns:
        A decorator function that wraps the tool implementation and returns
        an SdkMcpTool instance ready for use with create_sdk_mcp_server().

    Example:
        Basic tool with simple schema:
        >>> @tool("greet", "Greet a user", {"name": str})
        ... async def greet(args):
        ...     return {"content": [{"type": "text", "text": f"Hello, {args['name']}!"}]}

        Tool with multiple parameters:
        >>> @tool("add", "Add two numbers", {"a": float, "b": float})
        ... async def add_numbers(args):
        ...     result = args["a"] + args["b"]
        ...     return {"content": [{"type": "text", "text": f"Result: {result}"}]}

        Tool with error handling:
        >>> @tool("divide", "Divide two numbers", {"a": float, "b": float})
        ... async def divide(args):
        ...     if args["b"] == 0:
        ...         return {"content": [{"type": "text", "text": "Error: Division by zero"}], "is_error": True}
        ...     return {"content": [{"type": "text", "text": f"Result: {args['a'] / args['b']}"}]}

    Notes:
        - The tool function must be async (defined with async def)
        - The function receives a single dict argument with the input parameters
        - The function should return a dict with a "content" key containing the response
        - Errors can be indicated by including "is_error": True in the response
    r   r   c                 $    t        |       S )N)r   r   r   r   r   )r   )r   r   r   r   r   s    r   	decoratorztool.<locals>.decorator   s!     #%#
 	
r   )r   r   r   r   r   r   )r   r   r   r   r   s   ```` r   toolr      sC    n	
3%4S>!::;	
	C	
 	
 r   py_typec                 ^   t        |       }t        |dd      dv rt        t        |       d         S |t        u r=t        |       }t        |d         }|dd D ]  }t        |t              s||d<    |S  |S | t        u rddiS | t        u rdd	iS | t        u rdd
iS | t        u rddiS t        | dd      }|t        u st        | t        j                        re| j                  }|D cg c]  }|t        j                  us| }}t        |      dk(  rt        |d         S d|D cg c]  }t        |       c}iS |t         u r$t        | dd      }|rdt        |d         dS ddiS |t"        u rddiS | t         u rddiS | t"        u rddiS t%        |       rt'        |       S ddiS c c}w c c}w )z7Convert a Python type annotation to a JSON Schema dict._nameN)NotRequiredRequiredReadOnlyr   r   r   r   stringintegernumberboolean
__origin__anyOf__args__array)r   itemsobject)r   getattr_python_type_to_json_schemar   r   
isinstancer   intfloatboolr
   builtin_types	UnionTyper   NoneTypelenlistr   r   _typeddict_to_json_schema)r   originargsschemametaanon_none	item_argss           r   r   r      s    F vw%)PP*8G+<Q+?@@ ,T!W5HD$$(,}%	  #~!!#~	""%!!$	""WlD1F*Wm.E.EF#Gt!q0F0F'FAtGx=A.x{;;(K(Q5a8(KLL~GZ6	#.I)TU,.WXX  ~!!$  $!!G(11H+ H Ls   &F%>F%%F*td_classc                     t        | d      }i }|j                         D ]  \  }}t        |      ||<    t        | dt	        |j                                     }d|d}|rt        |      |d<   |S )z0Convert a TypedDict class to a JSON Schema dict.T)include_extras__required_keys__r   r   
propertiesrequired)_get_type_hintsr   r   r   setkeyssorted)r   hintsr   
field_name
field_typerequired_keysr   s          r   r   r      sz    HT:E!#J"'++-
J!<Z!H
: #0 H&93z?P;QRM F #M2zMr   versiontoolsc                    ddl m} ddlmmmmmmm	}  || |      }|r
|D ci c]  }|j                  | c}dt        t           dt        t        t        f   fd}dddt        t        t        f   d	z  fd
}|D cg c]C  }|j                  |j                  |j                    ||      |j"                   ||      d      E c}|j%                         dt&        |   ffd       }	|j)                         dt        dt        t        t        f   dt        ffd       }
t+        d| |      S c c}w c c}w )a  Create an in-process MCP server that runs within your Python application.

    Unlike external MCP servers that run as separate processes, SDK MCP servers
    run directly in your application's process. This provides:
    - Better performance (no IPC overhead)
    - Simpler deployment (single process)
    - Easier debugging (same process)
    - Direct access to your application's state

    Args:
        name: Unique identifier for the server. This name is used to reference
            the server in the mcp_servers configuration.
        version: Server version string. Defaults to "1.0.0". This is for
            informational purposes and doesn't affect functionality.
        tools: List of SdkMcpTool instances created with the @tool decorator.
            These are the functions that Claude can call through this server.
            If None or empty, the server will have no tools (rarely useful).

    Returns:
        McpSdkServerConfig: A configuration object that can be passed to
        ClaudeAgentOptions.mcp_servers. This config contains the server
        instance and metadata needed for the SDK to route tool calls.

    Example:
        Simple calculator server:
        >>> @tool("add", "Add numbers", {"a": float, "b": float})
        ... async def add(args):
        ...     return {"content": [{"type": "text", "text": f"Sum: {args['a'] + args['b']}"}]}
        >>>
        >>> @tool("multiply", "Multiply numbers", {"a": float, "b": float})
        ... async def multiply(args):
        ...     return {"content": [{"type": "text", "text": f"Product: {args['a'] * args['b']}"}]}
        >>>
        >>> calculator = create_sdk_mcp_server(
        ...     name="calculator",
        ...     version="2.0.0",
        ...     tools=[add, multiply]
        ... )
        >>>
        >>> # Use with Claude
        >>> options = ClaudeAgentOptions(
        ...     mcp_servers={"calc": calculator},
        ...     allowed_tools=["add", "multiply"]
        ... )

        Server with application state access:
        >>> class DataStore:
        ...     def __init__(self):
        ...         self.items = []
        ...
        >>> store = DataStore()
        >>>
        >>> @tool("add_item", "Add item to store", {"item": str})
        ... async def add_item(args):
        ...     store.items.append(args["item"])
        ...     return {"content": [{"type": "text", "text": f"Added: {args['item']}"}]}
        >>>
        >>> server = create_sdk_mcp_server("store", tools=[add_item])

    Notes:
        - The server runs in the same process as your Python application
        - Tools have direct access to your application's variables and state
        - No subprocess or IPC overhead for tool calls
        - Server lifecycle is managed automatically by the SDK

    See Also:
        - tool(): Decorator for creating tool functions
        - ClaudeAgentOptions: Configuration for using servers with query()
    r   )Server)AudioContentCallToolResultEmbeddedResourceImageContentResourceLinkTextContentTool)r   tool_defr   c                    t        | j                  t              rd| j                  v r7d| j                  v r)t        | j                  d   t              r| j                  S i }| j                  j	                         D ]  \  }}t        |      ||<    d|t        |j                               dS t        | j                        rt        | j                        S di dS )Nr   r   r   )r   r   r   r   )
r   r   r   r   r   r   r   r   r   r   )r   r   
param_name
param_types       r   _build_schemaz,create_sdk_mcp_server.<locals>._build_schema  s    (//6h333$(=(=="8#8#8#@#F#000
.6.C.C.I.I.K*J
-H-TJz* /L %", $Z__%6 7 
 H11201F1FGG$B77r   zSdkMcpTool[Any]Nc                 X    | j                   y t        | j                   dd       }|y d|iS )NmaxResultSizeCharszanthropic/maxResultSizeChars)r   r   )r   max_sizes     r   _build_metaz*create_sdk_mcp_server.<locals>._build_meta  s<    
 ##+x335I4PH2H==r   )r   r   inputSchemar   _metac                     K    S w)z#Return the list of available tools.r   )cached_tool_lists   r   
list_toolsz)create_sdk_mcp_server.<locals>.list_tools  s      $#s   r   	argumentsc           	        K   | vrt        d|  d      |    }|j                  |       d{   }g }d|v rx|d   D ]o  }|j                  d      }|dk(  r|j                   d|d                7|dk(  r!|j                   d|d	   |d
                ]|dk(  rg }|j                  d      }|j                  d      }	|j                  d      }
|r|j                  |       |	r|j                  t	        |	             |
r|j                  |
       |j                   d|rdj                  |      nd             |dk(  rN|j                  d      xs i }d|v r|j                   d|d                Ct        j                  d       Zt        j                  d|       r  ||j                  dd            S 7 w)z,Execute a tool by name with given arguments.zTool 'z' not foundNcontentr   text)r   r   imagedatamimeType)r   r   r   resource_linkr   urir   
zResource linkresourcez>Binary embedded resource cannot be converted to text, skippingz4Unsupported content type %r in tool result, skippingis_errorF)r   isError)
ValueErrorr   getappendr   joinloggerwarning)r   r   r   resultr   item	item_typeparts	link_namer   descr   r   r   r   r   r   r   tool_maps               r   	call_toolz(create_sdk_mcp_server.<locals>.call_tool  s     8# 6${!;<<~H#++I66F   F""9-D $ 0I F*{T&\'RS"g-(%,%)&\)-j)9 #o5 "$(HHV$4	"hhuo#xx6$!LL3!LLS2!LL.'%+9>TYYu%5O #j0#'88J#7#=2!X-#NN +hv>N O #NN ` R%Q .Z "J)F q 7s   -GGFGsdk)r   r   instance)
mcp.serverr   	mcp.typesr   r   r   r   r   r   r   r   r   r   r   r   model_validater   r   r   r   r  rB   )r   r   r   r   r   serverr   r   r   r   r  r   r   r   r   r   r   r   r  s              @@@@@@@@r   create_sdk_mcp_serverr  2  sq   P "   D'*F <ABEHMM8+EB	8JsO 	8S#X 	8(
	>"3 
	>S#X8M 
	>, "
 " $MM#+#7#7#0#:#+#7#7(2 "
 
				$$t* 	$ 
	$
 
			A	# A	$sCx. A	S A	 A	 
A	H 5tfEEy CF
s   EAE)zr2   r0   r/   r1   rO   rC   rB   rF   rG   rD   rE   rH   rI   rJ   r   r4   rw   r|   r{   ry   rz   r}   r_   r;   r[   r\   r]   r^   rs   rK   r7   rx   r~   r   r   r   r   r   r   r   rf   rh   rg   r8   r9   r:   r6   r   rR   rS   rT   rU   r<   r=   r?   r>   r5   rZ   rX   rV   rW   r   rr   rv   rY   rM   rt   rP   rN   ru   rQ   r@   rA   r3   rq   rd   r+   r%   r'   r-   r)   re   rk   ri   rl   rm   rn   ro   rp   rj   r"   r$   rL   r#   r   r,   r&   r(   r.   r*   r   r    r   r   r   r   r!   r   r   rc   rb   ra   r`   r  r   r   r   r   r   r   r   r   )N)z1.0.0N)r   loggingsystypesr   collections.abcr   r   dataclassesr   typingr   r   r   r	   r
   r   r   version_infor   r   r   typing_extensionsr
  r   _errorsr   r   r   r   r   _internal.session_importr   _internal.session_mutationsr   r   r   r   r   r   r   r    r!   _internal.session_storer"   r#   _internal.session_summaryr$   _internal.sessionsr%   r&   r'   r(   r)   r*   r+   r,   r-   r.   _internal.transportr/   _versionr0   clientr1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   r{   r|   r}   r~   r   r   r   r   r   r   r   r   r   r   	getLoggerr   r   r   r   r   r   r   r   r   r   r   r  __all__r   r   r   <module>r!     sD     
  / ! P P Pw8# D. %  >
 
 
 U ;   + ! # W W W W W W W W W W W W W W W W W W W W W Wv 
		8	$CL / / / +/	B
BB c3h'B !4'	B
 xyc3h889:JsOKLBJ3 3c3h 3l c3h & NRUF
UFUF.2:c?.Cd.JUFUFpKr   