22
33> ⚠️ ** Disclaimer:** This is an ** unofficial, community-driven SDK** and is ** not supported or endorsed by GitHub** . Use at your own risk.
44
5- This page covers advanced features and configurations for the Copilot SDK for Java.
6-
7- ## Table of Contents
8-
9- - [ Manual Server Control] ( #Manual_Server_Control )
10- - [ Tools] ( #Tools )
11- - [ System Message Customization] ( #System_Message_Customization )
12- - [ Multiple Sessions] ( #Multiple_Sessions )
13- - [ File Attachments] ( #File_Attachments )
14- - [ Bring Your Own Key (BYOK)] ( #Bring_Your_Own_Key_.28BYOK.29 )
15- - [ Permission Handling] ( #Permission_Handling )
16- - [ Infinite Sessions] ( #Infinite_Sessions )
17- - [ MCP Servers] ( #MCP_Servers )
18- - [ Error Handling] ( #Error_Handling )
5+ This guide covers advanced scenarios for extending and customizing your Copilot integration.
196
207---
218
22- ## Manual Server Control
23-
24- ``` java
25- var client = new CopilotClient (
26- new CopilotClientOptions (). setAutoStart(false )
27- );
28-
29- // Start manually
30- client. start(). get();
31-
32- // Use client...
33-
34- // Stop manually
35- client. stop(). get();
36- ```
37-
38- ## Tools
9+ ## Custom Tools
3910
40- You can let the CLI call back into your process when the model needs capabilities you own:
11+ Let the AI call back into your application to fetch data or perform actions.
4112
4213``` java
43- // Define a record for the tool's arguments (recommended)
14+ // Define strongly-typed arguments with a record
4415record IssueArgs(String id) {}
4516
4617var lookupTool = ToolDefinition . create(
@@ -54,217 +25,193 @@ var lookupTool = ToolDefinition.create(
5425 " required" , List . of(" id" )
5526 ),
5627 invocation - > {
57- // Option 1: Type-safe argument access using records (recommended)
5828 IssueArgs args = invocation. getArgumentsAs(IssueArgs . class);
5929 return CompletableFuture . completedFuture(fetchIssue(args. id()));
60-
61- // Option 2: Map-based access (alternative)
62- // Map<String, Object> args = invocation.getArguments();
63- // String id = (String) args.get("id");
64- // return CompletableFuture.completedFuture(fetchIssue(id));
6530 }
6631);
6732
6833var session = client. createSession(
6934 new SessionConfig ()
70- .setModel(" gpt-5" )
7135 .setTools(List . of(lookupTool))
7236). get();
7337```
7438
75- ## System Message Customization
39+ See [ ToolDefinition] ( apidocs/com/github/copilot/sdk/ToolDefinition.html ) Javadoc for schema details.
40+
41+ ---
42+
43+ ## System Messages
44+
45+ Customize the AI's behavior by adding rules or replacing the default prompt.
7646
77- Control the system prompt using ` SystemMessageConfig ` in session config:
47+ ### Adding Rules
48+
49+ Use ` APPEND ` mode to add constraints while keeping default guardrails:
7850
7951``` java
8052var session = client. createSession(
8153 new SessionConfig ()
82- .setModel(" gpt-5" )
8354 .setSystemMessage(new SystemMessageConfig ()
8455 .setMode(SystemMessageMode . APPEND )
8556 .setContent(" " "
86- <workflow_rules >
57+ <rules >
8758 - Always check for security vulnerabilities
88- - Suggest performance improvements when applicable
89- </workflow_rules >
59+ - Suggest performance improvements
60+ </rules >
9061 " " " ))
9162). get();
9263```
9364
94- For full control (removes all guardrails), use ` REPLACE ` mode:
65+ ### Full Control
66+
67+ Use ` REPLACE ` mode for complete control (removes default guardrails):
9568
9669``` java
9770var session = client. createSession(
9871 new SessionConfig ()
99- .setModel(" gpt-5" )
10072 .setSystemMessage(new SystemMessageConfig ()
10173 .setMode(SystemMessageMode . REPLACE )
102- .setContent(" You are a helpful assistant." ))
74+ .setContent(" You are a helpful coding assistant." ))
10375). get();
10476```
10577
106- ## Multiple Sessions
107-
108- ``` java
109- var session1 = client. createSession(
110- new SessionConfig (). setModel(" gpt-5" )
111- ). get();
112-
113- var session2 = client. createSession(
114- new SessionConfig (). setModel(" claude-sonnet-4.5" )
115- ). get();
116-
117- // Both sessions are independent
118- session1. send(new MessageOptions (). setPrompt(" Hello from session 1" )). get();
119- session2. send(new MessageOptions (). setPrompt(" Hello from session 2" )). get();
120- ```
78+ ---
12179
12280## File Attachments
12381
82+ Include files as context for the AI to analyze.
83+
12484``` java
12585session. send(new MessageOptions ()
126- .setPrompt(" Analyze this file" )
86+ .setPrompt(" Review this file for bugs " )
12787 .setAttachments(List . of(
12888 new Attachment ()
12989 .setType(" file" )
13090 .setPath(" /path/to/file.java" )
131- .setDisplayName(" My File " )
91+ .setDisplayName(" MyService.java " )
13292 ))
13393). get();
13494```
13595
96+ ---
97+
13698## Bring Your Own Key (BYOK)
13799
138- Use a custom API provider:
100+ Use your own OpenAI or Azure OpenAI API key instead of GitHub Copilot.
139101
140102``` java
141103var session = client. createSession(
142104 new SessionConfig ()
143105 .setProvider(new ProviderConfig ()
144106 .setType(" openai" )
145107 .setBaseUrl(" https://api.openai.com/v1" )
146- .setApiKey(" your-api-key " ))
108+ .setApiKey(" sk-... " ))
147109). get();
148110```
149111
150- ## Permission Handling
112+ ---
151113
152- Handle permission requests from the CLI:
114+ ## Infinite Sessions
115+
116+ Run long conversations without hitting context limits.
117+
118+ When enabled (default), the session automatically compacts older messages as the context window fills up.
153119
154120``` java
155121var session = client. createSession(
156122 new SessionConfig ()
157- .setModel(" gpt-5" )
158- .setOnPermissionRequest((request, invocation) - > {
159- // Approve or deny the permission request
160- var result = new PermissionRequestResult ();
161- result. setKind(" user-approved" );
162- return CompletableFuture . completedFuture(result);
163- })
123+ .setInfiniteSessions(new InfiniteSessionConfig ()
124+ .setEnabled(true )
125+ .setBackgroundCompactionThreshold(0.80 ) // Start compacting at 80%
126+ .setBufferExhaustionThreshold(0.95 )) // Block at 95%
164127). get();
165- ```
166-
167- ## Infinite Sessions
168128
169- Infinite sessions enable automatic context management for long-running conversations. When enabled (default), the session automatically manages context window limits through background compaction and persists state to a workspace directory.
170-
171- ### How It Works
129+ // Access the workspace where session state is persisted
130+ String workspace = session . getWorkspacePath();
131+ ```
172132
173- As conversations grow, they eventually approach the model's context window limit. Infinite sessions solve this by :
133+ For short conversations, disable to avoid overhead :
174134
175- 1 . ** Background Compaction** : When context utilization reaches the background threshold (default 80%), the session starts compacting older messages asynchronously while continuing to process new messages.
135+ ``` java
136+ new InfiniteSessionConfig (). setEnabled(false )
137+ ```
176138
177- 2 . ** Buffer Exhaustion Protection ** : If context reaches the exhaustion threshold (default 95%) before compaction completes, the session blocks until compaction finishes to prevent overflow.
139+ ---
178140
179- 3 . ** Workspace Persistence** : Session state is persisted to a workspace directory containing:
180- - ` checkpoints/ ` - Session checkpoints for resumption
181- - ` plan.md ` - Current conversation plan
182- - ` files/ ` - Associated files
141+ ## MCP Servers
183142
184- ### Configuration
143+ Extend the AI with external tools via the Model Context Protocol.
185144
186145``` java
187- var infiniteConfig = new InfiniteSessionConfig ()
188- .setEnabled(true )
189- .setBackgroundCompactionThreshold(0.80 ) // Start compacting at 80% utilization
190- .setBufferExhaustionThreshold(0.95 ); // Block at 95% until compaction completes
146+ Map<String , Object > server = Map . of(
147+ " type" , " local" ,
148+ " command" , " npx" ,
149+ " args" , List . of(" -y" , " @modelcontextprotocol/server-filesystem" , " /tmp" ),
150+ " tools" , List . of(" *" )
151+ );
191152
192153var session = client. createSession(
193154 new SessionConfig ()
194- .setModel(" gpt-5" )
195- .setInfiniteSessions(infiniteConfig)
155+ .setMcpServers(Map . of(" filesystem" , server))
196156). get();
197157```
198158
199- ### Configuration Options
200-
201- | Option | Default | Description |
202- | --------| ---------| -------------|
203- | ` enabled ` | ` true ` | Whether infinite sessions are enabled |
204- | ` backgroundCompactionThreshold ` | ` 0.80 ` | Context utilization (0.0-1.0) at which background compaction starts |
205- | ` bufferExhaustionThreshold ` | ` 0.95 ` | Context utilization (0.0-1.0) at which the session blocks until compaction completes |
206-
207- ### Accessing the Workspace
159+ 📖 ** [ Full MCP documentation →] ( mcp.html ) ** for local/remote servers and all options.
208160
209- When infinite sessions are enabled, you can access the workspace path:
210-
211- ``` java
212- var session = client. createSession(
213- new SessionConfig ()
214- .setModel(" gpt-5" )
215- .setInfiniteSessions(new InfiniteSessionConfig (). setEnabled(true ))
216- ). get();
217-
218- String workspacePath = session. getWorkspacePath();
219- if (workspacePath != null ) {
220- System . out. println(" Session workspace: " + workspacePath);
221- // Access checkpoints/, plan.md, files/ subdirectories
222- }
223- ```
161+ ---
224162
225- ### Disabling Infinite Sessions
163+ ## Permission Handling
226164
227- For short conversations where context management isn't needed:
165+ Approve or deny permission requests from the AI.
228166
229167``` java
230168var session = client. createSession(
231169 new SessionConfig ()
232- .setModel(" gpt-5" )
233- .setInfiniteSessions(new InfiniteSessionConfig (). setEnabled(false ))
170+ .setOnPermissionRequest((request, invocation) - > {
171+ // Inspect request and approve/deny
172+ var result = new PermissionRequestResult ();
173+ result. setKind(" user-approved" );
174+ return CompletableFuture . completedFuture(result);
175+ })
234176). get();
235-
236- // session.getWorkspacePath() will return null
237177```
238178
239- ## MCP Servers
240-
241- The Copilot SDK can integrate with MCP servers (Model Context Protocol) to extend the assistant's capabilities with external tools. MCP servers run as separate processes and expose tools that Copilot can invoke during conversations.
179+ ---
242180
243- 📖 ** [ Full MCP documentation → ] ( mcp.html ) ** - Learn about local vs remote servers, all configuration options, and troubleshooting.
181+ ## Manual Server Control
244182
245- Quick example:
183+ Control the CLI lifecycle yourself instead of auto-start.
246184
247185``` java
248- Map<String , Object > filesystemServer = new HashMap<> ();
249- filesystemServer. put(" type" , " local" );
250- filesystemServer. put(" command" , " npx" );
251- filesystemServer. put(" args" , List . of(" -y" , " @modelcontextprotocol/server-filesystem" , " /tmp" ));
252- filesystemServer. put(" tools" , List . of(" *" ));
186+ var client = new CopilotClient (
187+ new CopilotClientOptions (). setAutoStart(false )
188+ );
253189
254- var session = client. createSession(
255- new SessionConfig ()
256- .setMcpServers(Map . of(" filesystem" , filesystemServer))
257- ). get();
190+ client. start(). get(); // Start manually
191+ // ... use client ...
192+ client. stop(). get(); // Stop manually
258193```
259194
195+ ---
196+
260197## Error Handling
261198
199+ All SDK methods return ` CompletableFuture ` . Errors surface via ` ExecutionException ` :
200+
262201``` java
263202try {
264- var session = client. createSession(). get();
265203 session. send(new MessageOptions (). setPrompt(" Hello" )). get();
266204} catch (ExecutionException ex) {
267- Throwable cause = ex. getCause();
268- System . err. println(" Error: " + cause. getMessage());
205+ System . err. println(" Error: " + ex. getCause(). getMessage());
269206}
270207```
208+
209+ For reactive error handling, use ` exceptionally() ` or ` handle() ` :
210+
211+ ``` java
212+ session. send(new MessageOptions (). setPrompt(" Hello" ))
213+ .exceptionally(ex - > {
214+ System . err. println(" Failed: " + ex. getMessage());
215+ return null ;
216+ });
217+ ```
0 commit comments