Copilot Python SDK
Python SDK for programmatic control of GitHub Copilot CLI via JSON-RPC.
Prerequisites
To use the SDK, you'll need:
Installation
pip install microsoft-copilot-sdk
To include OpenTelemetry support:
pip install "microsoft-copilot-sdk[telemetry]"
Runtime
Published wheels pin the runtime version; after installing, pre-download the
matching native bundle:
python -m copilot download-runtime --in-process
This downloads the platform release package, verifies it against the release's
SHA256SUMS.txt, and directly stages copilot-runtime, its adjacent runtime.node,
and the filtered hostless runtime assets locally without retaining the downloaded
archive. If you skip this step, the SDK performs the same staging automatically on
first use.
The --in-process option also creates a copilot compatibility entrypoint from copilot-runtime
inside the complete materialized bundle. Its adjacent runtime.node can then be
used for in-process hosting. That canonical staged library is reused, so this does
not download a second runtime artifact.
| Platform |
Cache path |
| Linux |
~/.cache/copilot-sdk/cli/<version>/prebuilds/<platform>/ |
| macOS |
~/Library/Caches/copilot-sdk/cli/<version>/prebuilds/<platform>/ |
| Windows |
%LOCALAPPDATA%\copilot-sdk\cli\<version>\prebuilds\<platform>\ |
Environment variables
| Variable |
Description |
COPILOT_CLI_PATH |
Use this specific binary instead of downloading |
COPILOT_CLI_EXTRACT_DIR |
Override the version-specific cache directory |
COPILOT_SKIP_CLI_DOWNLOAD |
Set to 1 to disable auto-download |
COPILOT_CLI_DOWNLOAD_BASE_URL |
Override the GitHub Releases download URL used for the runtime package and checksums |
Run the Sample
Try the interactive chat sample (from the repo root):
cd python/samples
python chat.py
Quick Start
For experimental in-process AHP hosting, use client.start_ahp_host(AhpHostOptions(...)).
Set authentication=AhpHostAuthentication(mode) with "github", "none", or
"custom" in every client mode. Custom policies require a stable nonempty require_identity
and async authenticate(request): return AhpAuthenticationResult(identity, expires_at)
with that exact identity and a future RFC3339 expiration, or None to reject.
The request contains the decrypted admission token and an asyncio.Event
(cancellation_event) set when validation ends. Exceptions reject access.
Import these handwritten types from copilot. Admission tokens never configure
GitHub authentication or inference. Factories receive trusted request.authentication
beside request.config, never inside it. Select local_server=HostLocalServerOptions(),
github_environment=HostGitHubEnvironmentOptions(name="My app", compute_id="stable-installation-id")
for Mission Control/WPS (GitHub authentication only), or both; import transports
from copilot.rpc. At least one transport is required. GitHub-only hosts have no
url or token; host.environment_id identifies their environment.
await host.list_sessions() lists live and dormant sessions. Top-level compute_id
reuses the durable catalog across transports and must match github_environment.compute_id.
Omitted local identities persist. Dormant application publications need a resume callback.
See runtime-supervised AHP hosting for creation
and resume callbacks, resident-session publication, ownership, and shared-snapshot E2Es.
import asyncio
from copilot import CopilotClient
from copilot.session_events import (
AssistantMessageData,
SessionAutopilotStoppedData,
SessionIdleData,
SessionMode,
)
from copilot.session import PermissionHandler
async def main():
# Client automatically starts on enter and cleans up on exit
async with CopilotClient(mode="coding-agent") as client:
# Create a session with automatic cleanup
async with await client.create_session(
model="gpt-5", permissions={"on_request": PermissionHandler.approve_all}
) as session:
# Wait for non-Autopilot idle or this request's Autopilot stop
request_id = None
pending = []
done = asyncio.Event()
def observe(event):
match event.data:
case AssistantMessageData() as data:
print(data.content)
case SessionIdleData() as data if data.mode != SessionMode.AUTOPILOT:
done.set()
case SessionAutopilotStoppedData() as data if (
request_id and data.request_id == request_id
):
done.set()
def on_event(event):
if event.agent_id:
return
if request_id is None and isinstance(
event.data, (SessionIdleData, SessionAutopilotStoppedData)
):
pending.append(event)
else:
observe(event)
session.on(on_event)
request_id = await session.send("What is 2+2?")
for event in pending:
observe(event)
pending.clear()
await done.wait()
asyncio.run(main())
Message source
Use AgentMessageSource(agent_id) for messages from an identified agent.
Use source="system" for application-internal context, not as a substitute for
agent provenance. Both send and send_and_wait accept the optional
MessageSource type:
from copilot import AgentMessageSource, MessageSource
source: MessageSource = AgentMessageSource("reviewer")
await session.send("Review complete", source=source)
await session.send_and_wait("Review findings attached", source=source)
await session.send("Workspace context updated", source="system")
AgentMessageSource is immutable and requires a string ID. The SDK sends the ID
unchanged after the agent- prefix, so "reviewer" becomes "agent-reviewer".
It does not trim whitespace, change case, or remove an existing prefix.
Use AutomationMessageSource(automation_id) for a turn sent on behalf of an
automation the user configured, such as a recurring check-in; it becomes
automation-<id>. An automation turn defines the session's task like a user message but carries no human authority; see Message provenance.
Leave source unset (or None) for ordinary human sends so the field stays omitted.
Use "user" when you need to set it explicitly. Source is independent of delivery
mode and does not replace the session's system_message configuration, set billing
flags, or use the notification API. send_and_wait can return None when the
request completes without an assistant message, at non-Autopilot idle or its
matching Autopilot stop; errors still propagate.
Sub-agent events remain visible to listeners but do not complete the wait
or supply its reply.
Manual Resource Management
If you need more control over the lifecycle, you can call start(), stop(), and disconnect() manually:
For an SDK-owned stdio runtime, stop() and async context-manager exit request
shutdown, close stdin, and wait up to 10 seconds for the process to finish host
cleanup, including telemetry flushing. A process that does not exit is terminated,
then killed if necessary, with bounded waits. force_stop() skips graceful cleanup;
externally managed runtimes are not shut down.
It disconnects retained sessions locally, releases their registered callbacks, and
fails pending send_and_wait() calls without waiting for idle or their response timeout.
Disconnected sessions reject new event subscriptions.
import asyncio
from copilot import CopilotClient
from copilot.session_events import (
AssistantMessageData,
SessionAutopilotStoppedData,
SessionIdleData,
SessionMode,
)
from copilot.session import PermissionHandler
async def main():
client = CopilotClient(mode="coding-agent")
await client.start()
# approve_all is only valid when managed settings are disabled.
session = await client.create_session(
model="gpt-5", permissions={"on_request": PermissionHandler.approve_all}
)
request_id = None
pending = []
done = asyncio.Event()
def observe(event):
match event.data:
case AssistantMessageData() as data:
print(data.content)
case SessionIdleData() as data if data.mode != SessionMode.AUTOPILOT:
done.set()
case SessionAutopilotStoppedData() as data if (
request_id and data.request_id == request_id
):
done.set()
def on_event(event):
if event.agent_id:
return
if request_id is None and isinstance(
event.data, (SessionIdleData, SessionAutopilotStoppedData)
):
pending.append(event)
else:
observe(event)
session.on(on_event)
request_id = await session.send("What is 2+2?")
for event in pending:
observe(event)
pending.clear()
await done.wait()
# Clean up manually
await session.disconnect()
await client.stop()
asyncio.run(main())
Features
- ✅ Full JSON-RPC protocol support
- ✅ stdio, TCP, and in-process (FFI) transports
- ✅ Real-time streaming events
- ✅ Session history with
get_events()
- ✅ Type hints throughout
- ✅ Async/await native
- ✅ Async context manager support for automatic resource cleanup
Skill providers (experimental)
Skill providers let a session serve skills from SDK-owned storage instead of
SKILL.md files on disk. Implement SkillProvider, return generated
SkillProviderDescriptor values from list_skills(), and return the skill
markdown from read_skill(name). Both methods can be sync or async; keep sync
providers fast because they run on the event loop.
import asyncio
from copilot import CopilotClient, RuntimeConnection, SkillProvider, SkillProviderDescriptor
class MemorySkills(SkillProvider):
def list_skills(self):
return [
SkillProviderDescriptor(
name="release-notes",
description="Draft release notes from recent changes",
)
]
async def read_skill(self, name: str) -> str | None:
if name != "release-notes":
return None
return "Draft concise release notes with highlights and migration notes."
async def main():
async with CopilotClient(
mode="empty", runtime=RuntimeConnection.for_default(base_directory="./.copilot-empty")
) as client:
async with await client.create_session(
tools={"available_tools": []}, skills={"enabled": True, "provider": MemorySkills()}
) as session:
await session.send("Use /release-notes for this change set")
asyncio.run(main())
In "empty" mode, set skills={"enabled": True}; otherwise the provider is bound but
dormant. Providers are ephemeral and are not persisted, so pass skills={"provider": ...}
again to resume_session(). Cloud sessions do not support skill providers.
Providers must be safe for concurrent calls because the runtime may list or read
skills from multiple agent paths at the same time. When the runtime cancels a
call, for example after its 30-second limit or when the session disconnects, an
async provider's task is cancelled and receives asyncio.CancelledError. The
same happens when the connection closes or the client is force-stopped.
Supporting files (experimental)
To give a provider skill supporting files, such as scripts, references,
templates, and assets, set its descriptor's directory to the absolute path of
the folder that holds them:
from copilot import SkillProviderDescriptor
SkillProviderDescriptor(
name="release-notes",
description="Writes release notes in the team's format.",
directory="/srv/skills/release-notes",
)
When the skill is activated, the runtime lists the folder's files for the model.
See Supporting files for details.
API Reference
CopilotClient
from copilot import CopilotClient
from copilot.session import PermissionHandler
async with CopilotClient(mode="coding-agent") as client:
async with await client.create_session(
model="gpt-5", permissions={"on_request": PermissionHandler.approve_all}
) as session:
def on_event(event):
print(f"Event: {event.type}")
session.on(on_event)
await session.send("Hello!")
# ... wait for events ...
Note: For manual lifecycle management, see Manual Resource Management above.
from copilot import CopilotClient, RuntimeConnection
# Connect to an existing CLI server
client = CopilotClient(mode="coding-agent", runtime=RuntimeConnection.for_tcp("localhost", 3000))
CopilotClient Constructor:
from copilot import CopilotClient
CopilotClient(mode="coding-agent")
CopilotClient(
mode="coding-agent",
observability={"log_level": "debug"},
github={"token": "token"},
)
CopilotClient(mode="coding-agent") # resolve the deployment's current runtime default
CopilotClient(mode="coding-agent", observability={"log_level": "debug"}, github={"token": "token"})
All options are keyword-only. Feature settings use nested dictionaries;
CreateSessionOptions and ResumeSessionOptions type those session dictionaries.
Dotted names below identify group leaves, not flat keywords.
Grouped create/resume RPC payloads require protocol 4 runtimes.