-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathhooks.html
More file actions
681 lines (638 loc) · 28.6 KB
/
Copy pathhooks.html
File metadata and controls
681 lines (638 loc) · 28.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
<!DOCTYPE html>
<!--
| Generated by Apache Maven Doxia Site Renderer 2.0.0 from target/filtered-site/markdown/hooks.md at 2026-05-16
| Rendered using Apache Maven Fluido Skin 2.1.0
-->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="generator" content="Apache Maven Doxia Site Renderer 2.0.0" />
<title>Session Hooks – GitHub Copilot SDK :: Java</title>
<link rel="stylesheet" href="./css/apache-maven-fluido-2.1.0.min.css" />
<link rel="stylesheet" href="./css/site.css" />
<link rel="stylesheet" href="./css/print.css" media="print" />
<script src="./js/apache-maven-fluido-2.1.0.min.js"></script>
<style>.github-fork-ribbon:before { background-color: gray; }</style>
</head>
<body class="topBarEnabled">
<a class="github-fork-ribbon right-top" href="https://github.com/github/copilot-sdk-java" data-ribbon="Fork me on GitHub">Fork me on GitHub</a>
<header id="topbar" class="navbar navbar-fixed-top ">
<div class="navbar-inner">
<div class="container-fluid">
<a data-target=".nav-collapse" data-toggle="collapse" class="btn btn-navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="index.html">GitHub Copilot SDK for Java
</a>
<ul class="nav">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown">Overview <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="index.html">Introduction</a></li>
<li><a href="getting-started.html">Getting Started</a></li>
<li><a href="setup.html">Setup</a></li>
<li><a href="documentation.html">Documentation</a></li>
<li><a href="mcp.html">MCP Servers</a></li>
<li><a>Session Hooks</a></li>
<li><a href="advanced.html">Advanced Usage</a></li>
<li><a href="apidocs/index.html">API Javadoc</a></li>
</ul>
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown">Guides <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="documentation.html#Basic_Usage">Basic Usage</a></li>
<li><a href="documentation.html#Handling_Responses">Handling Responses</a></li>
<li><a href="documentation.html#Streaming_Responses">Streaming</a></li>
<li><a href="documentation.html#Choosing_a_Model">Choosing a Model</a></li>
<li><a href="documentation.html#Session_Management">Session Management</a></li>
</ul>
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown">Advanced <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="advanced.html#Custom_Tools">Custom Tools</a></li>
<li><a href="advanced.html#System_Messages">System Messages</a></li>
<li><a href="advanced.html#File_Attachments">File Attachments</a></li>
<li><a href="advanced.html#Bring_Your_Own_Key_.28BYOK.29">BYOK</a></li>
<li><a href="advanced.html#Infinite_Sessions">Infinite Sessions</a></li>
<li><a href="advanced.html#MCP_Servers">MCP Servers</a></li>
<li><a href="advanced.html#Slash_Commands">Slash Commands</a></li>
<li><a href="advanced.html#Elicitation_UI_Dialogs">Elicitation</a></li>
<li><a href="advanced.html#Getting_Session_Metadata_by_ID">Session Metadata</a></li>
<li><a>Session Hooks</a></li>
</ul>
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown">Cookbook <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="cookbook/README.html">Overview</a></li>
<li><a href="cookbook/error-handling.html">Error Handling</a></li>
<li><a href="cookbook/multiple-sessions.html">Multiple Sessions</a></li>
<li><a href="cookbook/managing-local-files.html">Managing Local Files</a></li>
<li><a href="cookbook/pr-visualization.html">PR Visualization</a></li>
<li><a href="cookbook/persisting-sessions.html">Persisting Sessions</a></li>
</ul>
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown">Project Documentation <b class="caret"></b></a>
<ul class="dropdown-menu">
<li class="dropdown-submenu">
<a href="project-info.html">Project Information</a>
<ul class="dropdown-menu">
<li><a href="dependencies.html">Dependencies</a></li>
<li><a href="dependency-info.html">Maven Coordinates</a></li>
<li><a href="distribution-management.html">Distribution Management</a></li>
<li><a href="index.html">About</a></li>
<li><a href="licenses.html">Licenses</a></li>
<li><a href="plugin-management.html">Plugin Management</a></li>
<li><a href="plugins.html">Plugins</a></li>
<li><a href="scm.html">Source Code Management</a></li>
<li><a href="summary.html">Summary</a></li>
<li><a href="team.html">Team</a></li>
</ul>
</li>
<li class="dropdown-submenu">
<a href="project-reports.html">Project Reports</a>
<ul class="dropdown-menu">
<li><a href="apidocs/index.html">Javadoc</a></li>
<li><a href="surefire.html">Surefire</a></li>
<li><a href="spotbugs.html">SpotBugs</a></li>
<li><a href="taglist.html">Tag List</a></li>
<li><a href="dependency-analysis.html">Dependency Analysis</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
</header>
<div class="container-fluid container-fluid-top">
<header>
<div id="banner">
<div class="pull-left"></div>
<div class="pull-right"></div>
<div class="clear"><hr/></div>
</div>
<div id="breadcrumbs">
<ul class="breadcrumb">
<li id="publishDate">Last Published: 2026-05-16<span class="divider">|</span>
</li>
<li id="projectVersion">Version: 1.0.0-beta-java.4<span class="divider">|</span></li>
<li><a href="index.html">Home</a><span class="divider">/</span></li>
<li class="active">Session Hooks</li>
</ul>
</div>
</header>
<div class="row-fluid">
<header id="leftColumn" class="span2">
<nav class="well sidebar-nav">
<ul class="nav nav-list">
<li class="nav-header">Overview</li>
<li><a href="index.html">Introduction</a></li>
<li><a href="getting-started.html">Getting Started</a></li>
<li><a href="setup.html">Setup</a></li>
<li><a href="documentation.html">Documentation</a></li>
<li><a href="mcp.html">MCP Servers</a></li>
<li class="active"><a>Session Hooks</a></li>
<li><a href="advanced.html">Advanced Usage</a></li>
<li><a href="apidocs/index.html">API Javadoc</a></li>
<li class="nav-header">Guides</li>
<li><a href="documentation.html#Basic_Usage">Basic Usage</a></li>
<li><a href="documentation.html#Handling_Responses">Handling Responses</a></li>
<li><a href="documentation.html#Streaming_Responses">Streaming</a></li>
<li><a href="documentation.html#Choosing_a_Model">Choosing a Model</a></li>
<li><a href="documentation.html#Session_Management">Session Management</a></li>
<li class="nav-header">Advanced</li>
<li><a href="advanced.html#Custom_Tools">Custom Tools</a></li>
<li><a href="advanced.html#System_Messages">System Messages</a></li>
<li><a href="advanced.html#File_Attachments">File Attachments</a></li>
<li><a href="advanced.html#Bring_Your_Own_Key_.28BYOK.29">BYOK</a></li>
<li><a href="advanced.html#Infinite_Sessions">Infinite Sessions</a></li>
<li><a href="advanced.html#MCP_Servers">MCP Servers</a></li>
<li><a href="advanced.html#Slash_Commands">Slash Commands</a></li>
<li><a href="advanced.html#Elicitation_UI_Dialogs">Elicitation</a></li>
<li><a href="advanced.html#Getting_Session_Metadata_by_ID">Session Metadata</a></li>
<li class="active"><a>Session Hooks</a></li>
<li class="nav-header">Cookbook</li>
<li><a href="cookbook/README.html">Overview</a></li>
<li><a href="cookbook/error-handling.html">Error Handling</a></li>
<li><a href="cookbook/multiple-sessions.html">Multiple Sessions</a></li>
<li><a href="cookbook/managing-local-files.html">Managing Local Files</a></li>
<li><a href="cookbook/pr-visualization.html">PR Visualization</a></li>
<li><a href="cookbook/persisting-sessions.html">Persisting Sessions</a></li>
<li class="nav-header">Project Documentation</li>
<li><a href="project-info.html"><span class="icon-chevron-right"></span>Project Information</a></li>
<li><a href="project-reports.html"><span class="icon-chevron-right"></span>Project Reports</a></li>
</ul>
</nav>
<div class="well sidebar-nav">
<div id="poweredBy">
<div class="clear"></div>
<div class="clear"></div>
<a href="https://maven.apache.org/" class="builtBy" target="_blank"><img class="builtBy" alt="Built by Maven" src="./images/logos/maven-feather.png" /></a>
</div>
</div>
</header>
<main id="bodyColumn" class="span10">
<section><a id="Session_Hooks"></a>
<h1>Session Hooks</h1>
<p>Session hooks allow you to intercept and modify tool execution, user prompts, and session lifecycle events. Use hooks to implement custom logic like logging, security controls, or context injection.</p><hr /><section><a id="Overview"></a>
<h2>Overview</h2>
<table class="table table-striped">
<thead>
<tr class="a">
<th>Hook</th>
<th>When It's Called</th>
<th>Can Modify</th></tr></thead><tbody>
<tr class="b">
<td><a href="#Pre-Tool_Use_Hook">Pre-Tool Use</a></td>
<td>Before a tool executes</td>
<td>Tool arguments, permission decision</td></tr>
<tr class="a">
<td><a href="#Post-Tool_Use_Hook">Post-Tool Use</a></td>
<td>After a tool executes</td>
<td>Tool result, additional context</td></tr>
<tr class="b">
<td><a href="#User_Prompt_Submitted_Hook">User Prompt Submitted</a></td>
<td>When user sends a message</td>
<td>Nothing (observation only)</td></tr>
<tr class="a">
<td><a href="#Session_Start_Hook">Session Start</a></td>
<td>When session begins</td>
<td>Nothing (observation only)</td></tr>
<tr class="b">
<td><a href="#Session_End_Hook">Session End</a></td>
<td>When session ends</td>
<td>Nothing (observation only)</td></tr>
<tr class="a">
<td><a href="#Checking_Whether_Hooks_Are_Registered">Checking Whether Hooks Are Registered</a></td>
<td>Before session creation</td>
<td>Whether any handlers are configured</td></tr></tbody>
</table>
<hr /></section><section><a id="Quick_Start"></a>
<h2>Quick Start</h2>
<p>Register hooks when creating a session:</p>
<pre class="prettyprint"><code class="language-java">var hooks = new SessionHooks()
.setOnPreToolUse((input, invocation) -> {
System.out.println("Tool: " + input.getToolName());
return CompletableFuture.completedFuture(PreToolUseHookOutput.allow());
})
.setOnPostToolUse((input, invocation) -> {
System.out.println("Result: " + input.getToolResult());
return CompletableFuture.completedFuture(null);
});
var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
.setModel("gpt-4.1")
.setHooks(hooks)
).get();
</code></pre><hr /></section><section><a id="Pre-Tool_Use_Hook"></a>
<h2>Pre-Tool Use Hook</h2>
<p>Called <strong>before</strong> a tool executes. Use this to:</p>
<ul>
<li>Approve, deny, or prompt for tool execution</li>
<li>Modify tool arguments</li>
<li>Add context for the LLM</li>
<li>Suppress tool output from being shown</li>
</ul><section><a id="Input"></a>
<h3>Input</h3>
<table class="table table-striped">
<thead>
<tr class="a">
<th>Field</th>
<th>Type</th>
<th>Description</th></tr></thead><tbody>
<tr class="b">
<td><code>getToolName()</code></td>
<td><code>String</code></td>
<td>Name of the tool being called</td></tr>
<tr class="a">
<td><code>getToolArgs()</code></td>
<td><code>JsonNode</code></td>
<td>Arguments passed to the tool</td></tr>
<tr class="b">
<td><code>getCwd()</code></td>
<td><code>String</code></td>
<td>Current working directory</td></tr>
<tr class="a">
<td><code>getTimestamp()</code></td>
<td><code>long</code></td>
<td>Timestamp in milliseconds</td></tr></tbody>
</table>
</section><section><a id="Output"></a>
<h3>Output</h3>
<table class="table table-striped">
<thead>
<tr class="a">
<th>Field</th>
<th>Type</th>
<th>Description</th></tr></thead><tbody>
<tr class="b">
<td><code>setPermissionDecision(String)</code></td>
<td><code>"allow"</code>, <code>"deny"</code>, <code>"ask"</code></td>
<td>Whether to execute the tool</td></tr>
<tr class="a">
<td><code>setPermissionDecisionReason(String)</code></td>
<td><code>String</code></td>
<td>Reason shown to user/LLM</td></tr>
<tr class="b">
<td><code>setModifiedArgs(JsonNode)</code></td>
<td><code>JsonNode</code></td>
<td>Modified arguments (optional)</td></tr>
<tr class="a">
<td><code>setAdditionalContext(String)</code></td>
<td><code>String</code></td>
<td>Extra context for the LLM</td></tr>
<tr class="b">
<td><code>setSuppressOutput(Boolean)</code></td>
<td><code>Boolean</code></td>
<td>Hide output from display</td></tr></tbody>
</table>
</section><section><a id="Example.3A_Security_Gate"></a>
<h3>Example: Security Gate</h3>
<p>Block dangerous tool calls:</p>
<pre class="prettyprint"><code class="language-java">var hooks = new SessionHooks()
.setOnPreToolUse((input, invocation) -> {
String tool = input.getToolName();
// Block file deletion
if (tool.equals("delete_file")) {
return CompletableFuture.completedFuture(
PreToolUseHookOutput.deny("File deletion is not allowed")
);
}
// Require confirmation for shell commands
if (tool.equals("run_terminal_cmd")) {
return CompletableFuture.completedFuture(PreToolUseHookOutput.ask());
}
// Allow everything else
return CompletableFuture.completedFuture(PreToolUseHookOutput.allow());
});
</code></pre></section><section><a id="Example.3A_Argument_Modification"></a>
<h3>Example: Argument Modification</h3>
<p>Inject context into tool arguments:</p>
<pre class="prettyprint"><code class="language-java">var hooks = new SessionHooks()
.setOnPreToolUse((input, invocation) -> {
if (input.getToolName().equals("search_code")) {
// Add project root to search path
var mapper = new ObjectMapper();
var modifiedArgs = mapper.createObjectNode();
modifiedArgs.put("path", "/my/project/src");
modifiedArgs.set("query", input.getToolArgs().get("query"));
return CompletableFuture.completedFuture(
PreToolUseHookOutput.withModifiedArgs("allow", modifiedArgs)
);
}
return CompletableFuture.completedFuture(PreToolUseHookOutput.allow());
});
</code></pre><hr /></section></section><section><a id="Post-Tool_Use_Hook"></a>
<h2>Post-Tool Use Hook</h2>
<p>Called <strong>after</strong> a tool executes. Use this to:</p>
<ul>
<li>Log tool results</li>
<li>Modify the result shown to the LLM</li>
<li>Add additional context based on results</li>
<li>Suppress output from display</li>
</ul><section><a id="Input_1"></a>
<h3>Input</h3>
<table class="table table-striped">
<thead>
<tr class="a">
<th>Field</th>
<th>Type</th>
<th>Description</th></tr></thead><tbody>
<tr class="b">
<td><code>getToolName()</code></td>
<td><code>String</code></td>
<td>Name of the tool that was called</td></tr>
<tr class="a">
<td><code>getToolArgs()</code></td>
<td><code>JsonNode</code></td>
<td>Arguments that were passed</td></tr>
<tr class="b">
<td><code>getToolResult()</code></td>
<td><code>JsonNode</code></td>
<td>Result from the tool</td></tr>
<tr class="a">
<td><code>getCwd()</code></td>
<td><code>String</code></td>
<td>Current working directory</td></tr>
<tr class="b">
<td><code>getTimestamp()</code></td>
<td><code>long</code></td>
<td>Timestamp in milliseconds</td></tr></tbody>
</table>
</section><section><a id="Output_1"></a>
<h3>Output</h3>
<table class="table table-striped">
<thead>
<tr class="a">
<th>Field</th>
<th>Type</th>
<th>Description</th></tr></thead><tbody>
<tr class="b">
<td><code>setModifiedResult(String)</code></td>
<td><code>String</code></td>
<td>Modified result for the LLM</td></tr>
<tr class="a">
<td><code>setAdditionalContext(String)</code></td>
<td><code>String</code></td>
<td>Extra context for the LLM</td></tr>
<tr class="b">
<td><code>setSuppressOutput(Boolean)</code></td>
<td><code>Boolean</code></td>
<td>Hide output from display</td></tr></tbody>
</table>
</section><section><a id="Example.3A_Result_Logging"></a>
<h3>Example: Result Logging</h3>
<p>Log all tool executions:</p>
<pre class="prettyprint"><code class="language-java">var hooks = new SessionHooks()
.setOnPostToolUse((input, invocation) -> {
System.out.printf("[%d] %s completed%n",
input.getTimestamp(),
input.getToolName());
System.out.println("Result: " + input.getToolResult());
return CompletableFuture.completedFuture(null);
});
</code></pre></section><section><a id="Example.3A_Result_Enrichment"></a>
<h3>Example: Result Enrichment</h3>
<p>Add context to file read results:</p>
<pre class="prettyprint"><code class="language-java">var hooks = new SessionHooks()
.setOnPostToolUse((input, invocation) -> {
if (input.getToolName().equals("read_file")) {
String context = "Note: This file was last modified 2 hours ago.";
return CompletableFuture.completedFuture(
new PostToolUseHookOutput(null, context, null)
);
}
return CompletableFuture.completedFuture(null);
});
</code></pre><hr /></section></section><section><a id="User_Prompt_Submitted_Hook"></a>
<h2>User Prompt Submitted Hook</h2>
<p>Called when the user submits a prompt, before the LLM processes it. This is an observation hook - you cannot modify the prompt.</p><section><a id="Input_2"></a>
<h3>Input</h3>
<table class="table table-striped">
<thead>
<tr class="a">
<th>Field</th>
<th>Type</th>
<th>Description</th></tr></thead><tbody>
<tr class="b">
<td><code>prompt()</code></td>
<td><code>String</code></td>
<td>The user's prompt text</td></tr>
<tr class="a">
<td><code>getTimestamp()</code></td>
<td><code>long</code></td>
<td>Timestamp in milliseconds</td></tr></tbody>
</table>
</section><section><a id="Output_2"></a>
<h3>Output</h3>
<p>Return <code>null</code> - this hook is observation-only.</p></section><section><a id="Example.3A_Prompt_Logging"></a>
<h3>Example: Prompt Logging</h3>
<pre class="prettyprint"><code class="language-java">var hooks = new SessionHooks()
.setOnUserPromptSubmitted((input, invocation) -> {
System.out.println("User asked: " + input.prompt());
// Track prompts for analytics
analytics.track("user_prompt", Map.of(
"sessionId", invocation.getSessionId(),
"promptLength", input.prompt().length()
));
return CompletableFuture.completedFuture(null);
});
</code></pre><hr /></section></section><section><a id="Session_Start_Hook"></a>
<h2>Session Start Hook</h2>
<p>Called when a session starts (either new or resumed).</p><section><a id="Input_3"></a>
<h3>Input</h3>
<table class="table table-striped">
<thead>
<tr class="a">
<th>Field</th>
<th>Type</th>
<th>Description</th></tr></thead><tbody>
<tr class="b">
<td><code>source()</code></td>
<td><code>String</code></td>
<td><code>"startup"</code>, <code>"resume"</code>, or <code>"new"</code></td></tr>
<tr class="a">
<td><code>getTimestamp()</code></td>
<td><code>long</code></td>
<td>Timestamp in milliseconds</td></tr></tbody>
</table>
</section><section><a id="Output_3"></a>
<h3>Output</h3>
<p>Return <code>null</code> - this hook is observation-only.</p></section><section><a id="Example.3A_Session_Initialization"></a>
<h3>Example: Session Initialization</h3>
<pre class="prettyprint"><code class="language-java">var hooks = new SessionHooks()
.setOnSessionStart((input, invocation) -> {
System.out.println("Session started: " + invocation.getSessionId());
System.out.println("Source: " + input.source());
// Initialize session-specific resources
sessionResources.put(invocation.getSessionId(), new ResourceManager());
return CompletableFuture.completedFuture(null);
});
</code></pre><hr /></section></section><section><a id="Session_End_Hook"></a>
<h2>Session End Hook</h2>
<p>Called when a session ends.</p><section><a id="Input_4"></a>
<h3>Input</h3>
<table class="table table-striped">
<thead>
<tr class="a">
<th>Field</th>
<th>Type</th>
<th>Description</th></tr></thead><tbody>
<tr class="b">
<td><code>reason()</code></td>
<td><code>String</code></td>
<td>Why the session ended</td></tr>
<tr class="a">
<td><code>getTimestamp()</code></td>
<td><code>long</code></td>
<td>Timestamp in milliseconds</td></tr></tbody>
</table>
</section><section><a id="Output_4"></a>
<h3>Output</h3>
<p>Return <code>null</code> - this hook is observation-only.</p></section><section><a id="Example.3A_Session_Cleanup"></a>
<h3>Example: Session Cleanup</h3>
<pre class="prettyprint"><code class="language-java">var hooks = new SessionHooks()
.setOnSessionEnd((input, invocation) -> {
System.out.println("Session ended: " + input.reason());
// Clean up session resources
var resources = sessionResources.remove(invocation.getSessionId());
if (resources != null) {
resources.close();
}
return CompletableFuture.completedFuture(null);
});
</code></pre><hr /></section></section><section><a id="Complete_Example"></a>
<h2>Complete Example</h2>
<p>Combining multiple hooks for comprehensive session control:</p>
<pre class="prettyprint"><code class="language-java">import com.github.copilot.sdk.CopilotClient;
import com.github.copilot.sdk.json.PermissionHandler;
import com.github.copilot.sdk.json.PreToolUseHookOutput;
import com.github.copilot.sdk.json.SessionConfig;
import com.github.copilot.sdk.json.SessionHooks;
import java.util.concurrent.CompletableFuture;
public class HooksExample {
public static void main(String[] args) throws Exception {
try (var client = new CopilotClient()) {
client.start().get();
var hooks = new SessionHooks()
// Security: control tool execution
.setOnPreToolUse((input, invocation) -> {
System.out.println("→ " + input.getToolName());
// Deny dangerous operations
if (input.getToolName().contains("delete")) {
return CompletableFuture.completedFuture(
PreToolUseHookOutput.deny("Deletion not allowed")
);
}
return CompletableFuture.completedFuture(PreToolUseHookOutput.allow());
})
// Logging: track tool results
.setOnPostToolUse((input, invocation) -> {
System.out.println("← " + input.getToolName() + " completed");
return CompletableFuture.completedFuture(null);
})
// Analytics: track user prompts
.setOnUserPromptSubmitted((input, invocation) -> {
System.out.println("User: " + input.prompt());
return CompletableFuture.completedFuture(null);
})
// Lifecycle: initialization and cleanup
.setOnSessionStart((input, invocation) -> {
System.out.println("Session started (" + input.source() + ")");
return CompletableFuture.completedFuture(null);
})
.setOnSessionEnd((input, invocation) -> {
System.out.println("Session ended: " + input.reason());
return CompletableFuture.completedFuture(null);
});
var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
.setModel("gpt-4.1")
.setHooks(hooks)
).get();
var response = session.sendAndWait("List files in /tmp").get();
System.out.println(response.getData().content());
session.close();
}
}
}
</code></pre><hr /></section><section><a id="Hook_Invocation_Object"></a>
<h2>Hook Invocation Object</h2>
<p>All hook handlers receive a <code>HookInvocation</code> object as the second parameter:</p>
<table class="table table-striped">
<thead>
<tr class="a">
<th>Method</th>
<th>Description</th></tr></thead><tbody>
<tr class="b">
<td><code>getSessionId()</code></td>
<td>The session ID where the hook was triggered</td></tr></tbody>
</table>
<p>This allows you to correlate hooks with specific sessions when managing multiple concurrent sessions.</p></section><section><a id="Checking_Whether_Hooks_Are_Registered"></a>
<h2>Checking Whether Hooks Are Registered</h2>
<p>Use <code>hasHooks()</code> to quickly verify that at least one hook handler is configured:</p>
<pre class="prettyprint"><code class="language-java">var hooks = new SessionHooks()
.setOnPreToolUse((input, invocation) ->
CompletableFuture.completedFuture(PreToolUseHookOutput.allow()));
if (hooks.hasHooks()) {
var session = client.createSession(
new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL).setHooks(hooks)
).get();
}
</code></pre><hr /></section><section><a id="Error_Handling"></a>
<h2>Error Handling</h2>
<p>If a hook throws an exception, the SDK logs the error and continues with default behavior:</p>
<ul>
<li>Pre-tool hooks default to allowing execution</li>
<li>Post-tool hooks have no effect on the result</li>
<li>Lifecycle hooks are observation-only</li>
</ul>
<p>To handle errors gracefully in your hooks:</p>
<pre class="prettyprint"><code class="language-java">.setOnPreToolUse((input, invocation) -> {
try {
// Your logic here
return CompletableFuture.completedFuture(PreToolUseHookOutput.allow());
} catch (Exception e) {
logger.error("Hook error", e);
// Fail-safe: deny if something goes wrong
return CompletableFuture.completedFuture(
PreToolUseHookOutput.deny("Internal error")
);
}
})
</code></pre><hr /></section><section><a id="See_Also"></a>
<h2>See Also</h2>
<ul>
<li><a href="apidocs/com/github/copilot/sdk/json/SessionHooks.html">SessionHooks Javadoc</a></li>
<li><a href="apidocs/com/github/copilot/sdk/json/PreToolUseHookInput.html">PreToolUseHookInput Javadoc</a></li>
<li><a href="apidocs/com/github/copilot/sdk/json/PreToolUseHookOutput.html">PreToolUseHookOutput Javadoc</a></li>
<li><a href="apidocs/com/github/copilot/sdk/json/PostToolUseHookInput.html">PostToolUseHookInput Javadoc</a></li>
<li><a href="apidocs/com/github/copilot/sdk/json/PostToolUseHookOutput.html">PostToolUseHookOutput Javadoc</a></li>
</ul><hr /></section><section><a id="Next_Steps"></a>
<h2>Next Steps</h2>
<ul>
<li>📖 <strong><a href="documentation.html">Documentation</a></strong> - Core concepts, events, session management</li>
<li>📖 <strong><a href="advanced.html">Advanced Usage</a></strong> - Tools, BYOK, MCP Servers, Custom Agents</li>
<li>📖 <strong><a href="mcp.html">MCP Servers</a></strong> - Integrate external tools via Model Context Protocol</li>
<li>📖 <strong><a href="apidocs/index.html">API Javadoc</a></strong> - Complete API reference</li>
</ul></section></section> </main>
</div>
</div>
<hr/>
<footer>
<div class="container-fluid">
<div class="row-fluid">
<p>© 2026
</p>
</div>
</div>
</footer>
</body>
</html>