MCP:L5 fixes in mcp_chatbot.py to run it locally

Interesting! I see, the L5/mcp_project/mcp_chatbot.py and it looks like the problem is in the tool_use handling block. Try using this instead…

async def process_query(self, query):       
      messages = [{‘role’: ‘user’, ‘content’: query}]       
      response = self.anthropic.messages.create(                           
            max_tokens=2024,                       
            model = ‘claude-sonnet-4-6’,
            tools=self.available_tools,
            messages=messages
      )

process_query = True
while process_query:
    assistant_content = []
    tool_results = []  # collect ALL tool results first
    has_tool_use = False

    for content in response.content:
        if content.type == 'text':
            print(content.text)
            assistant_content.append(content)
        elif content.type == 'tool_use':
            has_tool_use = True
            assistant_content.append(content)
            tool_name = content.name
            tool_args = content.input
            tool_id = content.id

            print(f"Calling tool {tool_name} with args {tool_args}")
            result = await self.session.call_tool(tool_name, arguments=tool_args)

            tool_results.append({   # collect, don't send yet
                "type": "tool_result",
                "tool_use_id": tool_id,
                "content": result.content
            })

    if has_tool_use:
        # Now send assistant message + ALL tool results together
        messages.append({'role': 'assistant', 'content': assistant_content})
        messages.append({'role': 'user', 'content': tool_results})

        response = self.anthropic.messages.create(
            max_tokens=2024,
            model='claude-3-7-sonnet-20250219',
            tools=self.available_tools,
            messages=messages
        )
    else:
        process_query = False  # no tools called, we're done
...

Let us know if that helps!

1 Like