⚠️ Disclaimer: This is an unofficial, community-driven SDK and is not supported or endorsed by GitHub. Use at your own risk.
This document provides detailed API reference and usage examples for the Copilot SDK for Java.
📖 Advanced Usage → - Tools, BYOK, MCP Servers, Infinite Sessions, and more.
new CopilotClient()
new CopilotClient(CopilotClientOptions options)Options:
cliPath- Path to CLI executable (default: "copilot" from PATH)cliArgs- Extra arguments prepended before SDK-managed flagscliUrl- URL of existing CLI server to connect to (e.g.,"localhost:8080"). When provided, the client will not spawn a CLI process.port- Server port (default: 0 for random)useStdio- Use stdio transport instead of TCP (default: true)logLevel- Log level (default: "info")autoStart- Auto-start server (default: true)autoRestart- Auto-restart on crash (default: true)cwd- Working directory for the CLI processenvironment- Environment variables to pass to the CLI process
Start the CLI server and establish connection.
Stop the server and close all sessions.
Force stop the CLI server without graceful cleanup.
Create a new conversation session.
Config:
sessionId- Custom session IDmodel- Model to use ("gpt-5", "claude-sonnet-4.5", etc.)tools- Custom tools exposed to the CLIsystemMessage- System message customizationavailableTools- List of tool names to allowexcludedTools- List of tool names to disableprovider- Custom API provider configuration (BYOK)streaming- Enable streaming of response chunks (default: false)mcpServers- MCP server configurationscustomAgents- Custom agent configurationsonPermissionRequest- Handler for permission requests
Resume an existing session.
Ping the server to check connectivity.
Get CLI status including version and protocol information.
Get current authentication status.
List available models with their metadata (id, name, capabilities, billing info).
Get current connection state. Returns one of: DISCONNECTED, CONNECTING, CONNECTED, ERROR.
List all available sessions.
Delete a session and its data from disk.
Get the ID of the most recently used session.
Represents a single conversation session.
getSessionId()- The unique identifier for this session
Convenience method to send a simple text message. Equivalent to send(new MessageOptions().setPrompt(prompt)).
Send a message to the session.
Options:
prompt- The message/prompt to sendattachments- File attachmentsmode- Delivery mode ("enqueue" or "immediate")
Returns the message ID.
Convenience method to send a simple text message and wait for the session to become idle. Equivalent to sendAndWait(new MessageOptions().setPrompt(prompt)).
Send a message and wait for the session to become idle. Default timeout is 60 seconds.
Send a message and wait for the session to become idle with custom timeout.
Subscribe to session events. Returns a Closeable to unsubscribe.
var subscription = session.on(evt -> {
System.out.println("Event: " + evt.getType());
});
// Later...
subscription.close();Abort the currently processing message in this session.
Get all events/messages from this session.
Dispose the session and free resources.
Sessions emit various events during processing. Each event type extends AbstractSessionEvent:
UserMessageEvent- User message addedAssistantMessageEvent- Assistant responseAssistantMessageDeltaEvent- Streaming response chunkToolExecutionStartEvent- Tool execution startedToolExecutionCompleteEvent- Tool execution completedSessionStartEvent- Session startedSessionIdleEvent- Session is idleSessionErrorEvent- Session error occurredSessionResumeEvent- Session was resumed- And more...
Use pattern matching (Java 21+) to handle specific event types:
session.on(evt -> {
if (evt instanceof AssistantMessageEvent msg) {
System.out.println(msg.getData().getContent());
} else if (evt instanceof SessionErrorEvent err) {
System.out.println("Error: " + err.getData().getMessage());
}
});Enable streaming to receive assistant response chunks as they're generated:
var session = client.createSession(
new SessionConfig()
.setModel("gpt-5")
.setStreaming(true)
).get();
var done = new CompletableFuture<Void>();
session.on(evt -> {
if (evt instanceof AssistantMessageDeltaEvent delta) {
// Streaming message chunk - print incrementally
System.out.print(delta.getData().getDeltaContent());
} else if (evt instanceof AssistantMessageEvent msg) {
// Final message - complete content
System.out.println("\n--- Final message ---");
System.out.println(msg.getData().getContent());
} else if (evt instanceof SessionIdleEvent) {
done.complete(null);
}
});
session.send(new MessageOptions().setPrompt("Tell me a short story")).get();
done.get();Query available models and their capabilities before creating a session:
try (var client = new CopilotClient()) {
client.start().get();
// List all available models
List<ModelInfo> models = client.listModels().get();
for (ModelInfo model : models) {
System.out.println("Model: " + model.getId());
System.out.println(" Name: " + model.getName());
if (model.getCapabilities() != null) {
System.out.println(" Max Output Tokens: " + model.getCapabilities().getMaxOutputTokens());
}
if (model.getPolicy() != null) {
System.out.println(" State: " + model.getPolicy().getState());
}
}
// Use a specific model from the list
var session = client.createSession(
new SessionConfig().setModel(models.get(0).getId())
).get();
}Each ModelInfo contains:
id- Model identifier (e.g., "claude-sonnet-4.5", "gpt-4o")name- Human-readable display namecapabilities- Model limits including max output tokenspolicy- Policy state informationbilling- Billing/usage information
📖 Advanced Usage → - Learn about Tools, BYOK, MCP Servers, Infinite Sessions, Permission Handling, and more.