-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Expand file tree
/
Copy pathserver.rs
More file actions
1623 lines (1482 loc) · 59.3 KB
/
server.rs
File metadata and controls
1623 lines (1482 loc) · 59.3 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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::custom_requests::*;
use anyhow::Result;
use fs_err as fs;
use goose::agents::extension::{Envs, PLATFORM_EXTENSIONS};
use goose::agents::{Agent, AgentConfig, ExtensionConfig, GoosePlatform, SessionConfig};
use goose::builtin_extension::register_builtin_extensions;
use goose::config::base::CONFIG_YAML_NAME;
use goose::config::extensions::get_enabled_extensions_with_config;
use goose::config::paths::Paths;
use goose::config::permission::PermissionManager;
use goose::config::Config;
use goose::conversation::message::{ActionRequiredData, Message, MessageContent};
use goose::conversation::Conversation;
use goose::mcp_utils::ToolResult;
use goose::permission::permission_confirmation::PrincipalType;
use goose::permission::{Permission, PermissionConfirmation};
use goose::providers::base::Provider;
use goose::providers::create as create_provider;
use goose::providers::provider_registry::ProviderConstructor;
use goose::session::session_manager::SessionType;
use goose::session::{Session, SessionManager};
use goose_acp_macros::custom_methods;
use rmcp::model::{CallToolResult, RawContent, ResourceContents, Role};
use sacp::schema::{
AgentCapabilities, AuthMethod, AuthenticateRequest, AuthenticateResponse, BlobResourceContents,
CancelNotification, Content, ContentBlock, ContentChunk, EmbeddedResource,
EmbeddedResourceResource, ImageContent, InitializeRequest, InitializeResponse,
ListSessionsResponse, LoadSessionRequest, LoadSessionResponse, McpCapabilities, McpServer,
ModelId, ModelInfo, NewSessionRequest, NewSessionResponse, PermissionOption,
PermissionOptionKind, PromptCapabilities, PromptRequest, PromptResponse,
RequestPermissionOutcome, RequestPermissionRequest, ResourceLink, SessionCapabilities,
SessionId, SessionInfo, SessionListCapabilities, SessionModelState, SessionNotification,
SessionUpdate, SetSessionModelRequest, SetSessionModelResponse, StopReason, TextContent,
TextResourceContents, ToolCall, ToolCallContent, ToolCallId, ToolCallLocation, ToolCallStatus,
ToolCallUpdate, ToolCallUpdateFields, ToolKind,
};
use sacp::{AgentToClient, ByteStreams, Handled, JrConnectionCx, JrMessageHandler, MessageCx};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio_util::compat::{TokioAsyncReadCompatExt as _, TokioAsyncWriteCompatExt as _};
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info, warn};
use url::Url;
// Agent binds provider, extensions, and permission channels to a single session.
// ACP has no session/close, so sessions accumulate until transport closes.
struct GooseAcpSession {
agent: Arc<Agent>,
messages: Conversation,
tool_requests: HashMap<String, goose::conversation::message::ToolRequest>,
cancel_token: Option<CancellationToken>,
}
pub struct GooseAcpAgent {
sessions: Arc<Mutex<HashMap<String, GooseAcpSession>>>,
provider_factory: ProviderConstructor,
config_dir: std::path::PathBuf,
session_manager: Arc<SessionManager>,
permission_manager: Arc<PermissionManager>,
goose_mode: goose::config::GooseMode,
disable_session_naming: bool,
builtins: Vec<String>,
}
fn mcp_server_to_extension_config(mcp_server: McpServer) -> Result<ExtensionConfig, String> {
match mcp_server {
McpServer::Stdio(stdio) => Ok(ExtensionConfig::Stdio {
name: stdio.name,
description: String::new(),
cmd: stdio.command.to_string_lossy().to_string(),
args: stdio.args,
envs: Envs::new(stdio.env.into_iter().map(|e| (e.name, e.value)).collect()),
env_keys: vec![],
timeout: None,
bundled: Some(false),
available_tools: vec![],
}),
McpServer::Http(http) => Ok(ExtensionConfig::StreamableHttp {
name: http.name,
description: String::new(),
uri: http.url,
envs: Envs::default(),
env_keys: vec![],
headers: http
.headers
.into_iter()
.map(|h| (h.name, h.value))
.collect(),
timeout: None,
bundled: Some(false),
available_tools: vec![],
}),
McpServer::Sse(_) => Err("SSE is unsupported, migrate to streamable_http".to_string()),
_ => Err("Unknown MCP server type".to_string()),
}
}
fn create_tool_location(path: &str, line: Option<u32>) -> ToolCallLocation {
let mut loc = ToolCallLocation::new(path);
if let Some(l) = line {
loc = loc.line(l);
}
loc
}
fn is_developer_file_tool(tool_name: &str) -> bool {
matches!(tool_name, "write" | "edit")
}
fn extract_tool_locations(
tool_request: &goose::conversation::message::ToolRequest,
tool_response: &goose::conversation::message::ToolResponse,
) -> Vec<ToolCallLocation> {
let mut locations = Vec::new();
if let Ok(tool_call) = &tool_request.tool_call {
if !is_developer_file_tool(tool_call.name.as_ref()) {
return locations;
}
let tool_name = tool_call.name.as_ref();
let path_str = tool_call
.arguments
.as_ref()
.and_then(|args| args.get("path"))
.and_then(|p| p.as_str());
if let Some(path_str) = path_str {
if matches!(tool_name, "write" | "edit") {
locations.push(create_tool_location(path_str, Some(1)));
return locations;
}
let command = tool_call
.arguments
.as_ref()
.and_then(|args| args.get("command"))
.and_then(|c| c.as_str());
if let Ok(result) = &tool_response.tool_result {
for content in &result.content {
if let RawContent::Text(text_content) = &content.raw {
let text = &text_content.text;
match command {
Some("view") => {
let line = extract_view_line_range(text)
.map(|range| range.0 as u32)
.or(Some(1));
locations.push(create_tool_location(path_str, line));
}
Some("str_replace") | Some("insert") => {
let line = extract_first_line_number(text)
.map(|l| l as u32)
.or(Some(1));
locations.push(create_tool_location(path_str, line));
}
Some("write") => {
locations.push(create_tool_location(path_str, Some(1)));
}
_ => {
locations.push(create_tool_location(path_str, Some(1)));
}
}
break;
}
}
}
if locations.is_empty() {
locations.push(create_tool_location(path_str, Some(1)));
}
}
}
locations
}
fn extract_view_line_range(text: &str) -> Option<(usize, usize)> {
let re = regex::Regex::new(r"\(lines (\d+)-(\d+|end)\)").ok()?;
if let Some(caps) = re.captures(text) {
let start = caps.get(1)?.as_str().parse::<usize>().ok()?;
let end = if caps.get(2)?.as_str() == "end" {
start
} else {
caps.get(2)?.as_str().parse::<usize>().ok()?
};
return Some((start, end));
}
None
}
fn extract_first_line_number(text: &str) -> Option<usize> {
let re = regex::Regex::new(r"```[^\n]*\n(\d+):").ok()?;
if let Some(caps) = re.captures(text) {
return caps.get(1)?.as_str().parse::<usize>().ok();
}
None
}
fn read_resource_link(link: ResourceLink) -> Option<String> {
let url = Url::parse(&link.uri).ok()?;
if url.scheme() == "file" {
let path = url.to_file_path().ok()?;
let contents = fs::read_to_string(&path).ok()?;
Some(format!(
"\n\n# {}\n```\n{}\n```",
path.to_string_lossy(),
contents
))
} else {
None
}
}
fn format_tool_name(tool_name: &str) -> String {
let capitalize = |s: &str| {
s.split_whitespace()
.map(|word| {
let mut chars = word.chars();
match chars.next() {
None => String::new(),
Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
}
})
.collect::<Vec<_>>()
.join(" ")
};
if let Some((extension, tool)) = tool_name.split_once("__") {
let formatted_extension = extension.replace('_', " ");
let formatted_tool = tool.replace('_', " ");
format!(
"{}: {}",
capitalize(&formatted_extension),
capitalize(&formatted_tool)
)
} else {
let formatted = tool_name.replace('_', " ");
capitalize(&formatted)
}
}
async fn add_builtins(agent: &Agent, builtins: Vec<String>) {
for builtin in builtins {
let config = if PLATFORM_EXTENSIONS.contains_key(builtin.as_str()) {
ExtensionConfig::Platform {
name: builtin.clone(),
description: builtin.clone(),
display_name: None,
bundled: None,
available_tools: Vec::new(),
}
} else {
ExtensionConfig::Builtin {
name: builtin.clone(),
display_name: None,
timeout: None,
bundled: None,
description: builtin.clone(),
available_tools: Vec::new(),
}
};
match agent
.extension_manager
.add_extension(config, None, None, None)
.await
{
Ok(_) => info!(extension = %builtin, "extension loaded"),
Err(e) => warn!(extension = %builtin, error = %e, "extension load failed"),
}
}
}
async fn add_extensions(agent: &Agent, extensions: Vec<ExtensionConfig>) {
for extension in extensions {
let name = extension.name().to_string();
match agent
.extension_manager
.add_extension(extension, None, None, None)
.await
{
Ok(_) => info!(extension = %name, "extension loaded"),
Err(e) => warn!(extension = %name, error = %e, "extension load failed"),
}
}
}
async fn build_model_state(provider: &dyn Provider, current_model: &str) -> SessionModelState {
let models = match provider.fetch_recommended_models().await {
Ok(models) => models,
Err(e) => {
warn!(error = %e, "failed to fetch models, model selection will be unavailable");
vec![]
}
};
SessionModelState::new(
ModelId::new(current_model),
models
.iter()
.map(|name| ModelInfo::new(ModelId::new(&**name), &**name))
.collect(),
)
}
impl GooseAcpAgent {
pub fn permission_manager(&self) -> Arc<PermissionManager> {
Arc::clone(&self.permission_manager)
}
pub async fn new(
provider_factory: ProviderConstructor,
builtins: Vec<String>,
data_dir: std::path::PathBuf,
config_dir: std::path::PathBuf,
goose_mode: goose::config::GooseMode,
disable_session_naming: bool,
) -> Result<Self> {
let session_manager = Arc::new(SessionManager::new(data_dir));
let permission_manager = Arc::new(PermissionManager::new(config_dir.clone()));
Ok(Self {
sessions: Arc::new(Mutex::new(HashMap::new())),
provider_factory,
config_dir,
session_manager,
permission_manager,
goose_mode,
disable_session_naming,
builtins,
})
}
async fn create_agent_for_session(&self) -> Arc<Agent> {
let agent = Agent::with_config(AgentConfig::new(
Arc::clone(&self.session_manager),
Arc::clone(&self.permission_manager),
None,
self.goose_mode,
self.disable_session_naming,
GoosePlatform::GooseCli,
));
let agent = Arc::new(agent);
let config_path = self.config_dir.join(CONFIG_YAML_NAME);
if let Ok(config_file) = Config::new(&config_path, "goose") {
let extensions = get_enabled_extensions_with_config(&config_file);
add_extensions(&agent, extensions).await;
}
add_builtins(&agent, self.builtins.clone()).await;
agent
}
pub async fn has_session(&self, session_id: &str) -> bool {
self.sessions.lock().await.contains_key(session_id)
}
fn convert_acp_prompt_to_message(&self, prompt: Vec<ContentBlock>) -> Message {
let mut user_message = Message::user();
for block in prompt {
match block {
ContentBlock::Text(text) => {
user_message = user_message.with_text(&text.text);
}
ContentBlock::Image(image) => {
user_message = user_message.with_image(&image.data, &image.mime_type);
}
ContentBlock::Resource(resource) => {
if let EmbeddedResourceResource::TextResourceContents(text_resource) =
&resource.resource
{
let header = format!("--- Resource: {} ---\n", text_resource.uri);
let content = format!("{}{}\n---\n", header, text_resource.text);
user_message = user_message.with_text(&content);
}
}
ContentBlock::ResourceLink(link) => {
if let Some(text) = read_resource_link(link) {
user_message = user_message.with_text(text)
}
}
ContentBlock::Audio(..) | _ => (),
}
}
user_message
}
async fn handle_message_content(
&self,
content_item: &MessageContent,
session_id: &SessionId,
session: &mut GooseAcpSession,
cx: &JrConnectionCx<AgentToClient>,
) -> Result<(), sacp::Error> {
match content_item {
MessageContent::Text(text) => {
cx.send_notification(SessionNotification::new(
session_id.clone(),
SessionUpdate::AgentMessageChunk(ContentChunk::new(ContentBlock::Text(
TextContent::new(text.text.clone()),
))),
))?;
}
MessageContent::ToolRequest(tool_request) => {
self.handle_tool_request(tool_request, session_id, session, cx)
.await?;
}
MessageContent::ToolResponse(tool_response) => {
self.handle_tool_response(tool_response, session_id, session, cx)
.await?;
}
MessageContent::Thinking(thinking) => {
cx.send_notification(SessionNotification::new(
session_id.clone(),
SessionUpdate::AgentThoughtChunk(ContentChunk::new(ContentBlock::Text(
TextContent::new(thinking.thinking.clone()),
))),
))?;
}
MessageContent::ActionRequired(action_required) => {
if let ActionRequiredData::ToolConfirmation {
id,
tool_name,
arguments,
prompt,
} = &action_required.data
{
self.handle_tool_permission_request(
cx,
&session.agent,
session_id,
id.clone(),
tool_name.clone(),
arguments.clone(),
prompt.clone(),
)?;
}
}
_ => {}
}
Ok(())
}
async fn handle_tool_request(
&self,
tool_request: &goose::conversation::message::ToolRequest,
session_id: &SessionId,
session: &mut GooseAcpSession,
cx: &JrConnectionCx<AgentToClient>,
) -> Result<(), sacp::Error> {
session
.tool_requests
.insert(tool_request.id.clone(), tool_request.clone());
let tool_name = match &tool_request.tool_call {
Ok(tool_call) => tool_call.name.to_string(),
Err(_) => "error".to_string(),
};
cx.send_notification(SessionNotification::new(
session_id.clone(),
SessionUpdate::ToolCall(
ToolCall::new(
ToolCallId::new(tool_request.id.clone()),
format_tool_name(&tool_name),
)
.status(ToolCallStatus::Pending),
),
))?;
Ok(())
}
async fn handle_tool_response(
&self,
tool_response: &goose::conversation::message::ToolResponse,
session_id: &SessionId,
session: &mut GooseAcpSession,
cx: &JrConnectionCx<AgentToClient>,
) -> Result<(), sacp::Error> {
let status = match &tool_response.tool_result {
Ok(result) if result.is_error == Some(true) => ToolCallStatus::Failed,
Ok(_) => ToolCallStatus::Completed,
Err(_) => ToolCallStatus::Failed,
};
let content = build_tool_call_content(&tool_response.tool_result);
let locations = if let Some(tool_request) = session.tool_requests.get(&tool_response.id) {
extract_tool_locations(tool_request, tool_response)
} else {
Vec::new()
};
let mut fields = ToolCallUpdateFields::new().status(status).content(content);
if !locations.is_empty() {
fields = fields.locations(locations);
}
cx.send_notification(SessionNotification::new(
session_id.clone(),
SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
ToolCallId::new(tool_response.id.clone()),
fields,
)),
))?;
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn handle_tool_permission_request(
&self,
cx: &JrConnectionCx<AgentToClient>,
agent: &Arc<Agent>,
session_id: &SessionId,
request_id: String,
tool_name: String,
arguments: serde_json::Map<String, serde_json::Value>,
prompt: Option<String>,
) -> Result<(), sacp::Error> {
let cx = cx.clone();
let agent = agent.clone();
let session_id = session_id.clone();
let formatted_name = format_tool_name(&tool_name);
let mut fields = ToolCallUpdateFields::new()
.title(formatted_name)
.kind(ToolKind::default())
.status(ToolCallStatus::Pending)
.raw_input(serde_json::Value::Object(arguments));
if let Some(p) = prompt {
fields = fields.content(vec![ToolCallContent::Content(Content::new(
ContentBlock::Text(TextContent::new(p)),
))]);
}
let tool_call_update = ToolCallUpdate::new(ToolCallId::new(request_id.clone()), fields);
fn option(kind: PermissionOptionKind) -> PermissionOption {
let id = serde_json::to_value(kind)
.unwrap()
.as_str()
.unwrap()
.to_string();
PermissionOption::new(id.clone(), id, kind)
}
let options = vec![
option(PermissionOptionKind::AllowAlways),
option(PermissionOptionKind::AllowOnce),
option(PermissionOptionKind::RejectOnce),
option(PermissionOptionKind::RejectAlways),
];
let permission_request =
RequestPermissionRequest::new(session_id, tool_call_update, options);
cx.send_request(permission_request)
.on_receiving_result(move |result| async move {
match result {
Ok(response) => {
agent
.handle_confirmation(
request_id,
outcome_to_confirmation(&response.outcome),
)
.await;
Ok(())
}
Err(e) => {
error!(error = ?e, "permission request failed");
agent
.handle_confirmation(
request_id,
PermissionConfirmation {
principal_type: PrincipalType::Tool,
permission: Permission::Cancel,
},
)
.await;
Ok(())
}
}
})?;
Ok(())
}
}
fn outcome_to_confirmation(outcome: &RequestPermissionOutcome) -> PermissionConfirmation {
let permission = match outcome {
RequestPermissionOutcome::Cancelled => Permission::Cancel,
RequestPermissionOutcome::Selected(selected) => {
match serde_json::from_value::<PermissionOptionKind>(serde_json::Value::String(
selected.option_id.0.to_string(),
)) {
Ok(PermissionOptionKind::AllowAlways) => Permission::AlwaysAllow,
Ok(PermissionOptionKind::AllowOnce) => Permission::AllowOnce,
Ok(PermissionOptionKind::RejectOnce) => Permission::DenyOnce,
Ok(PermissionOptionKind::RejectAlways) => Permission::AlwaysDeny,
_ => Permission::Cancel,
}
}
_ => Permission::Cancel,
};
PermissionConfirmation {
principal_type: PrincipalType::Tool,
permission,
}
}
fn build_tool_call_content(tool_result: &ToolResult<CallToolResult>) -> Vec<ToolCallContent> {
match tool_result {
Ok(result) => result
.content
.iter()
.filter_map(|content| match &content.raw {
RawContent::Text(val) => Some(ToolCallContent::Content(Content::new(
ContentBlock::Text(TextContent::new(val.text.clone())),
))),
RawContent::Image(val) => Some(ToolCallContent::Content(Content::new(
ContentBlock::Image(ImageContent::new(val.data.clone(), val.mime_type.clone())),
))),
RawContent::Resource(val) => {
let resource = match &val.resource {
ResourceContents::TextResourceContents {
mime_type,
text,
uri,
..
} => EmbeddedResourceResource::TextResourceContents(
TextResourceContents::new(text.clone(), uri.clone())
.mime_type(mime_type.clone()),
),
ResourceContents::BlobResourceContents {
mime_type,
blob,
uri,
..
} => EmbeddedResourceResource::BlobResourceContents(
BlobResourceContents::new(blob.clone(), uri.clone())
.mime_type(mime_type.clone()),
),
};
Some(ToolCallContent::Content(Content::new(
ContentBlock::Resource(EmbeddedResource::new(resource)),
)))
}
RawContent::Audio(_) | RawContent::ResourceLink(_) => None,
})
.collect(),
Err(_) => Vec::new(),
}
}
impl GooseAcpAgent {
async fn on_initialize(
&self,
args: InitializeRequest,
) -> Result<InitializeResponse, sacp::Error> {
debug!(?args, "initialize request");
let capabilities = AgentCapabilities::new()
.load_session(true)
.session_capabilities(SessionCapabilities::new().list(SessionListCapabilities::new()))
.prompt_capabilities(
PromptCapabilities::new()
.image(true)
.audio(false)
.embedded_context(true),
)
.mcp_capabilities(McpCapabilities::new().http(true));
Ok(InitializeResponse::new(args.protocol_version)
.agent_capabilities(capabilities)
.auth_methods(vec![AuthMethod::new(
"goose-provider",
"Configure Provider",
)
.description(
"Run `goose configure` to set up your AI provider and API key",
)]))
}
async fn on_new_session(
&self,
args: NewSessionRequest,
) -> Result<NewSessionResponse, sacp::Error> {
debug!(?args, "new session request");
let goose_session = self
.session_manager
.create_session(
args.cwd.clone(),
"ACP Session".to_string(),
SessionType::User,
)
.await
.map_err(|e| {
sacp::Error::internal_error().data(format!("Failed to create session: {}", e))
})?;
let agent = self.create_agent_for_session().await;
let provider = self
.init_provider(&agent, &goose_session)
.await
.map_err(|e| {
sacp::Error::internal_error().data(format!("Failed to set provider: {}", e))
})?;
for mcp_server in args.mcp_servers {
let config = match mcp_server_to_extension_config(mcp_server) {
Ok(c) => c,
Err(msg) => {
return Err(sacp::Error::invalid_params().data(msg));
}
};
let name = config.name().to_string();
if let Err(e) = agent.add_extension(config, &goose_session.id).await {
return Err(sacp::Error::internal_error()
.data(format!("Failed to add MCP server '{}': {}", name, e)));
}
}
let session = GooseAcpSession {
agent,
messages: Conversation::new_unvalidated(Vec::new()),
tool_requests: HashMap::new(),
cancel_token: None,
};
let mut sessions = self.sessions.lock().await;
sessions.insert(goose_session.id.clone(), session);
info!(
session_id = %goose_session.id,
session_type = "acp",
"Session started"
);
let model_state =
build_model_state(&*provider, &provider.get_model_config().model_name).await;
Ok(NewSessionResponse::new(SessionId::new(goose_session.id)).models(model_state))
}
async fn init_provider(&self, agent: &Agent, session: &Session) -> Result<Arc<dyn Provider>> {
let model_config = match &session.model_config {
Some(config) => config.clone(),
None => {
let config_path = self.config_dir.join(CONFIG_YAML_NAME);
let config = Config::new(&config_path, "goose")?;
let model_id = config.get_goose_model()?;
let provider_name = config.get_goose_provider()?;
goose::model::ModelConfig::new(&model_id)?.with_canonical_limits(&provider_name)
}
};
let provider = (self.provider_factory)(model_config, Vec::new()).await?;
agent.update_provider(provider.clone(), &session.id).await?;
Ok(provider)
}
async fn on_load_session(
&self,
args: LoadSessionRequest,
cx: &JrConnectionCx<AgentToClient>,
) -> Result<LoadSessionResponse, sacp::Error> {
debug!(?args, "load session request");
let session_id = args.session_id.0.to_string();
let goose_session = self
.session_manager
.get_session(&session_id, true)
.await
.map_err(|e| {
sacp::Error::invalid_params()
.data(format!("Failed to load session {}: {}", session_id, e))
})?;
let agent = self.create_agent_for_session().await;
let provider = self
.init_provider(&agent, &goose_session)
.await
.map_err(|e| {
sacp::Error::internal_error().data(format!("Failed to set provider: {}", e))
})?;
let conversation = goose_session.conversation.ok_or_else(|| {
sacp::Error::internal_error()
.data(format!("Session {} has no conversation data", session_id))
})?;
self.session_manager
.update(&session_id)
.working_dir(args.cwd.clone())
.apply()
.await
.map_err(|e| {
sacp::Error::internal_error()
.data(format!("Failed to update session working directory: {}", e))
})?;
let mut session = GooseAcpSession {
agent,
messages: conversation.clone(),
tool_requests: HashMap::new(),
cancel_token: None,
};
for message in conversation.messages() {
if !message.metadata.user_visible {
continue;
}
for content_item in &message.content {
match content_item {
MessageContent::Text(text) => {
let chunk = ContentChunk::new(ContentBlock::Text(TextContent::new(
text.text.clone(),
)));
let update = match message.role {
Role::User => SessionUpdate::UserMessageChunk(chunk),
Role::Assistant => SessionUpdate::AgentMessageChunk(chunk),
};
cx.send_notification(SessionNotification::new(
args.session_id.clone(),
update,
))?;
}
MessageContent::ToolRequest(tool_request) => {
self.handle_tool_request(tool_request, &args.session_id, &mut session, cx)
.await?;
}
MessageContent::ToolResponse(tool_response) => {
self.handle_tool_response(
tool_response,
&args.session_id,
&mut session,
cx,
)
.await?;
}
MessageContent::Thinking(thinking) => {
cx.send_notification(SessionNotification::new(
args.session_id.clone(),
SessionUpdate::AgentThoughtChunk(ContentChunk::new(
ContentBlock::Text(TextContent::new(thinking.thinking.clone())),
)),
))?;
}
_ => {}
}
}
}
let mut sessions = self.sessions.lock().await;
sessions.insert(session_id.clone(), session);
info!(
session_id = %session_id,
session_type = "acp",
"Session loaded"
);
let model_state =
build_model_state(&*provider, &provider.get_model_config().model_name).await;
Ok(LoadSessionResponse::new().models(model_state))
}
async fn on_prompt(
&self,
args: PromptRequest,
cx: &JrConnectionCx<AgentToClient>,
) -> Result<PromptResponse, sacp::Error> {
let session_id = args.session_id.0.to_string();
let cancel_token = CancellationToken::new();
let agent = {
let mut sessions = self.sessions.lock().await;
let session = sessions.get_mut(&session_id).ok_or_else(|| {
sacp::Error::invalid_params().data(format!("Session not found: {}", session_id))
})?;
session.cancel_token = Some(cancel_token.clone());
session.agent.clone()
};
let user_message = self.convert_acp_prompt_to_message(args.prompt);
let session_config = SessionConfig {
id: session_id.clone(),
schedule_id: None,
max_turns: None,
retry_config: None,
};
let mut stream = agent
.reply(user_message, session_config, Some(cancel_token.clone()))
.await
.map_err(|e| {
sacp::Error::internal_error().data(format!("Error getting agent reply: {}", e))
})?;
use futures::StreamExt;
let mut was_cancelled = false;
while let Some(event) = stream.next().await {
if cancel_token.is_cancelled() {
was_cancelled = true;
break;
}
match event {
Ok(goose::agents::AgentEvent::Message(message)) => {
let mut sessions = self.sessions.lock().await;
let session = sessions.get_mut(&session_id).ok_or_else(|| {
sacp::Error::invalid_params()
.data(format!("Session not found: {}", session_id))
})?;
session.messages.push(message.clone());
for content_item in &message.content {
self.handle_message_content(content_item, &args.session_id, session, cx)
.await?;
}
}
Ok(_) => {}
Err(e) => {
return Err(sacp::Error::internal_error()
.data(format!("Error in agent response stream: {}", e)));
}
}
}
let mut sessions = self.sessions.lock().await;
if let Some(session) = sessions.get_mut(&session_id) {
session.cancel_token = None;
}
Ok(PromptResponse::new(if was_cancelled {
StopReason::Cancelled
} else {
StopReason::EndTurn
}))
}
async fn on_cancel(&self, args: CancelNotification) -> Result<(), sacp::Error> {
debug!(?args, "cancel request");
let session_id = args.session_id.0.to_string();
let mut sessions = self.sessions.lock().await;
if let Some(session) = sessions.get_mut(&session_id) {
if let Some(ref token) = session.cancel_token {
info!(session_id = %session_id, "prompt cancelled");
token.cancel();
}
} else {
warn!(session_id = %session_id, "cancel request for unknown session");
}
Ok(())
}
async fn on_set_model(
&self,
session_id: &str,
model_id: &str,
provider_override: Option<&str>,
) -> Result<SetSessionModelResponse, sacp::Error> {
let config_path = self.config_dir.join(CONFIG_YAML_NAME);
let config = Config::new(&config_path, "goose").map_err(|e| {
sacp::Error::internal_error().data(format!("Failed to read config: {}", e))
})?;
let provider_name = if let Some(p) = provider_override {
p.to_string()
} else {
config.get_goose_provider().map_err(|_| {
sacp::Error::internal_error().data("No provider configured".to_string())
})?
};
let model_config = goose::model::ModelConfig::new(model_id)
.map_err(|e| {
sacp::Error::invalid_params().data(format!("Invalid model config: {}", e))
})?
.with_canonical_limits(&provider_name);
let provider = if provider_override.is_some() {
// When switching providers, use the global registry (same as HTTP update_agent_provider).
create_provider(&provider_name, model_config, Vec::new())
.await
.map_err(|e| {
sacp::Error::internal_error().data(format!("Failed to create provider: {}", e))
})?
} else {