Challenge 06 - Python - Build your first Agent with Microsoft Agent Framework and integrate with MCP remote server
< Previous Challenge - Home - Next Challenge >
In this challenge, you will build your first intelligent application using Microsoft Agent Framework, Microsoft's open-source engine for developing agentic AI applications. You'll create an interactive console application that demonstrates the core capabilities of AI agent orchestration and tool integration.
Microsoft Agent Framework is the evolution of both Semantic Kernel and Autogen, combining the strengths of each into a unified platform. It takes the best features from Semantic Kernel—such as prompt engineering, plugin integration, and middleware orchestration—and merges them with Autogen's advanced agent collaboration and planning capabilities. This results in a powerful, flexible framework for building, deploying, and managing AI agents at scale.
By the end of this challenge, you'll have hands-on experience with agent creation, tool integration, and connecting external services through the Model Context Protocol (MCP). Microsoft Agent Framework enables you to build sophisticated AI agents that can reason, plan, and execute complex tasks, with built-in support for multi-agent collaboration, persistent memory, and seamless integration with various AI models and external services.
Before diving into the implementation, let's understand the key concepts that make Microsoft Agent Framework powerful for AI development.
Microsoft Agent Framework provides a structured approach to AI agent development:
-
Agent Runtime: The central orchestration engine that manages AI services, tools, and agent execution
-
AI Services: Integration points with AI models (OpenAI, Azure OpenAI/Microsoft Foundry, etc.)
-
Tools: Reusable components that extend the agent's capabilities
-
Function Calling: The mechanism that allows AI models to decide and enable the execution of your code
-
Planning: Automatic orchestration of multiple tool calls to complete complex tasks
-
Agent State Management: Persistent memory and context across conversations
The Microsoft Agent Framework offers different components that can be used individually or combined.
-
Chat clients - provide abstractions for connecting to AI services from different providers under a common interface. Supported providers include Azure OpenAI, OpenAI, Anthropic, and more through the BaseChatClient abstraction.
-
Function tools - containers for custom functions that extend agent capabilities. Agents can automatically invoke functions with your own logic and integrate also with MCP servers and services.
-
Built-in tools - prebuilt capabilities including Code Interpreter for Python execution, File Search for document analysis, and Web Search for internet access.
-
Conversation management - structured message system with roles (USER, ASSISTANT, SYSTEM, TOOL) and AgentThread for persistent conversation context across interactions.
-
Workflow orchestration - supports sequential workflows, concurrent execution, handoff and Magentic patterns for complex multi-agent collaboration.
The Microsoft Agent Framework provides support for several types of agents to accommodate different use cases and requirements.
All agents are derived from a common base class, AIAgent, which provides a consistent interface for all agent types. This allows for building common, agent agnostic, higher level functionality such as multi-agent orchestrations.
| Agent Type | Description | Service Chat History storage supported | Custom Chat History storage supported |
|---|---|---|---|
| Azure AI Foundry Agent | An agent that uses the Azure AI Foundry Agents Service as its backend. | Yes | No |
| Azure OpenAI ChatCompletion | An agent that uses the Azure OpenAI ChatCompletion service. | No | Yes |
| Azure OpenAI Responses | An agent that uses the Azure OpenAI Responses service. | Yes | Yes |
| OpenAI ChatCompletion | An agent that uses the OpenAI ChatCompletion service. | No | Yes |
| OpenAI Responses | An agent that uses the OpenAI Responses service. | Yes | Yes |
| OpenAI Assistants | An agent that uses the OpenAI Assistants service. | Yes | No |
| Any other ChatClient | Any class inheriting from BaseChatClient, like AzureOpenAIResponsesClient and AzureOpenAIChatCompletionClient | Varies | Varies |
Microsoft Agent Framework can integrate with MCP servers to extend functionality:
- MCP Client Integration: Connect to remote MCP servers as additional capability sources
- Tool Registration: Convert MCP tools into Agent Framework tools
- Hybrid Architecture: Combine local tools with remote MCP services
- Scalable Design: Leverage both local processing and cloud-based services
This challenge will guide you through the process of developing your first intelligent app with Microsoft Agent Framework.
In just a few steps, you can build your first AI agent with Microsoft Agent Framework in Python.
requirements.txt:
azure-ai-agents>=1.2.0b5
azure-ai-projects>=2.0.0b3
azure-identity>=1.17.0
# opentelemetry-semantic-conventions-ai 0.4.14 removed SpanAttributes.LLM_SYSTEM,
# but agent-framework 1.0.0rc1 still references it. Downgrading to 0.4.13 fixes it.
opentelemetry-semantic-conventions-ai==0.4.13
agent-framework>=1.0.0rc1
mcp[cli]>=1.2.0
python-dotenv>=1.0.0
Starter code: A skeleton file is provided at
Resources/Challenge-06/python/agent_with_mcp.pywith the imports, chat loop, andTODOcomments already in place. Open it and fill in the missing pieces for each task below.
In this task, you will create a tool that allows the AI agent to display the current time. Since large language models (LLMs) are trained on past data and do not have real-time capabilities, they cannot provide the current time on their own.
By creating this tool, you will enable the AI agent to call a function that retrieves and displays the current time.
Add a method to retrieve the current time and register it as a tool in your agent.
from datetime import datetime, timezone
from agent_framework import tool
@tool(approval_mode="never_require")
def get_current_time_utc() -> str:
"""Returns the current system time in UTC."""
return f"The current time in UTC is {datetime.now(timezone.utc).isoformat()}"The @tool decorator automatically infers the tool name from the function name and the description from the docstring. You can also set approval_mode="always_require" in production if you want user confirmation before tool execution.
Note: For functions with parameters, simply use type annotations with
AnnotatedandFieldfor descriptions. The@tooldecorator handles schema generation automatically:from typing import Annotated from pydantic import Field from agent_framework import tool @tool(approval_mode="never_require") def get_time_for_timezone( timezone: Annotated[str, Field(description="The timezone name")] ) -> str: """Get time for a specific timezone.""" return f"Time in {timezone}: ..."Tip: You can also pass plain functions directly to
tools=[]without any decorator — the SDK will auto-wrap them. The@tooldecorator is useful when you want to configure options likeapproval_mode.
from agent_framework import Agent, tool
from agent_framework.azure import AzureOpenAIResponsesClient
from datetime import datetime, timezone
from dotenv import load_dotenv
import os
# Load environment variables from .env file
load_dotenv()
# Define the current time tool using the @tool decorator
@tool(approval_mode="never_require")
def get_current_time_utc() -> str:
"""Returns the current system time in UTC."""
return f"The current time in UTC is {datetime.now(timezone.utc).isoformat()}"
async def create_agent_with_tools():
"""Create an agent with the current time tool registered."""
# Create the chat client
# AZURE_OPENAI_DEPLOYMENT_NAME should be the name of your model deployment on Microsoft Foundry/Azure OpenAI
# i.e. "gpt-4o-mini"
client = AzureOpenAIResponsesClient(
endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
deployment_name=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"),
api_version=os.getenv("AZURE_OPENAI_API_VERSION", "latest")
)
# Create the agent explicitly and pass the @tool-decorated function directly.
# Alternatively, you can use the shorthand: client.as_agent(name=..., instructions=..., tools=...)
# which creates an Agent bound to that client in one call.
agent = Agent(
client=client,
name="TimeAgent",
instructions="When the user asks for the current time, use the get_current_time_utc tool to provide an accurate response. Do not engage in any other type of conversation.",
tools=[get_current_time_utc]
)
return agentTo interact with your agent, add a main function that handles the conversation loop:
async def main():
"""Main entry point for chatting with the agent."""
agent = await create_agent_with_tools()
print("Chat with TimeAgent (type 'exit' to quit)")
print("-" * 50)
while True:
user_input = input("\nYou: ").strip()
if user_input.lower() in ("exit", "quit"):
print("Bu-bye!")
break
if not user_input:
continue
# Stream response from agent token-by-token
# You can also use `result = await agent.run(user_input)`
# for "blocking", non-streaming call.
print("\nAgent: ", end="", flush=True)
async for update in agent.run(user_input, stream=True):
if update.text:
print(update.text, end="", flush=True)
print()
if __name__ == "__main__":
import asyncio
asyncio.run(main())Now, when you run your script and interact with your agent, you can ask for the current time and the agent will call the tool to provide an accurate response.
Example interaction:
You: What's the current time?
Agent: The current time in UTC is 2025-11-27T14:30:45.123456
In this task, you will integrate the Agent Service into your Microsoft Agent Framework application created in previous challenge. This will allow your agent to leverage the capabilities of the Agent Service and check for travel policy compliance.
To integrate with the Agent Service, you will need to set up the ProjectsClient and retrieve the agent using its ID.
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
import os
async def get_agent_from_service():
"""Retrieve an agent from Azure AI Foundry Agent Service."""
# Initialize the Azure AI Project client
endpoint = os.getenv("AZURE_AI_PROJECT_ENDPOINT")
project_client = AIProjectClient(
endpoint=endpoint,
credential=DefaultAzureCredential())
# Get the agents client
agents_client = project_client.agents
# Retrieve the agent by its ID
agent_id = os.getenv("AGENT_ID")
agent = agents_client.get_agent(agent_id)
return agent, agents_clientIn this task you will integrate the Weather MCP Remote server completed in the previous challenge and add it as tools in Microsoft Agent Framework.
from agent_framework import MCPStdioTool
async def integrate_mcp_tools_with_agent(agent, server_script_path: str):
"""Integrate MCP tools with the AI agent using MCPStdioTool."""
# Create MCP tool for the weather server
# MCPStdioTool automatically exposes all tools from the MCP server
mcp_tool = MCPStdioTool(
name="WeatherMCP",
command="python",
args=[server_script_path]
)
# Add the MCP tool to the agent
# The MCPStdioTool will handle all the tool discovery and invocation
if not hasattr(agent, 'tools') or agent.tools is None:
agent.tools = []
agent.tools.append(mcp_tool)
print(f"MCP tool integrated: {mcp_tool.name}")
print("All MCP server tools are now available to the agent.")
return agent- ✅ Ensure that your Python application is running and you are able to debug the application.
- ✅ Ensure that you are able to request the current time and receive an accurate response from the agent.
- ✅ Ensure that you are able to validate policy compliance functionality by ensuring the agent accurately answers travel policy questions.
- ✅ Set a breakpoint in one of the tool handlers and trigger it with a user prompt.
- ✅ Debug and inspect the agent's message history and tool call results.
- ✅ Integrate with the MCP Remote server and receive weather results.
- ✅ Demonstrate that the user can ask questions about weather data through the integrated MCP server.
- Learn Microsoft Agent Framework in 3 minutes!
- Introducing Microsoft Agent Framework: The Open-Source Engine for Agentic AI Apps
- Microsoft Agent Framework | MS Learn
- Microsoft Agent Framework | GitHub Repository
- Microsoft Agent Framework Python Samples | GitHub Repository
- Microsoft Agent Framework Python Documentation
- Microsoft Agent Framework MCP Integration Guide - Python