|
| 1 | +import time |
| 2 | +import json |
| 3 | + |
| 4 | +from azure.ai.agents import AgentsClient |
| 5 | +from azure.ai.agents.models import MessageTextContent, ListSortOrder |
| 6 | +from azure.ai.projects import AIProjectClient |
| 7 | +from azure.identity import DefaultAzureCredential |
| 8 | + |
| 9 | + |
| 10 | +project_client = AIProjectClient( |
| 11 | + endpoint=PROJECT_ENDPOINT, |
| 12 | + credential=DefaultAzureCredential() |
| 13 | +) |
| 14 | + |
| 15 | +with project_client: |
| 16 | + agent = project_client.agents.create_agent( |
| 17 | + model=MODEL_DEPLOYMENT_NAME, |
| 18 | + name="my-mcp-agent", |
| 19 | + instructions="You are a helpful assistant. Use the tools provided to answer the user's questions. Be sure to cite your sources.", |
| 20 | + tools= [ |
| 21 | + { |
| 22 | + "type": "mcp", |
| 23 | + "server_label": "<unique name for your MCP server>", |
| 24 | + "server_url": "<MCP server endpoint url>", |
| 25 | + "require_approval": "never" |
| 26 | + } |
| 27 | + ], |
| 28 | + tool_resources=None |
| 29 | + ) |
| 30 | + print(f"Created agent, agent ID: {agent.id}") |
| 31 | + |
| 32 | + thread = project_client.agents.threads.create() |
| 33 | + print(f"Created thread, thread ID: {thread.id}") |
| 34 | + |
| 35 | + message = project_client.agents.messages.create( |
| 36 | + thread_id=thread.id, role="user", content="<query related to your MCP server>", |
| 37 | + ) |
| 38 | + print(f"Created message, message ID: {message.id}") |
| 39 | + |
| 40 | + run = project_client.agents.runs.create(thread_id=thread.id, agent_id=agent.id) |
| 41 | + |
| 42 | + # Poll the run as long as run status is queued or in progress |
| 43 | + while run.status in ["queued", "in_progress", "requires_action"]: |
| 44 | + # Wait for a second |
| 45 | + time.sleep(1) |
| 46 | + run = project_client.agents.runs.get(thread_id=thread.id, run_id=run.id) |
| 47 | + print(f"Run status: {run.status}") |
| 48 | + |
| 49 | + if run.status == "failed": |
| 50 | + print(f"Run error: {run.last_error}") |
| 51 | + |
| 52 | + run_steps = project_client.agents.run_steps.list(thread_id=thread.id, run_id=run.id) |
| 53 | + for step in run_steps: |
| 54 | + print(f"Run step: {step.id}, status: {step.status}, type: {step.type}") |
| 55 | + if step.type == "tool_calls": |
| 56 | + print(f"Tool call details:") |
| 57 | + for tool_call in step.step_details.tool_calls: |
| 58 | + print(json.dumps(tool_call.as_dict(), indent=2)) |
| 59 | + |
| 60 | + messages = project_client.agents.messages.list(thread_id=thread.id, order=ListSortOrder.ASCENDING) |
| 61 | + for data_point in messages: |
| 62 | + last_message_content = data_point.content[-1] |
| 63 | + if isinstance(last_message_content, MessageTextContent): |
| 64 | + print(f"{data_point.role}: {last_message_content.text.value}") |
| 65 | + |
| 66 | + project_client.agents.delete_agent(agent.id) |
| 67 | + print(f"Deleted agent, agent ID: {agent.id}") |
0 commit comments