mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
Python: restructure: Python samples into progressive 01-05 layout (#3862)
* restructure: Python samples into progressive 01-05 layout - 01-get-started/: 6 numbered steps (hello agent → hosting) - 02-agents/: all agent concept samples (tools, middleware, providers, etc.) - 03-workflows/: ALL existing workflow samples preserved as-is - 04-hosting/: azure-functions, durabletask, a2a - 05-end-to-end/: demos, evaluation, hosted agents - Old files moved to _to_delete/ for review - Added AGENTS.md with structure documentation - autogen-migration/ and semantic-kernel-migration/ preserved at root * fix: switch to AzureOpenAI Foundry, fix CI failures - Switch all 01-get-started samples to AzureOpenAIResponsesClient with Azure AI Foundry project endpoint (AZURE_AI_PROJECT_ENDPOINT + AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME + AzureCliCredential) - Add _to_delete/ and 05-end-to-end/ to pyrightconfig.samples.json excludes - Fix test paths in packages/ that referenced old getting_started/ dirs: durabletask conftest + streaming test, azurefunctions conftest, devui conftest + capture_messages + openai_sdk_integration - Fix workflow_as_agent_human_in_the_loop.py import (sibling import) - Update hosting READMEs and tool comment paths - Replace root README.md with new structure overview - Update AGENTS.md to document Azure OpenAI Foundry as default provider * cleanup: remove _to_delete folder, copy resource files to active dirs All files in _to_delete/ were either: - Exact duplicates of files in the new structure (240 files) - Same file with only comment path updates (100 files) - One import-fix diff (workflow_as_agent_human_in_the_loop.py) - One superseded minimal_sample.py Resource files (sample.pdf, countries.json, employees.pdf, weather.json) copied to 02-agents/sample_assets/ and 02-agents/resources/ since active samples reference them. * fix: address PR review comments, centralize resources, remove root duplicates - Fix type annotation in 04_memory.py (string union -> proper types) - Fix old sample paths in observability files - Fix grammar/spelling in observability samples - Move sample_assets/ and resources/ to shared/ folder - Remove 8 duplicate observability files from 02-agents root - Update resource path references in multimodal_input and provider samples * fix: update broken links from old getting_started paths to new structure - Update relative paths in READMEs: getting_started/ → 01-get-started/, 02-agents/, 03-workflows/, 04-hosting/, 05-end-to-end/ - Fix absolute GitHub URLs in package READMEs - Fix broken link in ollama package README * fix: convert absolute GitHub URLs to relative paths for link checker Absolute URLs to python/samples/ on main branch 404 until PR merges. Converted to relative paths that linkspector can verify locally. * fix: update link for handoff sample moved to orchestrations/ * fix: update chatkit-integration README path from demos/ to 05-end-to-end/ * fix: update broken links in orchestrations README to match flat directory structure
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
# MCP (Model Context Protocol) Examples
|
||||
|
||||
This folder contains examples demonstrating how to work with MCP using Agent Framework.
|
||||
|
||||
## What is MCP?
|
||||
|
||||
The Model Context Protocol (MCP) is an open standard for connecting AI agents to data sources and tools. It enables secure, controlled access to local and remote resources through a standardized protocol.
|
||||
|
||||
## Examples
|
||||
|
||||
| Sample | File | Description |
|
||||
|--------|------|-------------|
|
||||
| **Agent as MCP Server** | [`agent_as_mcp_server.py`](agent_as_mcp_server.py) | Shows how to expose an Agent Framework agent as an MCP server that other AI applications can connect to |
|
||||
| **API Key Authentication** | [`mcp_api_key_auth.py`](mcp_api_key_auth.py) | Demonstrates API key authentication with MCP servers |
|
||||
| **GitHub Integration with PAT** | [`mcp_github_pat.py`](mcp_github_pat.py) | Demonstrates connecting to GitHub's MCP server using Personal Access Token (PAT) authentication |
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- `OPENAI_API_KEY` environment variable
|
||||
- `OPENAI_RESPONSES_MODEL_ID` environment variable
|
||||
|
||||
For `mcp_github_pat.py`:
|
||||
- `GITHUB_PAT` - Your GitHub Personal Access Token (create at https://github.com/settings/tokens)
|
||||
@@ -0,0 +1,75 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
from typing import Annotated, Any
|
||||
|
||||
import anyio
|
||||
from agent_framework import tool
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
|
||||
"""
|
||||
This sample demonstrates how to expose an Agent as an MCP server.
|
||||
|
||||
To run this sample, set up your MCP host (like Claude Desktop or VSCode GitHub Copilot Agents)
|
||||
with the following configuration:
|
||||
```json
|
||||
{
|
||||
"servers": {
|
||||
"agent-framework": {
|
||||
"command": "uv",
|
||||
"args": [
|
||||
"--directory=<path to project>/agent-framework/python/samples/getting_started/mcp",
|
||||
"run",
|
||||
"agent_as_mcp_server.py"
|
||||
],
|
||||
"env": {
|
||||
"OPENAI_API_KEY": "<OpenAI API key>",
|
||||
"OPENAI_RESPONSES_MODEL_ID": "<OpenAI Responses model ID>",
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
"""
|
||||
|
||||
|
||||
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_threads.py.
|
||||
@tool(approval_mode="never_require")
|
||||
def get_specials() -> Annotated[str, "Returns the specials from the menu."]:
|
||||
return """
|
||||
Special Soup: Clam Chowder
|
||||
Special Salad: Cobb Salad
|
||||
Special Drink: Chai Tea
|
||||
"""
|
||||
|
||||
|
||||
@tool(approval_mode="never_require")
|
||||
def get_item_price(
|
||||
menu_item: Annotated[str, "The name of the menu item."],
|
||||
) -> Annotated[str, "Returns the price of the menu item."]:
|
||||
return "$9.99"
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
# Define an agent
|
||||
# Agent's name and description provide better context for AI model
|
||||
agent = OpenAIResponsesClient().as_agent(
|
||||
name="RestaurantAgent",
|
||||
description="Answer questions about the menu.",
|
||||
tools=[get_specials, get_item_price],
|
||||
)
|
||||
|
||||
# Expose the agent as an MCP server
|
||||
server = agent.as_mcp_server()
|
||||
|
||||
# Run server
|
||||
from mcp.server.stdio import stdio_server
|
||||
|
||||
async def handle_stdin(stdin: Any | None = None, stdout: Any | None = None) -> None:
|
||||
async with stdio_server() as (read_stream, write_stream):
|
||||
await server.run(read_stream, write_stream, server.create_initialization_options())
|
||||
|
||||
await handle_stdin()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
anyio.run(run)
|
||||
@@ -0,0 +1,56 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import os
|
||||
|
||||
from agent_framework import Agent, MCPStreamableHTTPTool
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from httpx import AsyncClient
|
||||
|
||||
"""
|
||||
MCP Authentication Example
|
||||
|
||||
This example demonstrates how to authenticate with MCP servers using API key headers.
|
||||
|
||||
For more authentication examples including OAuth 2.0 flows, see:
|
||||
- https://github.com/modelcontextprotocol/python-sdk/tree/main/examples/clients/simple-auth-client
|
||||
- https://github.com/modelcontextprotocol/python-sdk/tree/main/examples/servers/simple-auth
|
||||
"""
|
||||
|
||||
|
||||
async def api_key_auth_example() -> None:
|
||||
"""Example of using API key authentication with MCP server."""
|
||||
# Configuration
|
||||
mcp_server_url = os.getenv("MCP_SERVER_URL", "your-mcp-server-url")
|
||||
api_key = os.getenv("MCP_API_KEY")
|
||||
|
||||
# Create authentication headers
|
||||
# Common patterns:
|
||||
# - Bearer token: "Authorization": f"Bearer {api_key}"
|
||||
# - API key header: "X-API-Key": api_key
|
||||
# - Custom header: "Authorization": f"ApiKey {api_key}"
|
||||
auth_headers = {
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
}
|
||||
|
||||
# Create HTTP client with authentication headers
|
||||
http_client = AsyncClient(headers=auth_headers)
|
||||
|
||||
# Create MCP tool with the configured HTTP client
|
||||
async with (
|
||||
MCPStreamableHTTPTool(
|
||||
name="MCP tool",
|
||||
description="MCP tool description",
|
||||
url=mcp_server_url,
|
||||
http_client=http_client, # Pass HTTP client with authentication headers
|
||||
) as mcp_tool,
|
||||
Agent(
|
||||
client=OpenAIResponsesClient(),
|
||||
name="Agent",
|
||||
instructions="You are a helpful assistant.",
|
||||
tools=mcp_tool,
|
||||
) as agent,
|
||||
):
|
||||
query = "What tools are available to you?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result.text}")
|
||||
@@ -0,0 +1,81 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from agent_framework import Agent
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
from dotenv import load_dotenv
|
||||
|
||||
"""
|
||||
MCP GitHub Integration with Personal Access Token (PAT)
|
||||
|
||||
This example demonstrates how to connect to GitHub's remote MCP server using a Personal Access
|
||||
Token (PAT) for authentication. The agent can use GitHub operations like searching repositories,
|
||||
reading files, creating issues, and more depending on how you scope your token.
|
||||
|
||||
Prerequisites:
|
||||
1. A GitHub Personal Access Token with appropriate scopes
|
||||
- Create one at: https://github.com/settings/tokens
|
||||
- For read-only operations, you can use more restrictive scopes
|
||||
2. Environment variables:
|
||||
- GITHUB_PAT: Your GitHub Personal Access Token (required)
|
||||
- OPENAI_API_KEY: Your OpenAI API key (required)
|
||||
- OPENAI_RESPONSES_MODEL_ID: Your OpenAI model ID (required)
|
||||
"""
|
||||
|
||||
|
||||
async def github_mcp_example() -> None:
|
||||
"""Example of using GitHub MCP server with PAT authentication."""
|
||||
# 1. Load environment variables from .env file if present
|
||||
load_dotenv()
|
||||
|
||||
# 2. Get configuration from environment
|
||||
github_pat = os.getenv("GITHUB_PAT")
|
||||
if not github_pat:
|
||||
raise ValueError(
|
||||
"GITHUB_PAT environment variable must be set. Create a token at https://github.com/settings/tokens"
|
||||
)
|
||||
|
||||
# 3. Create authentication headers with GitHub PAT
|
||||
auth_headers = {
|
||||
"Authorization": f"Bearer {github_pat}",
|
||||
}
|
||||
|
||||
# 4. Create agent with the GitHub MCP tool using instance method
|
||||
# The MCP tool manages the connection to the MCP server and makes its tools available
|
||||
# Set approval_mode="never_require" to allow the MCP tool to execute without approval
|
||||
client = OpenAIResponsesClient()
|
||||
github_mcp_tool = client.get_mcp_tool(
|
||||
server_label="GitHub",
|
||||
server_url="https://api.githubcopilot.com/mcp/",
|
||||
headers=auth_headers,
|
||||
require_approval="never",
|
||||
)
|
||||
|
||||
# 5. Create agent with the GitHub MCP tool
|
||||
async with Agent(
|
||||
client=client,
|
||||
name="GitHubAgent",
|
||||
instructions=(
|
||||
"You are a helpful assistant that can help users interact with GitHub. "
|
||||
"You can search for repositories, read file contents, check issues, and more. "
|
||||
"Always be clear about what operations you're performing."
|
||||
),
|
||||
tools=github_mcp_tool,
|
||||
) as agent:
|
||||
# Example 1: Get authenticated user information
|
||||
query1 = "What is my GitHub username and tell me about my account?"
|
||||
print(f"\nUser: {query1}")
|
||||
result1 = await agent.run(query1)
|
||||
print(f"Agent: {result1.text}")
|
||||
|
||||
# Example 2: List my repositories
|
||||
query2 = "List all the repositories I own on GitHub"
|
||||
print(f"\nUser: {query2}")
|
||||
result2 = await agent.run(query2)
|
||||
print(f"Agent: {result2.text}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(github_mcp_example())
|
||||
Reference in New Issue
Block a user