-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathservice.rs
More file actions
1571 lines (1470 loc) · 58.9 KB
/
Copy pathservice.rs
File metadata and controls
1571 lines (1470 loc) · 58.9 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::{
AppState, VERSION,
api::mcp::{
dispatch::{
ToolCall, ToolIdentity, dispatch_tool_call, linked_cancel_token,
operator_cancellation_result,
},
effects::tab_groups::apply_agent_tab_group_title,
naming::{build_session_group_title, client_prefix_from_slug, normalize_small_name},
observers::audit::{LocalToolDispatch, record_local_tool_dispatch},
prompt::BROWSERCLAW_MCP_INSTRUCTIONS,
},
identity::{ClientIdentity, ClientInfo, ProfileView},
ids::{DispatchId, SessionId},
services::{
sessions::Session,
skills::{CreateSkill, SkillOrigin},
},
};
use browseros_mcp::{OutputFileAccess, ToolDef, ToolResult, catalog};
use rmcp::{
ErrorData as McpError, RoleServer,
handler::server::ServerHandler,
model::{
CallToolRequestMethod, CallToolRequestParams, CallToolResponse, CallToolResult,
Implementation, InitializeRequestParams, InitializeResult, JsonObject, ListToolsResult,
PaginatedRequestParams, ProtocolVersion, ServerCapabilities, Tool, ToolAnnotations,
},
service::{NotificationContext, RequestContext},
};
use serde_json::{Value, json};
use std::{
borrow::Cow,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
time::Instant as StdInstant,
};
use tokio::sync::Mutex;
use tokio_util::sync::CancellationToken;
use tracing::warn;
use ulid::Ulid;
use uuid::Uuid;
const SERVER_NAME: &str = "browseros-neo";
const SERVER_TITLE: &str = "BrowserOS neo";
const NAME_SESSION_TOOL_NAME: &str = "name_session";
const NAME_SESSION_DESCRIPTION: &str = "Name this browser session at the start of a task: a small lowercase 2-3 word label for what it is doing, e.g. \"invoice processing\", a `category` for the kind of task, and a short `summary`. Tabs are grouped as <client>/<name>; the label and summary stay on this machine (the summary makes the session findable in audit search), and only the category is used for anonymous aggregate analytics. Call again to update.";
const NAME_SESSION_CATEGORY_DESCRIPTION: &str = "The kind of task, for anonymous aggregate analytics only; the free-form name is never sent. Pick the closest fit from the list.";
const NAME_SESSION_SUMMARY_DESCRIPTION: &str = "One or two short lines saying what this task is, phrased so you can find it again by searching later. No names, emails, URLs, file paths, or account numbers.";
const SUMMARY_MAX_LEN: usize = 200;
const NAME_SESSION_INPUT_MAX_LEN: usize = 64;
const SESSION_ARG_DESCRIPTION: &str = "Opaque session handle returned by the server. Pass it back on every call to keep working in the same browser session; omit it to start a new session.";
const SAVE_SKILL_TOOL_NAME: &str = "save_skill";
const SAVE_SKILL_DESCRIPTION: &str = "When you finish a repeatable browser task the user is likely to run again, save it as a BrowserOS neo skill so it can be re-run by name later; save genuinely repeatable, user-valuable tasks, not one-offs. Give a lowercase-hyphen name, a one-line description, the ordered steps, and any shortcuts learned this run. In the steps, name the exact browser SDK calls you actually used this session (e.g. browser.wait, browser.read, browser.pages.newPage) so a later run reuses them verbatim; never invent, rename, or guess a method that is not in the run tool's SDK (there is no browser.waitFor, for example). The skill is saved and linked into your agents under a neo- prefix (neo-<name>) so it never clobbers your own skills and you can list them all by typing /neo; a name given without the prefix is namespaced automatically. Call again with the same name to update it in place.";
const MARK_SKILL_RUN_TOOL_NAME: &str = "mark_skill_run";
const MARK_SKILL_RUN_DESCRIPTION: &str = "Mark this browser session as a run of a saved skill so BrowserOS neo records the run and its cost once the session ends. Call this once, at the start, when you are running a skill, with the skill's name.";
/// Owns one MCP transport lifetime. Drop best-effort schedules removal of a started
/// server session, which records its end and begins retained-group handling.
pub struct ClawMcpService {
state: AppState,
catalog: Arc<Vec<ToolDef>>,
name_session_tool: Tool,
save_skill_tool: Tool,
mark_skill_run_tool: Tool,
output_files: OutputFileAccess,
lifecycle: Arc<Mutex<ServiceLifecycle>>,
fallback_session_id: SessionId,
closed: AtomicBool,
}
#[derive(Default)]
struct ServiceLifecycle {
client_info: Option<ClientInfo>,
session_id: Option<SessionId>,
started: bool,
}
#[derive(Clone)]
struct StartedSession {
session: Arc<Session>,
agent_label: String,
}
impl ClawMcpService {
#[must_use]
pub fn new(state: AppState) -> Self {
Self {
state,
catalog: Arc::new(catalog()),
name_session_tool: name_session_tool(),
save_skill_tool: save_skill_tool(),
mark_skill_run_tool: mark_skill_run_tool(),
output_files: browseros_mcp::output_file::create_browser_output_file_access(),
lifecycle: Arc::new(Mutex::new(ServiceLifecycle::default())),
fallback_session_id: SessionId::new(format!("stdio-{}", Ulid::new())),
closed: AtomicBool::new(false),
}
}
fn find_tool_index(&self, name: &str) -> Option<usize> {
self.catalog.iter().position(|tool| tool.name == name)
}
fn listed_tools(&self) -> Vec<Tool> {
let mut tools = self
.catalog
.iter()
.map(ToolDef::to_mcp_tool)
.map(with_session_arg)
.collect::<Vec<_>>();
tools.push(with_session_arg(self.name_session_tool.clone()));
tools.push(with_session_arg(self.save_skill_tool.clone()));
tools.push(with_session_arg(self.mark_skill_run_tool.clone()));
tools
}
async fn call_name_session(
&self,
started: &StartedSession,
raw_args: &Value,
) -> CallToolResult {
let dispatch_id = DispatchId::new();
let dispatch_cancel = CancellationToken::new();
if !started
.session
.try_register_dispatch(dispatch_id.clone(), dispatch_cancel)
.await
{
return CallToolResult::error(vec![rmcp::model::ContentBlock::text(
"BrowserOS neo session is no longer live",
)]);
}
let started_at = StdInstant::now();
let rename = match rename_session(Some(started.session.as_ref()), raw_args).await {
Ok(rename) => rename,
Err(message) => {
return finish_local_dispatch(
started.session.as_ref(),
&dispatch_id,
ToolResult::error(message),
)
.await
.into_call_tool_result();
}
};
if let Some(category) = raw_args
.get("category")
.and_then(Value::as_str)
.map(str::trim)
.filter(|category| !category.is_empty())
{
// At most once per session: a later name_session rename must not
// re-declare and overcount the category mix or the declaration rate.
if started.session.try_mark_task_declared() {
self.state.analytics.capture(
crate::analytics::events::AGENT_SESSION_TASK_DECLARED,
json!({
"task_category": category,
"client_name": started.session.client_name(),
}),
);
}
}
// Scrub structural PII from any provided summary before it is persisted or
// indexed for search; stored locally only, never sent to analytics. Last write wins.
let scrubbed_summary = raw_args
.get("summary")
.and_then(Value::as_str)
.map(str::trim)
.filter(|summary| !summary.is_empty())
.map(scrub_summary);
if let Some(clean) = scrubbed_summary.as_deref()
&& !clean.is_empty()
&& let Err(error) = self
.state
.audit_log
.set_task_summary(started.session.id().as_str(), clean)
.await
{
warn!(error = %error, "failed to store task summary");
}
let browser = self.state.browser.session().await;
apply_agent_tab_group_title(
browser.as_ref(),
&self.state.sessions.ownership(),
started.session.convo_id(),
started.session.as_ref(),
started.session.child_token(),
)
.await;
let result = ToolResult::text(rename.response, None);
// The audit dispatch persists the raw tool arguments; substitute the scrubbed
// summary so the unsanitized text never reaches the audit detail timeline.
let dispatch_args = match scrubbed_summary.as_deref() {
Some(clean) => with_scrubbed_summary(raw_args, clean),
None => raw_args.clone(),
};
if let Err(error) = record_local_tool_dispatch(
&self.state,
LocalToolDispatch {
session: &started.session,
agent_label: &started.agent_label,
tool_name: NAME_SESSION_TOOL_NAME,
raw_args: &dispatch_args,
result: &result,
duration_ms: i64::try_from(started_at.elapsed().as_millis()).unwrap_or(i64::MAX),
dispatch_id: dispatch_id.clone(),
},
)
.await
{
warn!(error = %error, "local tool audit submission failed");
}
finish_local_dispatch(started.session.as_ref(), &dispatch_id, result)
.await
.into_call_tool_result()
}
async fn call_save_skill(&self, started: &StartedSession, raw_args: &Value) -> CallToolResult {
let dispatch_id = DispatchId::new();
let dispatch_cancel = CancellationToken::new();
if !started
.session
.try_register_dispatch(dispatch_id.clone(), dispatch_cancel)
.await
{
return CallToolResult::error(vec![rmcp::model::ContentBlock::text(
"BrowserOS neo session is no longer live",
)]);
}
let started_at = StdInstant::now();
let session_id = started.session.id().as_str().to_string();
let result = match parse_save_skill(raw_args, session_id) {
Ok(input) => match self.state.skills.upsert(input).await {
Ok(view) => ToolResult::text(format!("saved skill /{}", view.model.name), None),
Err(error) => ToolResult::error(error.to_string()),
},
Err(message) => ToolResult::error(message),
};
if let Err(error) = record_local_tool_dispatch(
&self.state,
LocalToolDispatch {
session: &started.session,
agent_label: &started.agent_label,
tool_name: SAVE_SKILL_TOOL_NAME,
raw_args,
result: &result,
duration_ms: i64::try_from(started_at.elapsed().as_millis()).unwrap_or(i64::MAX),
dispatch_id: dispatch_id.clone(),
},
)
.await
{
warn!(error = %error, "local tool audit submission failed");
}
finish_local_dispatch(started.session.as_ref(), &dispatch_id, result)
.await
.into_call_tool_result()
}
async fn call_mark_skill_run(
&self,
started: &StartedSession,
raw_args: &Value,
) -> CallToolResult {
let dispatch_id = DispatchId::new();
let dispatch_cancel = CancellationToken::new();
if !started
.session
.try_register_dispatch(dispatch_id.clone(), dispatch_cancel)
.await
{
return CallToolResult::error(vec![rmcp::model::ContentBlock::text(
"BrowserOS neo session is no longer live",
)]);
}
let started_at = StdInstant::now();
let session_id = started.session.id().as_str().to_string();
let result = match parse_skill_name(raw_args) {
Ok(name) => {
// Skills are namespaced under neo-; accept a bare name too so a
// run is still recorded if the agent drops the prefix.
let name = crate::services::skills::neo_prefixed(&name);
match self.state.skill_runs.mark(&session_id, &name).await {
Ok(()) => ToolResult::text(format!("recording this run of /{name}"), None),
Err(error) => ToolResult::error(error.to_string()),
}
}
Err(message) => ToolResult::error(message),
};
if let Err(error) = record_local_tool_dispatch(
&self.state,
LocalToolDispatch {
session: &started.session,
agent_label: &started.agent_label,
tool_name: MARK_SKILL_RUN_TOOL_NAME,
raw_args,
result: &result,
duration_ms: i64::try_from(started_at.elapsed().as_millis()).unwrap_or(i64::MAX),
dispatch_id: dispatch_id.clone(),
},
)
.await
{
warn!(error = %error, "local tool audit submission failed");
}
finish_local_dispatch(started.session.as_ref(), &dispatch_id, result)
.await
.into_call_tool_result()
}
async fn set_client_info(&self, request: &InitializeRequestParams) {
let mut lifecycle = self.lifecycle.lock().await;
lifecycle.client_info = Some(ClientInfo {
name: clean_client_field(&request.client_info.name, "agent"),
version: clean_client_field(&request.client_info.version, "unknown"),
title: request
.client_info
.title
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.map(str::to_string),
});
}
/// Looks up an existing store session for `session_id` or mints one under it.
/// Does not touch `self.lifecycle`, so a caller that must stay out of the
/// transport-close cleanup can start a session without arming that teardown.
async fn start_session_in_store(
&self,
session_id: SessionId,
client: ClientInfo,
) -> Result<StartedSession, McpError> {
let session = if let Some(session) = self.state.sessions.lookup(&session_id).await {
session
} else {
let profiles = self.state.profiles.list_profiles().await.map_err(|error| {
McpError::internal_error(format!("agent profile lookup failed: {error}"), None)
})?;
let profiles = profiles.iter().map(ProfileView::from).collect::<Vec<_>>();
let agent = ClientIdentity::resolve(&client, &profiles);
let session = self
.state
.sessions
.mint_with_id(session_id.clone(), agent, client.clone())
.await
.map_err(|error| {
McpError::internal_error(format!("mcp session start failed: {error}"), None)
})?;
tracing::info!(
session_id = %session.id(),
agent = %session.convo_id(),
"mcp session initialized"
);
session
};
Ok(started_session_from(session, &client))
}
/// Legacy and stdio path. Caches the session id and start flag in
/// `self.lifecycle`, which the transport-close `Drop` uses to reap the session.
async fn ensure_session_started(
&self,
session_id: SessionId,
) -> Result<StartedSession, McpError> {
let mut lifecycle = self.lifecycle.lock().await;
if lifecycle.session_id.is_none() {
lifecycle.session_id = Some(session_id.clone());
}
let session_id = lifecycle
.session_id
.clone()
.unwrap_or_else(|| session_id.clone());
let client = lifecycle.client_info.clone().unwrap_or_else(|| ClientInfo {
name: "agent".to_string(),
version: "unknown".to_string(),
title: None,
});
if lifecycle.started {
let session = self
.state
.sessions
.lookup(&session_id)
.await
.ok_or_else(|| {
McpError::invalid_request(
format!("BrowserOS neo session {session_id} is no longer live"),
None,
)
})?;
return Ok(started_session_from(session, &client));
}
let started = self.start_session_in_store(session_id, client).await?;
lifecycle.started = true;
Ok(started)
}
/// Modern stateless path. Reuses a live server-minted handle; any absent or
/// unrecognized handle mints a fresh server-generated handle rather than being
/// honored, so a caller cannot choose or seed a session id and concurrent calls
/// never mint the same id. Does not touch `self.lifecycle`, so the per-request
/// service `Drop` never reaps it; idle sweeping owns cleanup.
async fn resolve_modern_session(
&self,
provided: Option<SessionId>,
) -> Result<(StartedSession, SessionId), McpError> {
let client = ClientInfo {
name: "agent".to_string(),
version: "unknown".to_string(),
title: None,
};
if let Some(handle) = provided
&& let Some(session) = self.state.sessions.lookup(&handle).await
{
return Ok((started_session_from(session, &client), handle));
}
let handle = SessionId::new(Uuid::new_v4().to_string());
let started = self.start_session_in_store(handle.clone(), client).await?;
Ok((started, handle))
}
async fn learn_session_from_request(
&self,
context: &RequestContext<RoleServer>,
) -> Result<StartedSession, McpError> {
let session_id = session_id_from_extensions(&context.extensions)
.unwrap_or_else(|| self.fallback_session_id.clone());
self.ensure_session_started(session_id).await
}
async fn learn_session_from_notification(&self, context: &NotificationContext<RoleServer>) {
let session_id = session_id_from_extensions(&context.extensions)
.unwrap_or_else(|| self.fallback_session_id.clone());
if let Err(error) = self.ensure_session_started(session_id).await {
warn!(error = %error, "mcp session start failed");
}
}
}
impl Drop for ClawMcpService {
fn drop(&mut self) {
if self.closed.swap(true, Ordering::SeqCst) {
return;
}
let state = self.state.clone();
let lifecycle = self.lifecycle.clone();
let Ok(handle) = tokio::runtime::Handle::try_current() else {
return;
};
handle.spawn(async move {
let session_id = {
let lifecycle = lifecycle.lock().await;
lifecycle
.started
.then(|| lifecycle.session_id.clone())
.flatten()
};
let Some(session_id) = session_id else {
return;
};
if let Err(error) = state
.sessions
.remove(&session_id, "closed", Some("transport closed"))
.await
{
warn!(error = %error, session_id = %session_id, "mcp session close failed");
}
});
}
}
// The server serves the modern stateless revision alongside the legacy revisions,
// so 2026-07-28 clients get the sessionless model while older clients keep the
// session model. rmcp picks per request from what a client negotiates.
const SUPPORTED_PROTOCOL_VERSIONS: &[ProtocolVersion] = &[
ProtocolVersion::V_2026_07_28,
ProtocolVersion::V_2025_11_25,
ProtocolVersion::V_2025_06_18,
ProtocolVersion::V_2025_03_26,
ProtocolVersion::V_2024_11_05,
];
impl ServerHandler for ClawMcpService {
fn get_info(&self) -> InitializeResult {
let capabilities = ServerCapabilities::builder().enable_tools().build();
let mut implementation = Implementation::new(SERVER_NAME, VERSION);
implementation.title = Some(SERVER_TITLE.to_string());
InitializeResult::new(capabilities)
.with_server_info(implementation)
.with_instructions(BROWSERCLAW_MCP_INSTRUCTIONS)
}
fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> {
Cow::Borrowed(SUPPORTED_PROTOCOL_VERSIONS)
}
async fn initialize(
&self,
request: InitializeRequestParams,
context: RequestContext<RoleServer>,
) -> Result<InitializeResult, McpError> {
context.peer.set_peer_info(request.clone());
self.set_client_info(&request).await;
let info = self.get_info();
let Some(session_id) = session_id_from_extensions(&context.extensions) else {
return Ok(info);
};
let _ = self.ensure_session_started(session_id).await?;
Ok(info)
}
async fn on_initialized(&self, context: NotificationContext<RoleServer>) {
self.learn_session_from_notification(&context).await;
}
fn list_tools(
&self,
_request: Option<PaginatedRequestParams>,
_context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<ListToolsResult, McpError>> + Send + '_ {
std::future::ready(Ok(ListToolsResult::with_all_items(self.listed_tools())))
}
fn get_tool(&self, name: &str) -> Option<Tool> {
if name == NAME_SESSION_TOOL_NAME {
return Some(with_session_arg(self.name_session_tool.clone()));
}
if name == SAVE_SKILL_TOOL_NAME {
return Some(with_session_arg(self.save_skill_tool.clone()));
}
if name == MARK_SKILL_RUN_TOOL_NAME {
return Some(with_session_arg(self.mark_skill_run_tool.clone()));
}
self.find_tool_index(name)
.map(|index| with_session_arg(self.catalog[index].to_mcp_tool()))
}
async fn call_tool(
&self,
request: CallToolRequestParams,
context: RequestContext<RoleServer>,
) -> Result<CallToolResponse, McpError> {
let is_name_session = request.name == NAME_SESSION_TOOL_NAME;
let is_save_skill = request.name == SAVE_SKILL_TOOL_NAME;
let is_mark_skill_run = request.name == MARK_SKILL_RUN_TOOL_NAME;
let tool_index = self.find_tool_index(&request.name);
if !is_name_session && !is_save_skill && !is_mark_skill_run && tool_index.is_none() {
return Err(McpError::method_not_found::<CallToolRequestMethod>());
}
let mut raw_args = request
.arguments
.map(Value::Object)
.unwrap_or_else(|| Value::Object(JsonObject::new()));
let provided_handle = raw_args
.get("session")
.and_then(Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.map(SessionId::new);
if let Value::Object(map) = &mut raw_args {
map.remove("session");
}
let modern = protocol_version_from_extensions(&context.extensions)
.is_some_and(|version| version >= ProtocolVersion::V_2026_07_28)
&& session_id_from_extensions(&context.extensions).is_none();
let (started, session_handle) = if modern {
let (started, handle) = self.resolve_modern_session(provided_handle).await?;
(started, Some(handle))
} else {
(self.learn_session_from_request(&context).await?, None)
};
started.session.touch(tokio::time::Instant::now()).await;
started.session.mark_used();
let concurrent_used_sessions = self.state.sessions.used_count().await.max(1);
let tool_started_at = tokio::time::Instant::now();
let tool_name = request.name.to_string();
let result = if is_name_session {
Ok(self.call_name_session(&started, &raw_args).await)
} else if is_save_skill {
Ok(self.call_save_skill(&started, &raw_args).await)
} else if is_mark_skill_run {
Ok(self.call_mark_skill_run(&started, &raw_args).await)
} else {
let Some(tool_index) = tool_index else {
unreachable!("catalog tool was validated before session resolution");
};
let browser_session = self.state.browser.session().await;
let ownership_key = started.session.convo_id().clone();
let default_tab_group_id = self
.state
.sessions
.ownership()
.tab_group_ref(&ownership_key)
.await;
let dispatch_cancel = CancellationToken::new();
let cancel = linked_cancel_token(
started.session.child_token(),
context.ct.clone(),
dispatch_cancel.clone(),
);
let identity = ToolIdentity {
session: started.session.clone(),
agent: started.session.agent().clone(),
ownership_key,
agent_label: started.agent_label,
};
let call = ToolCall::new(
self.catalog.clone(),
tool_index,
raw_args,
started.session.id().clone(),
Some(identity),
browser_session,
cancel,
context.ct.clone(),
dispatch_cancel,
default_tab_group_id,
self.state.clone(),
self.output_files.clone(),
);
dispatch_tool_call(call).await
};
let finished = finish_tool_call(
started.session.as_ref(),
&tool_name,
tool_started_at,
concurrent_used_sessions,
result,
)
.await;
attach_session_handle(finished, session_handle).map(Into::into)
}
}
async fn finish_tool_call(
session: &Session,
tool_name: &str,
started_at: tokio::time::Instant,
concurrent_used_sessions: usize,
result: Result<CallToolResult, McpError>,
) -> Result<CallToolResult, McpError> {
session
.record_tool_usage(tool_name, started_at.elapsed(), concurrent_used_sessions)
.await;
result
}
#[derive(Debug, PartialEq, Eq)]
struct SessionRename {
response: String,
}
async fn rename_session(
session: Option<&Session>,
raw_args: &Value,
) -> Result<SessionRename, &'static str> {
let Some(session) = session else {
return Err("unable to resolve this session");
};
let Some(raw_name) = raw_args.get("name").and_then(Value::as_str) else {
return Err("name must be a string");
};
if raw_name.chars().count() > NAME_SESSION_INPUT_MAX_LEN {
return Err("name must be at most 64 characters");
}
let label = normalize_small_name(raw_name);
if label.is_empty() {
return Err("name must contain a usable session name");
}
let prefix = client_prefix_from_slug(session.agent().slug());
let old_label = session.rename(label.clone()).await;
let old_title = build_session_group_title(prefix, &old_label);
let new_title = build_session_group_title(prefix, &label);
Ok(SessionRename {
response: format!("renamed to {new_title} (was {old_title})"),
})
}
/// Best-effort structural PII scrub for an agent-provided task summary before it is
/// stored and indexed for search: drops any whitespace token that looks like an email,
/// URL, file path, bare domain/filename, or a long digit run (phone / card / account
/// number). Collapses whitespace and caps the length. Free prose and names are kept;
/// the agent is instructed to omit those, and the summary never leaves this machine.
fn scrub_summary(raw: &str) -> String {
let scrubbed = raw
.split_whitespace()
.filter(|token| !is_pii_token(token))
.collect::<Vec<_>>()
.join(" ");
if scrubbed.chars().count() > SUMMARY_MAX_LEN {
scrubbed
.chars()
.take(SUMMARY_MAX_LEN)
.collect::<String>()
.trim_end()
.to_string()
} else {
scrubbed
}
}
/// Clones the tool arguments with the `summary` field replaced by its already-scrubbed
/// form, so the audit dispatch timeline persists the sanitized summary rather than the raw
/// one the scrubber removed from `tasks.task_summary` and the search index.
fn with_scrubbed_summary(raw_args: &Value, clean: &str) -> Value {
let mut owned = raw_args.clone();
if let Some(object) = owned.as_object_mut() {
object.insert("summary".to_string(), Value::String(clean.to_string()));
}
owned
}
fn is_pii_token(token: &str) -> bool {
let lower = token.to_ascii_lowercase();
if token.contains('@')
|| lower.contains("://")
|| lower.starts_with("www.")
|| token.contains('/')
|| token.contains('\\')
{
return true;
}
if token.chars().filter(|c| c.is_ascii_digit()).count() >= 7 {
return true;
}
// bare domains / filenames: example.com, crm.internal.acme.com, report.pdf
if let Some((prefix, suffix)) = lower.rsplit_once('.') {
return !prefix.is_empty()
&& (2..=24).contains(&suffix.len())
&& suffix.chars().all(|c| c.is_ascii_alphabetic());
}
false
}
fn name_session_tool() -> Tool {
let Value::Object(input_schema) = json!({
"type": "object",
"properties": {
"name": { "type": "string", "maxLength": NAME_SESSION_INPUT_MAX_LEN },
"category": {
"type": "string",
"enum": crate::analytics::events::TASK_CATEGORY_VALUES,
"description": NAME_SESSION_CATEGORY_DESCRIPTION
},
"summary": {
"type": "string",
"maxLength": SUMMARY_MAX_LEN,
"description": NAME_SESSION_SUMMARY_DESCRIPTION
}
},
"required": ["name"]
}) else {
unreachable!();
};
Tool::new(
NAME_SESSION_TOOL_NAME,
NAME_SESSION_DESCRIPTION,
input_schema,
)
.with_annotations(
ToolAnnotations::with_title("Name session")
.read_only(false)
.destructive(false)
.idempotent(true),
)
}
fn save_skill_tool() -> Tool {
let Value::Object(input_schema) = json!({
"type": "object",
"properties": {
"name": { "type": "string", "pattern": "^[a-z0-9-]+$" },
"description": { "type": "string" },
"steps": { "type": "array", "items": { "type": "string" } },
"learnedNotes": { "type": "array", "items": { "type": "string" } },
"site": { "type": "string" }
},
"required": ["name", "description"]
}) else {
unreachable!();
};
Tool::new(SAVE_SKILL_TOOL_NAME, SAVE_SKILL_DESCRIPTION, input_schema).with_annotations(
ToolAnnotations::with_title("Save skill")
.read_only(false)
.destructive(false)
.idempotent(true),
)
}
fn mark_skill_run_tool() -> Tool {
let Value::Object(input_schema) = json!({
"type": "object",
"properties": {
"name": { "type": "string", "pattern": "^[a-z0-9-]+$" }
},
"required": ["name"]
}) else {
unreachable!();
};
Tool::new(
MARK_SKILL_RUN_TOOL_NAME,
MARK_SKILL_RUN_DESCRIPTION,
input_schema,
)
.with_annotations(
ToolAnnotations::with_title("Mark skill run")
.read_only(false)
.destructive(false)
.idempotent(true),
)
}
fn parse_skill_name(raw_args: &Value) -> Result<String, String> {
raw_args
.get("name")
.and_then(Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.map(str::to_string)
.ok_or_else(|| "name must be a non-empty string".to_string())
}
fn parse_save_skill(raw_args: &Value, session_id: String) -> Result<CreateSkill, String> {
let name = raw_args
.get("name")
.and_then(Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.ok_or("name must be a non-empty string")?
.to_string();
let description = raw_args
.get("description")
.and_then(Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.ok_or("description must be a non-empty string")?
.to_string();
let steps = parse_string_array(raw_args.get("steps"), "steps")?;
let learned_notes = parse_string_array(raw_args.get("learnedNotes"), "learnedNotes")?;
let site = raw_args
.get("site")
.and_then(Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.map(str::to_string);
Ok(CreateSkill {
name,
description,
site,
steps,
learned_notes,
origin: SkillOrigin::Agent,
source_session_id: Some(session_id),
})
}
fn parse_string_array(value: Option<&Value>, field: &str) -> Result<Vec<String>, String> {
match value {
None | Some(Value::Null) => Ok(Vec::new()),
Some(Value::Array(items)) => items
.iter()
.map(|item| {
item.as_str()
.map(str::to_string)
.ok_or_else(|| format!("{field} entries must be strings"))
})
.collect(),
Some(_) => Err(format!("{field} must be an array of strings")),
}
}
fn clean_client_field(value: &str, fallback: &str) -> String {
let trimmed = value.trim();
if trimmed.is_empty() {
fallback.to_string()
} else {
trimmed.to_string()
}
}
async fn finish_local_dispatch(
session: &Session,
dispatch_id: &DispatchId,
result: ToolResult,
) -> ToolResult {
if !session.finish_dispatch(dispatch_id).await && session.operator_stop_requested() {
operator_cancellation_result()
} else {
result
}
}
fn started_session_from(session: Arc<Session>, client: &ClientInfo) -> StartedSession {
let agent_label = client
.title
.as_deref()
.filter(|value| !value.is_empty())
.or_else(|| (!client.name.is_empty()).then_some(client.name.as_str()))
.unwrap_or_else(|| session.agent().slug())
.to_string();
StartedSession {
session,
agent_label,
}
}
fn with_session_arg(mut tool: Tool) -> Tool {
let mut schema = tool.input_schema.as_ref().clone();
let properties = schema
.entry("properties")
.or_insert_with(|| Value::Object(JsonObject::new()));
if let Value::Object(properties) = properties {
properties.insert(
"session".to_string(),
json!({ "type": "string", "description": SESSION_ARG_DESCRIPTION }),
);
}
tool.input_schema = Arc::new(schema);
tool
}
fn attach_session_handle(
result: Result<CallToolResult, McpError>,
handle: Option<SessionId>,
) -> Result<CallToolResult, McpError> {
let Some(handle) = handle else {
return result;
};
result.map(|mut call_result| {
let handle = handle.to_string();
match &mut call_result.structured_content {
Some(Value::Object(map)) => {
map.insert("session".to_string(), Value::String(handle));
}
_ => {
call_result.structured_content = Some(json!({ "session": handle }));
}
}
call_result
})
}
fn session_id_from_extensions(extensions: &rmcp::model::Extensions) -> Option<SessionId> {
extensions
.get::<axum::http::request::Parts>()
.and_then(|parts| parts.headers.get("mcp-session-id"))
.and_then(|value| value.to_str().ok())
.map(str::trim)
.filter(|value| !value.is_empty())
.map(SessionId::new)
}
fn protocol_version_from_extensions(
extensions: &rmcp::model::Extensions,
) -> Option<ProtocolVersion> {
extensions
.get::<axum::http::request::Parts>()
.and_then(|parts| parts.headers.get("mcp-protocol-version"))
.and_then(|value| value.to_str().ok())
.map(str::trim)
.filter(|value| !value.is_empty())
.and_then(protocol_version_from_str)
}
fn protocol_version_from_str(value: &str) -> Option<ProtocolVersion> {
match value {
"2026-07-28" => Some(ProtocolVersion::V_2026_07_28),
"2025-11-25" => Some(ProtocolVersion::V_2025_11_25),
"2025-06-18" => Some(ProtocolVersion::V_2025_06_18),
"2025-03-26" => Some(ProtocolVersion::V_2025_03_26),
"2024-11-05" => Some(ProtocolVersion::V_2024_11_05),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::identity::ConversationIdentity;
use rmcp::handler::server::ServerHandler;
use serde_json::json;
#[test]
fn supported_protocol_versions_includes_modern_and_legacy() {
assert!(SUPPORTED_PROTOCOL_VERSIONS.contains(&ProtocolVersion::V_2026_07_28));
assert!(SUPPORTED_PROTOCOL_VERSIONS.contains(&ProtocolVersion::V_2025_11_25));
}
#[tokio::test]
async fn with_session_arg_adds_an_optional_session_property_to_every_tool() -> anyhow::Result<()>
{