azure-sdk-for-python icon indicating copy to clipboard operation
azure-sdk-for-python copied to clipboard

Calling MCP server tool not working for Azure AI Agent

Open ITWApple opened this issue 1 year ago • 16 comments

I have the issue where Azure AI Agent when configured with a MCP server, tool call to MCP server fails. Agent can successfully retrieve all the available tools. It appears that the MCP session is terminated by the Agent- using a DELETE call- before calling a tool, causing the MCP server to respond with 404 error. l. I ran wireshark to analyze the packets and I see DELETE being called before calling the tool. I have tested the same MCP server using FastMCP client and MS Copilot Studio Agent- and in both cases my MCP server works fine ; Azure AI Agent however fails.

Python: 3.13.5 Name: azure-ai-agents Version: 1.2.0b3

Below is my code that I am using for creating a thread and message.

`import os, time #import gradio as gr from dotenv import load_dotenv import asyncio

Azure AI Agent SDK

from azure.ai.projects.aio import AIProjectClient from azure.identity.aio import DefaultAzureCredential from azure.ai.agents.models import ( ListSortOrder, McpTool, RequiredMcpToolCall, RunStepActivityDetails, SubmitToolApprovalAction, ToolApproval, )

Load environment variables

load_dotenv()

Azure Agent + OpenAI configuration

endpoint = os.getenv("AZ_PROJ_ENDPNT") # Azure project endpoint (Agent Service) api_key = os.getenv("AZ_OPENAPI") # Your Azure OpenAI / Agent key deployment = os.getenv("AZ_MODEL") # Model deployment name mcp_server_url = os.getenv("MCP_SERVER_URL") mcp_server_label = os.getenv("MCP_SERVER_LABEL") agent_id = os.getenv("AZ_AGENT_ID")

async def main() -> None:

project_client = AIProjectClient(
    endpoint=endpoint,
    credential=DefaultAzureCredential(),
)

# Initialize agent MCP tool
mcp_tool = McpTool(
    server_label=mcp_server_label,
    server_url=mcp_server_url,
    #allowed_tools=[],  # Optional: specify allowed tools
)
mcp_tool.set_approval_mode("never")  # Uncomment to disable approval requirement
async with project_client:
    agents_client = project_client.agents
    agent = await agents_client.get_agent(agent_id=agent_id)
    
    # print(f"Created agent, ID: {agent.id}")
    # print(f"MCP Server: {mcp_tool.server_label} at {mcp_tool.server_url}")

    #Create thread for communication
    thread = await agents_client.threads.create()
    print(f"Created thread, ID: {thread.id}")

    # Create message to thread
    message = await agents_client.messages.create(
        thread_id=thread.id,
        role="user",
        content="Please list all the devices under company Example",
    )
    print(f"Created message, ID: {message.id}")

    #Create and process agent run in thread with MCP tools

    run = await agents_client.runs.create(thread_id=thread.id, agent_id=agent.id, tool_resources=mcp_tool.resources)
    print(f"Created run, ID: {run.id}")

    while run.status in ["queued", "in_progress", "requires_action"]:
        await asyncio.sleep(1)
        run = await agents_client.runs.get(thread_id=thread.id, run_id=run.id)

        if run.status == "requires_action" and isinstance(run.required_action, SubmitToolApprovalAction):
            tool_calls = run.required_action.submit_tool_approval.tool_calls
            if not tool_calls:
                print("No tool calls provided - cancelling run")
                await agents_client.runs.cancel(thread_id=thread.id, run_id=run.id)
                break

            tool_approvals = []
            for tool_call in tool_calls:
                if isinstance(tool_call, RequiredMcpToolCall):
                    try:
                        print(f"Approving tool call: {tool_call}")
                        tool_approvals.append(
                            ToolApproval(
                                tool_call_id=tool_call.id,
                                approve=True,
                                headers=mcp_tool.headers,
                            )
                        )
                    except Exception as e:
                        print(f"Error approving tool_call {tool_call.id}: {e}")

            print(f"tool_approvals: {tool_approvals}")
            if tool_approvals:
                await agents_client.runs.submit_tool_outputs(
                    thread_id=thread.id, run_id=run.id, tool_approvals=tool_approvals
                )

        print(f"Current run status: {run.status}")

    print(f"Run completed with status: {run.status}")
    if run.status == "failed":
        print(f"Run failed: {run.last_error}")

    # Display run steps and tool calls
    run_steps = agents_client.run_steps.list(thread_id=thread.id, run_id=run.id)

    # Loop through each step
    async for step in run_steps:
        print(f"Step {step['id']} status: {step['status']}")

        # Check if there are tool calls in the step details
        step_details = step.get("step_details", {})
        tool_calls = step_details.get("tool_calls", [])

        if tool_calls:
            print("  MCP Tool calls:")
            for call in tool_calls:
                print(f"    Tool Call ID: {call.get('id')}")
                print(f"    Type: {call.get('type')}")

        if isinstance(step_details, RunStepActivityDetails):
            for activity in step_details.activities:
                for function_name, function_definition in activity.tools.items():
                    print(
                        f'  The function {function_name} with description "{function_definition.description}" will be called.:'
                    )
                    if len(function_definition.parameters) > 0:
                        print("  Function parameters:")
                        for argument, func_argument in function_definition.parameters.properties.items():
                            print(f"      {argument}")
                            print(f"      Type: {func_argument.type}")
                            print(f"      Description: {func_argument.description}")
                    else:
                        print("This function has no parameters")

        print()  # add an extra newline between steps

    # Fetch and log all messages
    messages = agents_client.messages.list(thread_id=thread.id, order=ListSortOrder.ASCENDING)
    print("\nConversation:")
    print("-" * 50)
    async for msg in messages:
        if msg.text_messages:
            last_text = msg.text_messages[-1]
            print(f"{msg.role.upper()}: {last_text.text.value}")
            print("-" * 50)

if name == "main": asyncio.run(main())`

Screenshots:

  1. DELETE:
Image
  1. Tool Call (after DELETE)
Image
  1. Failed 404:
Image

Notes: My MCP server is accessible online but access is restricted only from MS published IP list. Therefore not accessible to general public to test with. I have tested the tool calling with RestAPI and its the same result.

creating a new issue since I did not receive a response when posted on another issue.: Originally posted by @ITWApple in #42428

ITWApple avatar Aug 26 '25 17:08 ITWApple

Thanks for the feedback! We are routing this to the appropriate team for follow-up. cc @dargilco @glharper @howieleung @jhakulin @nick863 @trangevi.

github-actions[bot] avatar Aug 26 '25 17:08 github-actions[bot]

@apryiomka FYI

glharper avatar Aug 26 '25 19:08 glharper

Can confirm i have experienced the same. I am finding that discovery runs against my MCP, consisting of a POST to init and then a bunch of requests to list tools, followed by a DELETE request. However, then the tool runs and and its calling the MCP again with the sessionId that its just deleted - which no longer exists on my MCP resulting in an error

billycrid avatar Aug 27 '25 14:08 billycrid

@glharper , Sorry I dont mean to rush your team, but I wanted to follow up on this issue and if you need any additional information. Thank you!

ITWApple avatar Aug 28 '25 14:08 ITWApple

I am having the same issue

pragati-gupta-mu avatar Aug 29 '25 12:08 pragati-gupta-mu

I am having the same issue

zsakss avatar Aug 30 '25 13:08 zsakss

Same here. Initialize works, the agents gets the tool listings fine but the actual call doesn't work. Seems like the same bug, it issues DELETE after initialize.

Oh and to add: these MCP servers in question work with Copilot Studio, MCP Inspector, VS Code copilot and other custom tools so it seems to be Azure AI Foundry issue.

ss-solteq avatar Sep 02 '25 04:09 ss-solteq

I confirm. I made a test on a personal mcp server, I intercepted the DELETE requests and canceled the execution and everything worked fine. The agent executed the tools successfully.

zsakss avatar Sep 02 '25 09:09 zsakss

@yasufs Could you take a look and update with what you find?

glharper avatar Sep 02 '25 16:09 glharper

I found a bug in the MCP client code that causes it to always DELETE the session after the tools/list call, then go on to use the same session ID when invoking tools. It would be relatively easy to avoid issuing the DELETE call. Would that solve the problem for you @ITWApple and others facing the same issue?

yasufs avatar Sep 02 '25 21:09 yasufs

I found a bug in the MCP client code that causes it to always DELETE the session after the tools/list call, then go on to use the same session ID when invoking tools. It would be relatively easy to avoid issuing the DELETE call. Would that solve the problem for you @ITWApple and others facing the same issue?

@yasufs I believe that would work. Thank you for finding this bug and reaching out!

ITWApple avatar Sep 03 '25 13:09 ITWApple

Hi @yasufs , just wondering if you had a rough ETA by any chance, for the fix. Thanks in advance

ITWApple avatar Sep 08 '25 14:09 ITWApple

Hi @ITWApple , I believe the fix has been rolled out now. Can you try it and see if it works?

yasufs avatar Sep 08 '25 18:09 yasufs

@yasufs I just tested and it works now!! Thank you so much!

ITWApple avatar Sep 08 '25 19:09 ITWApple

Hi @ITWApple. Thank you for opening this issue and giving us the opportunity to assist. We believe that this has been addressed. If you feel that further discussion is needed, please add a comment with the text "/unresolve" to remove the "issue-addressed" label and continue the conversation.

github-actions[bot] avatar Sep 16 '25 13:09 github-actions[bot]

Hi @ITWApple, since you haven’t asked that we /unresolve the issue, we’ll close this out. If you believe further discussion is needed, please add a comment /unresolve to reopen the issue.

github-actions[bot] avatar Sep 23 '25 16:09 github-actions[bot]