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

Hello. On this short course MCP: Build Rich-Context AI Apps with Anthropic i have the following error in L5 Creating MCP client.

when launching the mcp_chatbot.py given in L5 I have the following error message when asking to extract_info for 2 papers on a subject. Info for the first paper will be displayed but after I have the following error message: Error: Error code: 400 - {‘type’: ‘error’, ‘error’: {‘type’: ‘invalid_request_error’, ‘message’: ‘messages.2: tool_use ids were found without tool_result blocks immediately after: toolu_01Sj12tubWuB8JRf8A6n2FDs. Each tool_use block must have a corresponding tool_result block in the next message.’}, ‘request_id’: ‘req_011CYeeV2XLXSuJwx5GyhtSz’} can someone help me on this issue please?

2 Likes

Hello @Lauyao !

I’m just testing L5: Creating the MCP Agent and it is actually running as expected (and as shown by the instructor in the video)

Remember, when running the code cell for the new terminal, you need to add some commands (in the same terminal) such as cd L5/mcp_project, source .venv/bin/activate, etc before running the mcp server.

If the issue you encountered keeps persistent, could you please add a screenshot to help you figure out the issue?

Happy Learning!

Lesly

Hello @lesly.zerna
Here is a screenshot. thank you for your help.

I see you are running it locally! Therefore you need to first install all packages needed and seet up your APIs KEYs.

Checklist to set up locally:

  • you will find the requirements.txt file if you click Open from File, in the top menu. Once you have it:
    pip install -r requirements.txt

  • In your working folder, create .env with ANTHROPIC_API_KEY, and set with your own API KEY
  • Review the tool result handling to batch parallel results. Focus in this code line:
    messages.append({“role”: “user”, “content”: [tool_result_1]})
  • Ensure each tool_use_id in results matches the original

Let us know, how it goes!

Yes I have already done all what you asked.

I am running the code from L5/mcp_project/mcp_chatbot.py

You can see that I am connected to MCP server and have the list of tools

When i asked to extract info for one paper it works. The issue is when i ask to extract more than one paper.

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

Hi @lesly.zerna Yes I tried the code that you sent and it worked. Thanks a lot !

1 Like

Awesome!

Therefore, the shared fixed code will be useful if anyone wants to run locally!

Happy Learning!

Lesly