Python: Add BaseAgent implementation for GitHub Copilot SDK (#3404)

* Added GithubCopilotAgent

* Fixed errors

* Updated examples

* Updated naming and tests

* Resolved comments and more tests

* Updated tool handling

* Updated tool handling

* Small fixes

* Removed default permission handler

* Resolved comments

* Updated positional args

* Updated docstrings

* Small fixes and more examples

* Added example with MCP
This commit is contained in:
Dmytro Struk
2026-01-26 10:09:04 -08:00
committed by GitHub
Unverified
parent a3a9147e61
commit 407fb3025e
21 changed files with 2207 additions and 0 deletions
@@ -0,0 +1,37 @@
# GitHub Copilot Agent Examples
This directory contains examples demonstrating how to use the `GithubCopilotAgent` from the Microsoft Agent Framework.
> **Security Note**: These examples demonstrate various permission types (shell, read, write, url). Only enable permissions that are necessary for your use case. Each permission grants the agent additional capabilities that could affect your system.
## Prerequisites
1. **GitHub Copilot CLI**: Install and authenticate the Copilot CLI
2. **GitHub Copilot Subscription**: An active GitHub Copilot subscription
3. **Install the package**:
```bash
pip install agent-framework-github-copilot --pre
```
## Environment Variables
The following environment variables can be configured:
| Variable | Description | Default |
|----------|-------------|---------|
| `GITHUB_COPILOT_CLI_PATH` | Path to the Copilot CLI executable | `copilot` |
| `GITHUB_COPILOT_MODEL` | Model to use (e.g., "gpt-5", "claude-sonnet-4") | Server default |
| `GITHUB_COPILOT_TIMEOUT` | Request timeout in seconds | `60` |
| `GITHUB_COPILOT_LOG_LEVEL` | CLI log level | `info` |
## Examples
| File | Description |
|------|-------------|
| [`github_copilot_basic.py`](github_copilot_basic.py) | The simplest way to create an agent using `GithubCopilotAgent`. Demonstrates both streaming and non-streaming responses with function tools. |
| [`github_copilot_with_session.py`](github_copilot_with_session.py) | Shows session management with automatic creation, persistence via thread objects, and resuming sessions by ID. |
| [`github_copilot_with_shell.py`](github_copilot_with_shell.py) | Shows how to enable shell command execution permissions. Demonstrates running system commands like listing files and getting system information. |
| [`github_copilot_with_file_operations.py`](github_copilot_with_file_operations.py) | Shows how to enable file read and write permissions. Demonstrates reading file contents and creating new files. |
| [`github_copilot_with_url.py`](github_copilot_with_url.py) | Shows how to enable URL fetching permissions. Demonstrates fetching and processing web content. |
| [`github_copilot_with_mcp.py`](github_copilot_with_mcp.py) | Shows how to configure MCP (Model Context Protocol) servers, including local (stdio) and remote (HTTP) servers. |
| [`github_copilot_with_multiple_permissions.py`](github_copilot_with_multiple_permissions.py) | Shows how to combine multiple permission types for complex tasks that require shell, read, and write access. |
@@ -0,0 +1,75 @@
# Copyright (c) Microsoft. All rights reserved.
"""
GitHub Copilot Agent Basic Example
This sample demonstrates basic usage of GithubCopilotAgent.
Shows both streaming and non-streaming responses with function tools.
Environment variables (optional):
- GITHUB_COPILOT_CLI_PATH - Path to the Copilot CLI executable
- GITHUB_COPILOT_MODEL - Model to use (e.g., "gpt-5", "claude-sonnet-4")
- GITHUB_COPILOT_TIMEOUT - Request timeout in seconds
- GITHUB_COPILOT_LOG_LEVEL - CLI log level
"""
import asyncio
from random import randint
from typing import Annotated
from agent_framework.github import GithubCopilotAgent, GithubCopilotOptions
from pydantic import Field
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
"""Get the weather for a given location."""
conditions = ["sunny", "cloudy", "rainy", "stormy"]
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}C."
async def non_streaming_example() -> None:
"""Example of non-streaming response (get the complete result at once)."""
print("=== Non-streaming Response Example ===")
agent: GithubCopilotAgent[GithubCopilotOptions] = GithubCopilotAgent(
default_options={"instructions": "You are a helpful weather agent."},
tools=[get_weather],
)
async with agent:
query = "What's the weather like in Seattle?"
print(f"User: {query}")
result = await agent.run(query)
print(f"Agent: {result}\n")
async def streaming_example() -> None:
"""Example of streaming response (get results as they are generated)."""
print("=== Streaming Response Example ===")
agent: GithubCopilotAgent[GithubCopilotOptions] = GithubCopilotAgent(
default_options={"instructions": "You are a helpful weather agent."},
tools=[get_weather],
)
async with agent:
query = "What's the weather like in Tokyo?"
print(f"User: {query}")
print("Agent: ", end="", flush=True)
async for chunk in agent.run_stream(query):
if chunk.text:
print(chunk.text, end="", flush=True)
print("\n")
async def main() -> None:
print("=== Basic GitHub Copilot Agent Example ===")
await non_streaming_example()
await streaming_example()
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,53 @@
# Copyright (c) Microsoft. All rights reserved.
"""
GitHub Copilot Agent with File Operation Permissions
This sample demonstrates how to enable file read and write operations with GithubCopilotAgent.
By providing a permission handler that approves "read" and/or "write" requests, the agent can
read from and write to files on the filesystem.
SECURITY NOTE: Only enable file permissions when you trust the agent's actions.
- "read" allows the agent to read any accessible file
- "write" allows the agent to create or modify files
"""
import asyncio
from agent_framework.github import GithubCopilotAgent, GithubCopilotOptions
from copilot.types import PermissionRequest, PermissionRequestResult
def prompt_permission(request: PermissionRequest, context: dict[str, str]) -> PermissionRequestResult:
"""Permission handler that prompts the user for approval."""
kind = request.get("kind", "unknown")
print(f"\n[Permission Request: {kind}]")
if "path" in request:
print(f" Path: {request.get('path')}")
response = input("Approve? (y/n): ").strip().lower()
if response in ("y", "yes"):
return PermissionRequestResult(kind="approved")
return PermissionRequestResult(kind="denied-interactively-by-user")
async def main() -> None:
print("=== GitHub Copilot Agent with File Operation Permissions ===\n")
agent: GithubCopilotAgent[GithubCopilotOptions] = GithubCopilotAgent(
default_options={
"instructions": "You are a helpful assistant that can read and write files.",
"on_permission_request": prompt_permission,
},
)
async with agent:
query = "Read the contents of README.md and summarize it"
print(f"User: {query}")
result = await agent.run(query)
print(f"Agent: {result}\n")
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,75 @@
# Copyright (c) Microsoft. All rights reserved.
"""
GitHub Copilot Agent with MCP Servers
This sample demonstrates how to configure MCP (Model Context Protocol) servers
with GithubCopilotAgent. It shows both local (stdio) and remote (HTTP) server
configurations, giving the agent access to external tools and data sources.
SECURITY NOTE: MCP servers can expose powerful capabilities. Only configure
servers you trust. The permission handler below prompts the user for approval
of MCP-related actions.
"""
import asyncio
from agent_framework.github import GithubCopilotAgent, GithubCopilotOptions
from copilot.types import MCPServerConfig, PermissionRequest, PermissionRequestResult
def prompt_permission(request: PermissionRequest, context: dict[str, str]) -> PermissionRequestResult:
"""Permission handler that prompts the user for approval."""
kind = request.get("kind", "unknown")
print(f"\n[Permission Request: {kind}]")
response = input("Approve? (y/n): ").strip().lower()
if response in ("y", "yes"):
return PermissionRequestResult(kind="approved")
return PermissionRequestResult(kind="denied-interactively-by-user")
async def main() -> None:
print("=== GitHub Copilot Agent with MCP Servers ===\n")
# Configure both local and remote MCP servers
mcp_servers: dict[str, MCPServerConfig] = {
# Local stdio server: provides filesystem access tools
"filesystem": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "."],
"tools": ["*"],
},
# Remote HTTP server: Microsoft Learn documentation
"microsoft-learn": {
"type": "http",
"url": "https://learn.microsoft.com/api/mcp",
"tools": ["*"],
},
}
agent: GithubCopilotAgent[GithubCopilotOptions] = GithubCopilotAgent(
default_options={
"instructions": "You are a helpful assistant with access to the local filesystem and Microsoft Learn.",
"on_permission_request": prompt_permission,
"mcp_servers": mcp_servers,
},
)
async with agent:
# Query that exercises the local filesystem MCP server
query1 = "List the files in the current directory"
print(f"User: {query1}")
result1 = await agent.run(query1)
print(f"Agent: {result1}\n")
# Query that exercises the remote Microsoft Learn MCP server
query2 = "Search Microsoft Learn for 'Azure Functions Python' and summarize the top result"
print(f"User: {query2}")
result2 = await agent.run(query2)
print(f"Agent: {result2}\n")
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,61 @@
# Copyright (c) Microsoft. All rights reserved.
"""
GitHub Copilot Agent with Multiple Permissions
This sample demonstrates how to enable multiple permission types with GithubCopilotAgent.
By combining different permission kinds in the handler, the agent can perform complex tasks
that require multiple capabilities.
Available permission kinds:
- "shell": Execute shell commands
- "read": Read files from the filesystem
- "write": Write files to the filesystem
- "mcp": Use MCP (Model Context Protocol) servers
- "url": Fetch content from URLs
SECURITY NOTE: Only enable permissions that are necessary for your use case.
More permissions mean more potential for unintended actions.
"""
import asyncio
from agent_framework.github import GithubCopilotAgent, GithubCopilotOptions
from copilot.types import PermissionRequest, PermissionRequestResult
def prompt_permission(request: PermissionRequest, context: dict[str, str]) -> PermissionRequestResult:
"""Permission handler that prompts the user for approval."""
kind = request.get("kind", "unknown")
print(f"\n[Permission Request: {kind}]")
if "command" in request:
print(f" Command: {request.get('command')}")
if "path" in request:
print(f" Path: {request.get('path')}")
response = input("Approve? (y/n): ").strip().lower()
if response in ("y", "yes"):
return PermissionRequestResult(kind="approved")
return PermissionRequestResult(kind="denied-interactively-by-user")
async def main() -> None:
print("=== GitHub Copilot Agent with Multiple Permissions ===\n")
agent: GithubCopilotAgent[GithubCopilotOptions] = GithubCopilotAgent(
default_options={
"instructions": "You are a helpful development assistant that can read, write files and run commands.",
"on_permission_request": prompt_permission,
},
)
async with agent:
query = "List the first 3 Python files, then read the first one and create a summary in summary.txt"
print(f"User: {query}")
result = await agent.run(query)
print(f"Agent: {result}\n")
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,137 @@
# Copyright (c) Microsoft. All rights reserved.
"""
GitHub Copilot Agent with Session Management
This sample demonstrates session management with GithubCopilotAgent, showing
persistent conversation capabilities. Sessions are automatically persisted
server-side by the Copilot CLI.
"""
import asyncio
from random import randint
from typing import Annotated
from agent_framework.github import GithubCopilotAgent, GithubCopilotOptions
from pydantic import Field
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
"""Get the weather for a given location."""
conditions = ["sunny", "cloudy", "rainy", "stormy"]
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
async def example_with_automatic_session_creation() -> None:
"""Each run() without thread creates a new session."""
print("=== Automatic Session Creation Example ===")
agent: GithubCopilotAgent[GithubCopilotOptions] = GithubCopilotAgent(
default_options={"instructions": "You are a helpful weather agent."},
tools=[get_weather],
)
async with agent:
# First query - creates a new session
query1 = "What's the weather like in Seattle?"
print(f"User: {query1}")
result1 = await agent.run(query1)
print(f"Agent: {result1}")
# Second query - without thread, creates another new session
query2 = "What was the last city I asked about?"
print(f"\nUser: {query2}")
result2 = await agent.run(query2)
print(f"Agent: {result2}")
print("Note: Each call creates a separate session, so the agent doesn't remember previous context.\n")
async def example_with_session_persistence() -> None:
"""Reuse session via thread object for multi-turn conversations."""
print("=== Session Persistence Example ===")
agent: GithubCopilotAgent[GithubCopilotOptions] = GithubCopilotAgent(
default_options={"instructions": "You are a helpful weather agent."},
tools=[get_weather],
)
async with agent:
# Create a thread to maintain conversation context
thread = agent.get_new_thread()
# First query
query1 = "What's the weather like in Tokyo?"
print(f"User: {query1}")
result1 = await agent.run(query1, thread=thread)
print(f"Agent: {result1}")
# Second query - using same thread maintains context
query2 = "How about London?"
print(f"\nUser: {query2}")
result2 = await agent.run(query2, thread=thread)
print(f"Agent: {result2}")
# Third query - agent should remember both previous cities
query3 = "Which of the cities I asked about has better weather?"
print(f"\nUser: {query3}")
result3 = await agent.run(query3, thread=thread)
print(f"Agent: {result3}")
print("Note: The agent remembers context from previous messages in the same session.\n")
async def example_with_existing_session_id() -> None:
"""Resume session in new agent instance using service_thread_id."""
print("=== Existing Session ID Example ===")
existing_session_id = None
# First agent instance - start a conversation
agent1: GithubCopilotAgent[GithubCopilotOptions] = GithubCopilotAgent(
default_options={"instructions": "You are a helpful weather agent."},
tools=[get_weather],
)
async with agent1:
thread = agent1.get_new_thread()
query1 = "What's the weather in Paris?"
print(f"User: {query1}")
result1 = await agent1.run(query1, thread=thread)
print(f"Agent: {result1}")
# Capture the session ID for later use
existing_session_id = thread.service_thread_id
print(f"Session ID: {existing_session_id}")
if existing_session_id:
print("\n--- Continuing with the same session ID in a new agent instance ---")
# Second agent instance - resume the conversation
agent2: GithubCopilotAgent[GithubCopilotOptions] = GithubCopilotAgent(
default_options={"instructions": "You are a helpful weather agent."},
tools=[get_weather],
)
async with agent2:
# Create thread with existing session ID
thread = agent2.get_new_thread(service_thread_id=existing_session_id)
query2 = "What was the last city I asked about?"
print(f"User: {query2}")
result2 = await agent2.run(query2, thread=thread)
print(f"Agent: {result2}")
print("Note: The agent continues the conversation using the session ID.\n")
async def main() -> None:
print("=== GitHub Copilot Agent Session Management Examples ===\n")
await example_with_automatic_session_creation()
await example_with_session_persistence()
await example_with_existing_session_id()
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,52 @@
# Copyright (c) Microsoft. All rights reserved.
"""
GitHub Copilot Agent with Shell Permissions
This sample demonstrates how to enable shell command execution with GithubCopilotAgent.
By providing a permission handler that approves "shell" requests, the agent can execute
shell commands to perform tasks like listing files, running scripts, or executing system commands.
SECURITY NOTE: Only enable shell permissions when you trust the agent's actions.
Shell commands have full access to your system within the permissions of the running process.
"""
import asyncio
from agent_framework.github import GithubCopilotAgent, GithubCopilotOptions
from copilot.types import PermissionRequest, PermissionRequestResult
def prompt_permission(request: PermissionRequest, context: dict[str, str]) -> PermissionRequestResult:
"""Permission handler that prompts the user for approval."""
kind = request.get("kind", "unknown")
print(f"\n[Permission Request: {kind}]")
if "command" in request:
print(f" Command: {request.get('command')}")
response = input("Approve? (y/n): ").strip().lower()
if response in ("y", "yes"):
return PermissionRequestResult(kind="approved")
return PermissionRequestResult(kind="denied-interactively-by-user")
async def main() -> None:
print("=== GitHub Copilot Agent with Shell Permissions ===\n")
agent: GithubCopilotAgent[GithubCopilotOptions] = GithubCopilotAgent(
default_options={
"instructions": "You are a helpful assistant that can execute shell commands.",
"on_permission_request": prompt_permission,
},
)
async with agent:
query = "List the first 3 Python files in the current directory"
print(f"User: {query}")
result = await agent.run(query)
print(f"Agent: {result}\n")
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,52 @@
# Copyright (c) Microsoft. All rights reserved.
"""
GitHub Copilot Agent with URL Fetching
This sample demonstrates how to enable URL fetching with GithubCopilotAgent.
By providing a permission handler that approves "url" requests, the agent can
fetch and process content from web URLs.
SECURITY NOTE: Only enable URL permissions when you trust the agent's actions.
URL fetching allows the agent to access any URL accessible from your network.
"""
import asyncio
from agent_framework.github import GithubCopilotAgent, GithubCopilotOptions
from copilot.types import PermissionRequest, PermissionRequestResult
def prompt_permission(request: PermissionRequest, context: dict[str, str]) -> PermissionRequestResult:
"""Permission handler that prompts the user for approval."""
kind = request.get("kind", "unknown")
print(f"\n[Permission Request: {kind}]")
if "url" in request:
print(f" URL: {request.get('url')}")
response = input("Approve? (y/n): ").strip().lower()
if response in ("y", "yes"):
return PermissionRequestResult(kind="approved")
return PermissionRequestResult(kind="denied-interactively-by-user")
async def main() -> None:
print("=== GitHub Copilot Agent with URL Fetching ===\n")
agent: GithubCopilotAgent[GithubCopilotOptions] = GithubCopilotAgent(
default_options={
"instructions": "You are a helpful assistant that can fetch and summarize web content.",
"on_permission_request": prompt_permission,
},
)
async with agent:
query = "Fetch https://learn.microsoft.com/agent-framework/tutorials/quick-start and summarize its contents"
print(f"User: {query}")
result = await agent.run(query)
print(f"Agent: {result}\n")
if __name__ == "__main__":
asyncio.run(main())