Repository navigation #
Expand file tree #
/
Copy path
More file actions
5256 lines (4849 loc) · 219 KB /
Copy path
File metadata and controls #
5256 lines (4849 loc) · 219 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
//! MCP server integration using the official rmcp SDK.
use std::collections::HashMap;
use std::ffi::OsString;
use std::future::Future;
use std::sync::{Arc, LazyLock};
use xai_grok_config::BearerTokenPath;
use xai_grok_telemetry::region;
use xai_grok_telemetry::region::Parent;
use agent_client_protocol as acp;
use tokio::{
io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader},
process::{ChildStderr, Command},
sync::{Mutex, Notify},
};
use rmcp::{
ClientHandler, ClientLifecycleMode, ClientServiceExt,
model::{
CallToolRequestParams, ClientCapabilities, ClientConfig, Implementation,
PaginatedRequestParams,
},
service::{
ClientInitializeError, NotificationContext, RequestContext, RoleClient, RunningService,
ServiceError,
},
service::{RxJsonRpcMessage, TxJsonRpcMessage},
transport::{
StreamableHttpClientTransport, Transport,
streamable_http_client::StreamableHttpClientTransportConfig,
},
};
pub use crate::auth_status::McpOauthDiscovery;
use crate::auth_status::{HttpAuthDecision, decide_http_auth_from_disk};
use crate::bearer_token_file::BearerTokenFile;
use crate::call_result::mcp_output_from_call_result;
pub use crate::generation::{Generation, Replacement, Superseded};
use crate::oauth::OAUTH_DISCOVERY_TIMEOUT;
use crate::oauth_config::McpOAuthConfig;
pub use crate::shared_mcp_state::SharedMcpState;
use xai_grok_tools::types::{
output::{MCPOutputDetails, ToolOutput},
tool::{ToolKind, ToolNamespace},
tool_metadata::ToolMetadata,
};
use xai_grok_tools::util::{ProcessGroup, ProcessScope};
pub use crate::tool_name::{
MCP_QUALIFIED_NAME_MAX_CHARS, McpToolAdmissionError, PROVIDER_TOOL_NAME_MAX_CHARS,
parse_mcp_qualified_name, parse_mcp_tool_name, qualify_mcp_tool_name, validate_tool_name,
};
/// MCP tool name delimiter: server names are qualified as `"server__tool"`.
/// Canonical definition lives in `xai_grok_workspace_types`; re-exported here for callers that historically imported it from this module.
pub use xai_grok_workspace_types::MCP_TOOL_NAME_DELIMITER;
/// Routing hint for first-party local app MCP endpoints: which agent/session a request belongs to. **Advisory only, never authentication** — any local process can set it, so receivers must not treat it as proof of identity.
/// Caller-supplied configs cannot smuggle it: the header is stripped from every HTTP/SSE config and re-added only when the spawn context asks for it (mirroring the `GROK_SESSION_ID` env protection on stdio servers).
pub const GROK_AGENT_ID_HEADER: &str = "X-Grok-Agent-ID";
/// Reqwest 0.13 twin of the 0.12 adapters in `xai_grok_extra_ca`.
fn with_extra_root_certificates(mut builder: reqwest::ClientBuilder) -> reqwest::ClientBuilder {
xai_grok_extra_ca::ensure_default_crypto_provider();
builder = builder.tls_backend_rustls();
for der in xai_grok_extra_ca::extra_root_ders() {
match reqwest::Certificate::from_der(der) {
Ok(cert) => builder = builder.add_root_certificate(cert),
Err(e) => tracing::warn!(
error = %e,
"extra CA bundle: validated DER rejected by reqwest 0.13; skipping cert"
),
}
}
builder
}
/// Max protocol icons kept per server/tool at ingest.
pub const MAX_MCP_ICONS_PER_ENTITY: usize = 8;
/// Max bytes for a single icon `src` (including data URIs) at ingest.
pub const MAX_MCP_ICON_SRC_BYTES: usize = 64 * 1024;
/// Max bytes for a single icon `mime_type` string at ingest.
pub const MAX_MCP_ICON_MIME_TYPE_BYTES: usize = 128;
/// Max size tokens kept per icon (`48x48`, `any`, …) at ingest.
pub const MAX_MCP_ICON_SIZES: usize = 8;
/// Max bytes for a single size token at ingest.
pub const MAX_MCP_ICON_SIZE_TOKEN_BYTES: usize = 32;
/// Wire theme for MCP protocol icons.
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum McpIconTheme {
Light,
Dark,
#[serde(other)]
Unknown,
}
/// ACP-facing MCP protocol icon (SEP-973), mirrored from rmcp so clients never depend on the quarantined SDK types.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct McpIcon {
pub src: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mime_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sizes: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub theme: Option<McpIconTheme>,
}
impl McpIcon {
/// Convert an rmcp icon with ingest rules: trim `src`, allow only `https://` and `data:image/…`, drop empty/oversized values.
pub fn from_rmcp(icon: rmcp::model::Icon) -> Option<Self> {
let src = icon.src.trim();
if src.is_empty() || src.len() > MAX_MCP_ICON_SRC_BYTES {
return None;
}
if !is_allowed_mcp_icon_src(src) {
return None;
}
let theme = match icon.theme {
Some(rmcp::model::IconTheme::Light) => Some(McpIconTheme::Light),
Some(rmcp::model::IconTheme::Dark) => Some(McpIconTheme::Dark),
_ => None,
};
let mime_type = icon.mime_type.and_then(|mime| {
let mime = mime.trim();
if mime.is_empty() || mime.len() > MAX_MCP_ICON_MIME_TYPE_BYTES {
None
} else {
Some(mime.to_owned())
}
});
let sizes = icon.sizes.map(|sizes| {
sizes
.into_iter()
.filter_map(|size| {
let size = size.trim();
if size.is_empty() || size.len() > MAX_MCP_ICON_SIZE_TOKEN_BYTES {
None
} else {
Some(size.to_owned())
}
})
.take(MAX_MCP_ICON_SIZES)
.collect::<Vec<_>>()
});
let sizes = sizes.filter(|sizes| !sizes.is_empty());
Some(Self {
src: src.to_owned(),
mime_type,
sizes,
theme,
})
}
pub fn from_rmcp_list(icons: Option<Vec<rmcp::model::Icon>>) -> Vec<Self> {
icons
.unwrap_or_default()
.into_iter()
.filter_map(Self::from_rmcp)
.take(MAX_MCP_ICONS_PER_ENTITY)
.collect()
}
}
fn is_allowed_mcp_icon_src(src: &str) -> bool {
src.starts_with("data:image/") || src.starts_with("https://")
}
/// Sanitize an MCP server or tool name into a single safe path segment (e.g. `"user-Hugging Face"` becomes `user-Hugging_Face`).
/// Shared so the per-server folder advertised in the prompt matches the tool files on disk.
pub fn sanitize_descriptor_segment(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' {
out.push(c);
} else {
out.push('_');
}
}
if out.is_empty() {
out.push('_');
}
out
}
/// Result of a diff-based MCP config update.
#[derive(Debug)]
pub struct McpConfigDiff {
/// Server names that are new or had their config changed.
pub added: Vec<McpServerName>,
/// Server names that were removed or had their config changed (old instance torn down).
pub removed: Vec<McpServerName>,
/// Server names whose config is identical, so their clients stay alive.
pub retained: Vec<McpServerName>,
}
/// A server-set change together with the claim for the pass that covers it, taken in one critical section.
#[must_use = "dropping the change releases the successor pass's claim"]
pub struct McpConfigChange {
pub diff: McpConfigDiff,
pub claim: InitClaimGuard,
}
/// MCP server name used as the key in client/tool maps (e.g. `"github"`, `"grok_com_linear"`).
pub type McpServerName = String;
/// Unqualified MCP tool name (e.g. `"create_issue"`, without the `server__` prefix).
type ToolName = String;
/// Init state. `Starting` precedes `finish_init`, which fires early so the session is not blocked on MCP; `Finished`
/// may still have handshakes draining; `Complete` is set by the pass once its last publication has landed.
#[derive(Debug, Default)]
pub enum InitProgress {
#[default]
NotStarted,
Starting {
/// Set once mark_handshaking has seeded the set.
seeded: bool,
handshaking: std::collections::HashSet<McpServerName>,
},
Finished {
handshaking: std::collections::HashSet<McpServerName>,
},
Complete,
}
impl InitProgress {
pub fn is_complete(&self) -> bool {
matches!(self, Self::Complete)
}
/// Init work is outstanding, including the pass's final publication.
pub fn is_in_progress(&self) -> bool {
matches!(self, Self::Starting { .. } | Self::Finished { .. })
}
/// True iff `finish_init` has fired, regardless of whether background handshakes are still draining.
/// Used for diagnostic logging that tells the pre-finish window apart from finished with handshakes still draining.
pub fn has_finished_init(&self) -> bool {
matches!(self, Self::Finished { .. } | Self::Complete)
}
/// True iff the named server is currently handshaking.
pub fn is_server_handshaking(&self, name: &str) -> bool {
match self {
Self::Starting { handshaking, .. } | Self::Finished { handshaking } => {
handshaking.contains(name)
}
Self::NotStarted | Self::Complete => false,
}
}
/// Iterate over server names whose background handshake is still in flight.
/// Empty when [`Self::NotStarted`] or fully complete.
pub fn handshaking_servers(&self) -> impl Iterator<Item = &McpServerName> {
match self {
Self::Starting { handshaking, .. } | Self::Finished { handshaking } => {
Some(handshaking.iter())
}
Self::NotStarted | Self::Complete => None,
}
.into_iter()
.flatten()
}
/// Number of in-flight per-server handshakes.
pub fn handshaking_count(&self) -> usize {
match self {
Self::Starting { handshaking, .. } | Self::Finished { handshaking } => {
handshaking.len()
}
Self::NotStarted | Self::Complete => 0,
}
}
/// Transition `Starting` to `Finished`, preserving the handshaking set.
/// No-op if already `Finished`; warns and stays put if called from `NotStarted`, which would be a caller bug.
pub fn finish(&mut self) {
match self {
Self::Starting { handshaking, .. } => {
// Move only the inner set, leaving the outer `&mut self` ready to be reassigned
// `mem::take(self)` would force a `NotStarted` placeholder and a redundant put-back in the already-Finished arm below
let handshaking = std::mem::take(handshaking);
*self = Self::Finished { handshaking };
}
// Idempotent: already past the finish boundary
// Per-server handshakes continue draining via `mark_handshake_complete`
Self::Finished { .. } | Self::Complete => {}
Self::NotStarted => {
tracing::warn!(
"InitProgress::finish called from NotStarted; staying in NotStarted"
);
}
}
}
pub fn complete(&mut self) {
*self = Self::Complete;
}
/// Transition any state to `NotStarted`, clearing all per-server progress.
/// Used on generation mismatch (config change racing active init) and on full reset.
pub fn cancel(&mut self) {
*self = Self::NotStarted;
}
/// Add names to the handshaking set; only meaningful in `Starting` or `Finished`.
/// Warns if called from `NotStarted`: a handshake starting without `try_start_init` is a caller bug.
pub fn mark_handshaking(&mut self, names: impl IntoIterator<Item = McpServerName>) {
match self {
Self::Starting {
seeded,
handshaking,
} => {
*seeded = true;
handshaking.extend(names);
}
Self::Finished { handshaking } => {
handshaking.extend(names);
}
Self::NotStarted | Self::Complete => {
tracing::warn!("InitProgress::mark_handshaking called outside a pass; ignoring");
}
}
}
/// Remove a server from the handshaking set (on success or failure of its handshake).
/// No-op if not present or if `NotStarted`.
pub fn mark_handshake_complete(&mut self, name: &str) {
match self {
Self::Starting { handshaking, .. } | Self::Finished { handshaking } => {
handshaking.remove(name);
}
Self::NotStarted | Self::Complete => {}
}
}
}
/// One in-process SDK MCP server registration: its tool-namespace name and the SDK-side id echoed back in `x.ai/mcp/sdk_call`.
/// A named struct (rather than a `(String, String)` tuple) so callers can't transpose the two strings.
/// `Deserialize` d from a `_meta["x.ai/mcp/servers"]` entry, so the `serverId` wire field name is declared (and serde-checked) exactly once here.
#[derive(Debug, Clone, serde::Deserialize)]
pub struct AcpServerEntry {
pub name: McpServerName,
#[serde(rename = "serverId")]
pub server_id: String,
}
/// The session's in-process SDK MCP servers (declared via `_meta["x.ai/mcp/servers"]`), bundled with the shared reverse-RPC invoker.
/// The registry survives `update_configs` clears; config reloads only touch `configs`/` owned_clients`.
struct AcpMcpRegistry {
/// Registered servers (`name -> serverId`).
servers: Vec<AcpServerEntry>,
/// Shared reverse-RPC invoker all these servers' tools are called through (emits `x.ai/mcp/sdk_call` over the ACP connection).
invoker: Arc<dyn crate::acp_transport::AcpReverseInvoker>,
}
/// `Cooling` waits out the backoff; `InFlight` marks a running respawn attempt and carries the token that attempt must present to settle.
/// An in-flight server is never handed to another trigger, and a token invalidated by config teardown makes the stale attempt's results unusable.
#[derive(Debug, Clone, Copy)]
enum UnreachableRetry {
Cooling {
retry_at: std::time::Instant,
},
InFlight {
token: u64,
started_at: std::time::Instant,
},
}
/// Ownership of init. [`McpState`] keeps only a `Weak` to it, so a dropped pass releases ownership and the next
/// waiter re-owns.
#[must_use = "dropping the guard releases init ownership"]
pub struct InitClaimGuard {
token: std::sync::Arc<()>,
signal: std::sync::Arc<tokio::sync::Notify>,
}
impl Drop for InitClaimGuard {
fn drop(&mut self) {
self.signal.notify_waiters();
}
}
/// Admitted server list shared with the session handle.
///
/// `update_configs` and `update_configs_diff` publish into this cell, so a