@@ -324,11 +324,14 @@ async def _messages_create(
324324 def _process_response (self , response : BetaMessage ) -> ModelResponse :
325325 """Process a non-streamed response, and prepare a message to return."""
326326 items : list [ModelResponsePart ] = []
327+ builtin_tool_calls : dict [str , BuiltinToolCallPart ] = {}
327328 for item in response .content :
328329 if isinstance (item , BetaTextBlock ):
329330 items .append (TextPart (content = item .text ))
330331 elif isinstance (item , BetaServerToolUseBlock ):
331- items .append (_map_server_tool_use_block (item , self .system ))
332+ call_part = _map_server_tool_use_block (item , self .system )
333+ builtin_tool_calls [call_part .tool_call_id ] = call_part
334+ items .append (call_part )
332335 elif isinstance (item , BetaWebSearchToolResultBlock ):
333336 items .append (_map_web_search_tool_result_block (item , self .system ))
334337 elif isinstance (item , BetaCodeExecutionToolResultBlock ):
@@ -340,9 +343,12 @@ def _process_response(self, response: BetaMessage) -> ModelResponse:
340343 elif isinstance (item , BetaThinkingBlock ):
341344 items .append (ThinkingPart (content = item .thinking , signature = item .signature , provider_name = self .system ))
342345 elif isinstance (item , BetaMCPToolUseBlock ):
343- items .append (_map_mcp_server_use_block (item , self .system ))
346+ call_part = _map_mcp_server_use_block (item , self .system )
347+ builtin_tool_calls [call_part .tool_call_id ] = call_part
348+ items .append (call_part )
344349 elif isinstance (item , BetaMCPToolResultBlock ):
345- items .append (_map_mcp_server_result_block (item , self .system ))
350+ call_part = builtin_tool_calls .get (item .tool_use_id )
351+ items .append (_map_mcp_server_result_block (item , call_part , self .system ))
346352 else :
347353 assert isinstance (item , BetaToolUseBlock ), f'unexpected item type { type (item )} '
348354 items .append (
@@ -545,9 +551,9 @@ async def _map_message(self, messages: list[ModelMessage]) -> tuple[str, list[Be
545551 )
546552 assistant_content_params .append (server_tool_use_block_param )
547553 elif (
548- response_part .tool_name == MCPServerTool .kind
554+ response_part .tool_name .startswith (MCPServerTool .kind )
555+ and (server_id := response_part .tool_name .split (':' , 1 )[1 ])
549556 and (args := response_part .args_as_dict ())
550- and (server_id := args .get ('server_id' ))
551557 and (tool_name := args .get ('tool_name' ))
552558 and (tool_args := args .get ('tool_args' ))
553559 ): # pragma: no branch
@@ -590,7 +596,7 @@ async def _map_message(self, messages: list[ModelMessage]) -> tuple[str, list[Be
590596 ),
591597 )
592598 )
593- elif response_part .tool_name == MCPServerTool .kind and isinstance (
599+ elif response_part .tool_name . startswith ( MCPServerTool .kind ) and isinstance (
594600 response_part .content , dict
595601 ): # pragma: no branch
596602 assistant_content_params .append (
@@ -714,6 +720,7 @@ class AnthropicStreamedResponse(StreamedResponse):
714720 async def _get_event_iterator (self ) -> AsyncIterator [ModelResponseStreamEvent ]: # noqa: C901
715721 current_block : BetaContentBlock | None = None
716722
723+ builtin_tool_calls : dict [str , BuiltinToolCallPart ] = {}
717724 async for event in self ._response :
718725 if isinstance (event , BetaRawMessageStartEvent ):
719726 self ._usage = _map_usage (event , self ._provider_name , self ._provider_url , self ._model_name )
@@ -751,9 +758,11 @@ async def _get_event_iterator(self) -> AsyncIterator[ModelResponseStreamEvent]:
751758 if maybe_event is not None : # pragma: no branch
752759 yield maybe_event
753760 elif isinstance (current_block , BetaServerToolUseBlock ):
761+ call_part = _map_server_tool_use_block (current_block , self .provider_name )
762+ builtin_tool_calls [call_part .tool_call_id ] = call_part
754763 yield self ._parts_manager .handle_part (
755764 vendor_part_id = event .index ,
756- part = _map_server_tool_use_block ( current_block , self . provider_name ) ,
765+ part = call_part ,
757766 )
758767 elif isinstance (current_block , BetaWebSearchToolResultBlock ):
759768 yield self ._parts_manager .handle_part (
@@ -767,6 +776,7 @@ async def _get_event_iterator(self) -> AsyncIterator[ModelResponseStreamEvent]:
767776 )
768777 elif isinstance (current_block , BetaMCPToolUseBlock ):
769778 call_part = _map_mcp_server_use_block (current_block , self .provider_name )
779+ builtin_tool_calls [call_part .tool_call_id ] = call_part
770780
771781 args_json = call_part .args_as_json_str ()
772782 # Drop the final `{}}` so that we can add tool args deltas
@@ -785,9 +795,10 @@ async def _get_event_iterator(self) -> AsyncIterator[ModelResponseStreamEvent]:
785795 if maybe_event is not None : # pragma: no branch
786796 yield maybe_event
787797 elif isinstance (current_block , BetaMCPToolResultBlock ):
798+ call_part = builtin_tool_calls .get (current_block .tool_use_id )
788799 yield self ._parts_manager .handle_part (
789800 vendor_part_id = event .index ,
790- part = _map_mcp_server_result_block (current_block , self .provider_name ),
801+ part = _map_mcp_server_result_block (current_block , call_part , self .provider_name ),
791802 )
792803
793804 elif isinstance (event , BetaRawContentBlockDeltaEvent ):
@@ -908,21 +919,22 @@ def _map_code_execution_tool_result_block(
908919def _map_mcp_server_use_block (item : BetaMCPToolUseBlock , provider_name : str ) -> BuiltinToolCallPart :
909920 return BuiltinToolCallPart (
910921 provider_name = provider_name ,
911- tool_name = MCPServerTool .kind ,
922+ tool_name = ':' . join ([ MCPServerTool .kind , item . server_name ]) ,
912923 args = {
913924 'action' : 'call_tool' ,
914- 'server_id' : item .server_name ,
915925 'tool_name' : item .name ,
916926 'tool_args' : cast (dict [str , Any ], item .input ),
917927 },
918928 tool_call_id = item .id ,
919929 )
920930
921931
922- def _map_mcp_server_result_block (item : BetaMCPToolResultBlock , provider_name : str ) -> BuiltinToolReturnPart :
932+ def _map_mcp_server_result_block (
933+ item : BetaMCPToolResultBlock , call_part : BuiltinToolCallPart | None , provider_name : str
934+ ) -> BuiltinToolReturnPart :
923935 return BuiltinToolReturnPart (
924936 provider_name = provider_name ,
925- tool_name = MCPServerTool .kind ,
937+ tool_name = call_part . tool_name if call_part else MCPServerTool .kind ,
926938 content = item .model_dump (mode = 'json' , include = {'content' , 'is_error' }),
927939 tool_call_id = item .tool_use_id ,
928940 )
0 commit comments