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
use arc_swap::ArcSwapOption;
pub use mcp_common::ToolFilter;
/**
* Create a local SSE server that proxies requests to a stdio MCP server.
*/
use rmcp::{
ErrorData, RoleClient, RoleServer, ServerHandler,
model::{
CallToolRequestParam, CallToolResult, ClientInfo, Content, Implementation, ListToolsResult,
PaginatedRequestParam, ProtocolVersion, ServerInfo,
},
service::{NotificationContext, Peer, RequestContext, RunningService},
};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Instant, SystemTime};
use tracing::{debug, error, info, warn};
/// 全局请求计数器,用于生成唯一的请求 ID
static REQUEST_COUNTER: AtomicU64 = AtomicU64::new(1);
/// 包装后端连接和运行服务
/// 用于 ArcSwap 热替换
#[derive(Debug)]
struct PeerInner {
/// Peer 用于发送请求
peer: Peer<RoleClient>,
/// 保持 RunningService 的所有权,确保服务生命周期
#[allow(dead_code)]
_running: Arc<RunningService<RoleClient, ClientInfo>>,
}
/// A SSE proxy handler that forwards requests to a client based on the server's capabilities
/// 使用 ArcSwap 实现后端热替换,支持断开时立即返回错误
///
/// **SSE 模式**:使用 rmcp 0.10,稳定的 SSE 传输协议
#[derive(Clone, Debug)]
pub struct SseHandler {
/// 后端连接(ArcSwap 支持无锁原子替换)
/// None 表示后端断开/重连中
peer: Arc<ArcSwapOption<PeerInner>>,
/// 缓存的服务器信息(保持不变,重连后应一致)
cached_info: ServerInfo,
/// MCP ID 用于日志记录
mcp_id: String,
/// 工具过滤配置
tool_filter: ToolFilter,
}
impl ServerHandler for SseHandler {
fn get_info(&self) -> ServerInfo {
self.cached_info.clone()
}
#[tracing::instrument(skip(self, request, context), fields(
mcp_id = %self.mcp_id,
request = ?request,
))]
async fn list_tools(
&self,
request: Option<PaginatedRequestParam>,
context: RequestContext<RoleServer>,
) -> Result<ListToolsResult, ErrorData> {
// 原子加载后端连接
let inner_guard = self.peer.load();
let inner = inner_guard.as_ref().ok_or_else(|| {
error!("Backend connection is not available (reconnecting)");
ErrorData::internal_error(
"Backend connection is not availabletemp/rust-sdk, reconnecting...".to_string(),
None,
)
})?;
// 检查后端连接是否已关闭
if inner.peer.is_transport_closed() {
error!("Backend transport is closed");
return Err(ErrorData::internal_error(
"Backend connection closed, please retry".to_string(),
None,
));
}
// Check if the server has tools capability and forward the request
match self.capabilities().tools {
Some(_) => {
// 使用 tokio::select! 同时等待取消和结果
tokio::select! {
result = inner.peer.list_tools(request) => {
match result {
Ok(result) => {
// 根据过滤配置过滤工具列表
let filtered_tools: Vec<_> = if self.tool_filter.is_enabled() {
result
.tools
.into_iter()
.filter(|tool| self.tool_filter.is_allowed(&tool.name))
.collect()
} else {
result.tools
};
// 记录工具列表结果,这些结果会通过 SSE 推送给客户端
info!(
"[list_tools] Tool list results - MCP ID: {}, number of tools: {}{}",
self.mcp_id,
filtered_tools.len(),
if self.tool_filter.is_enabled() {
" (filtered)"
} else {
""
}
);
debug!(
"Proxying list_tools response with {} tools",
filtered_tools.len()
);
Ok(ListToolsResult {
tools: filtered_tools,
next_cursor: result.next_cursor,
})
}
Err(err) => {
error!("Error listing tools: {:?}", err);
Err(ErrorData::internal_error(
format!("Error listing tools: {err}"),
None,
))
}
}
}
_ = context.ct.cancelled() => {
info!("[list_tools] Request canceled - MCP ID: {}", self.mcp_id);
Err(ErrorData::internal_error(
"Request cancelled".to_string(),
None,
))
}
}
}
None => {
// Server doesn't support tools, return empty list
warn!("Server doesn't support tools capability");
Ok(ListToolsResult::default())
}
}
}
#[tracing::instrument(skip(self, request, context), fields(
mcp_id = %self.mcp_id,
tool_name = %request.name,
tool_arguments = ?request.arguments,
))]
async fn call_tool(
&self,
request: CallToolRequestParam,
context: RequestContext<RoleServer>,
) -> Result<CallToolResult, ErrorData> {
// 生成唯一请求 ID 用于追踪
let request_id = REQUEST_COUNTER.fetch_add(1, Ordering::Relaxed);
let start = Instant::now();
let start_time = SystemTime::now();
info!(
"[call_tool:{}] Start - Tool: {}, MCP ID: {}, Time: {:?}",
request_id, request.name, self.mcp_id, start_time
);
// 首先检查工具是否被过滤
if !self.tool_filter.is_allowed(&request.name) {
info!(
"[call_tool:{}] Tool is filtered - MCP ID: {}, Tool: {}",
request_id, self.mcp_id, request.name
);
return Ok(CallToolResult::error(vec![Content::text(format!(
"Tool '{}' is not allowed by filter configuration",
request.name
))]));
}
// 原子加载后端连接
let inner_guard = self.peer.load();
let inner = match inner_guard.as_ref() {
Some(inner) => {
let transport_closed = inner.peer.is_transport_closed();
info!(
"[call_tool:{}] Backend connection exists - transport_closed: {}",
request_id, transport_closed
);
inner
}
None => {
error!(
"[call_tool:{}] Backend connection unavailable (reconnecting) - MCP ID: {}",
request_id, self.mcp_id
);
return Ok(CallToolResult::error(vec![Content::text(
"Backend connection is not available, reconnecting...",
)]));
}
};
// 检查后端连接是否已关闭
if inner.peer.is_transport_closed() {
error!(
"[call_tool:{}] Backend transport is closed - MCP ID: {}",
request_id, self.mcp_id
);
return Ok(CallToolResult::error(vec![Content::text(
"Backend connection closed, please retry",
)]));
}
// Check if the server has tools capability and forward the request
let result = match self.capabilities().tools {
Some(_) => {
// 记录发送请求到后端的时间点
info!(
"[call_tool:{}] Send request to backend... - Tool: {}, Elapsed time: {}ms",
request_id,
request.name,
start.elapsed().as_millis()
);
// 使用 tokio::select! 同时等待取消和结果
tokio::select! {
result = inner.peer.call_tool(request.clone()) => {
let elapsed = start.elapsed();
match &result {
Ok(call_result) => {
// 记录工具调用结果,这些结果会通过 SSE 推送给客户端
let is_error = call_result.is_error.unwrap_or(false);
info!(
"[call_tool:{}] Response received - tool: {}, time taken: {}ms, is_error: {}, MCP ID: {}",
request_id, request.name, elapsed.as_millis(), is_error, self.mcp_id
);
if is_error {
// 记录错误响应的内容(用于调试)
debug!(
"[call_tool:{}] Error response content: {:?}",
request_id, call_result.content
);
}
Ok(call_result.clone())
}
Err(err) => {
error!(
"[call_tool:{}] Backend returns error - Tool: {}, Time: {}ms, Error: {:?}, MCP ID: {}",
request_id, request.name, elapsed.as_millis(), err, self.mcp_id
);
// Return an error result instead of propagating the error
Ok(CallToolResult::error(vec![Content::text(format!(
"Error: {err}"
))]))
}
}
}
_ = context.ct.cancelled() => {
let elapsed = start.elapsed();
warn!(
"[call_tool:{}] Request canceled - Tool: {}, Time taken: {}ms, MCP ID: {}",
request_id, request.name, elapsed.as_millis(), self.mcp_id
);
Ok(CallToolResult::error(vec![Content::text(
"Request cancelled"
)]))
}
}
}
None => {
error!(
"[call_tool:{}] The server does not support tools capability - MCP ID: {}",
request_id, self.mcp_id
);
Ok(CallToolResult::error(vec![Content::text(
"Server doesn't support tools capability",
)]))
}
};
let total_elapsed = start.elapsed();
info!(
"[call_tool:{}] Completed - Tool: {}, total time taken: {}ms",
request_id,
request.name,
total_elapsed.as_millis()
);
result
}
async fn list_resources(
&self,
request: Option<PaginatedRequestParam>,
context: RequestContext<RoleServer>,
) -> Result<rmcp::model::ListResourcesResult, ErrorData> {
// 原子加载后端连接
let inner_guard = self.peer.load();
let inner = inner_guard.as_ref().ok_or_else(|| {
error!("Backend connection is not available (reconnecting)");
ErrorData::internal_error(
"Backend connection is not available, reconnecting...".to_string(),
None,
)
})?;
// 检查后端连接是否已关闭
if inner.peer.is_transport_closed() {
error!("Backend transport is closed");
return Err(ErrorData::internal_error(
"Backend connection closed, please retry".to_string(),
None,
));
}
// Check if the server has resources capability and forward the request
match self.capabilities().resources {
Some(_) => {
tokio::select! {
result = inner.peer.list_resources(request) => {
match result {
Ok(result) => {
// 记录资源列表结果,这些结果会通过 SSE 推送给客户端
info!(
"[list_resources] Resource list results - MCP ID: {}, resource quantity: {}",
self.mcp_id,
result.resources.len()
);
debug!("Proxying list_resources response");
Ok(result)
}
Err(err) => {
error!("Error listing resources: {:?}", err);
Err(ErrorData::internal_error(
format!("Error listing resources: {err}"),
None,
))
}
}
}
_ = context.ct.cancelled() => {
info!("[list_resources] Request canceled - MCP ID: {}", self.mcp_id);
Err(ErrorData::internal_error(
"Request cancelled".to_string(),
None,
))
}
}
}
None => {
// Server doesn't support resources, return empty list
warn!("Server doesn't support resources capability");
Ok(rmcp::model::ListResourcesResult::default())
}
}
}
async fn read_resource(
&self,
request: rmcp::model::ReadResourceRequestParam,
context: RequestContext<RoleServer>,
) -> Result<rmcp::model::ReadResourceResult, ErrorData> {
// 原子加载后端连接
let inner_guard = self.peer.load();
let inner = inner_guard.as_ref().ok_or_else(|| {
error!("Backend connection is not available (reconnecting)");
ErrorData::internal_error(
"Backend connection is not available, reconnecting...".to_string(),
None,
)
})?;
// 检查后端连接是否已关闭
if inner.peer.is_transport_closed() {
error!("Backend transport is closed");
return Err(ErrorData::internal_error(
"Backend connection closed, please retry".to_string(),
None,
));
}
// Check if the server has resources capability and forward the request
match self.capabilities().resources {
Some(_) => {
tokio::select! {
result = inner.peer.read_resource(rmcp::model::ReadResourceRequestParam {
uri: request.uri.clone(),
}) => {
match result {
Ok(result) => {
// 记录资源读取结果,这些结果会通过 SSE 推送给客户端
info!(
"[read_resource] Resource read result - MCP ID: {}, URI: {}",
self.mcp_id, request.uri
);
debug!("Proxying read_resource response for {}", request.uri);
Ok(result)
}
Err(err) => {
error!("Error reading resource: {:?}", err);
Err(ErrorData::internal_error(
format!("Error reading resource: {err}"),
None,
))
}
}
}
_ = context.ct.cancelled() => {
info!("[read_resource] Request canceled - MCP ID: {}, URI: {}", self.mcp_id, request.uri);
Err(ErrorData::internal_error(
"Request cancelled".to_string(),
None,
))
}
}
}
None => {
// Server doesn't support resources, return error
error!("Server doesn't support resources capability");
Ok(rmcp::model::ReadResourceResult {
contents: Vec::new(),
})
}
}
}
async fn list_resource_templates(
&self,
request: Option<PaginatedRequestParam>,
context: RequestContext<RoleServer>,
) -> Result<rmcp::model::ListResourceTemplatesResult, ErrorData> {
// 原子加载后端连接
let inner_guard = self.peer.load();
let inner = inner_guard.as_ref().ok_or_else(|| {
error!("Backend connection is not available (reconnecting)");
ErrorData::internal_error(
"Backend connection is not available, reconnecting...".to_string(),
None,
)
})?;
// 检查后端连接是否已关闭
if inner.peer.is_transport_closed() {
error!("Backend transport is closed");
return Err(ErrorData::internal_error(
"Backend connection closed, please retry".to_string(),
None,
));
}
// Check if the server has resources capability and forward the request
match self.capabilities().resources {
Some(_) => {
tokio::select! {
result = inner.peer.list_resource_templates(request) => {
match result {
Ok(result) => {
debug!("Proxying list_resource_templates response");
Ok(result)
}
Err(err) => {
error!("Error listing resource templates: {:?}", err);
Err(ErrorData::internal_error(
format!("Error listing resource templates: {err}"),
None,
))
}
}
}
_ = context.ct.cancelled() => {
info!("[list_resource_templates] request canceled - MCP ID: {}", self.mcp_id);
Err(ErrorData::internal_error(
"Request cancelled".to_string(),
None,
))
}
}
}
None => {
// Server doesn't support resources, return empty list
warn!("Server doesn't support resources capability");
Ok(rmcp::model::ListResourceTemplatesResult::default())
}
}
}
async fn list_prompts(
&self,
request: Option<PaginatedRequestParam>,
context: RequestContext<RoleServer>,
) -> Result<rmcp::model::ListPromptsResult, ErrorData> {
// 原子加载后端连接
let inner_guard = self.peer.load();
let inner = inner_guard.as_ref().ok_or_else(|| {
error!("Backend connection is not available (reconnecting)");
ErrorData::internal_error(
"Backend connection is not available, reconnecting...".to_string(),
None,
)
})?;
// 检查后端连接是否已关闭
if inner.peer.is_transport_closed() {
error!("Backend transport is closed");
return Err(ErrorData::internal_error(
"Backend connection closed, please retry".to_string(),
None,
));
}
// Check if the server has prompts capability and forward the request
match self.capabilities().prompts {
Some(_) => {
tokio::select! {
result = inner.peer.list_prompts(request) => {
match result {
Ok(result) => {
debug!("Proxying list_prompts response");
Ok(result)
}
Err(err) => {
error!("Error listing prompts: {:?}", err);
Err(ErrorData::internal_error(
format!("Error listing prompts: {err}"),
None,
))
}
}
}
_ = context.ct.cancelled() => {
info!("[list_prompts] Request canceled - MCP ID: {}", self.mcp_id);
Err(ErrorData::internal_error(
"Request cancelled".to_string(),
None,
))
}
}
}
None => {
// Server doesn't support prompts, return empty list
warn!("Server doesn't support prompts capability");
Ok(rmcp::model::ListPromptsResult::default())
}
}
}
async fn get_prompt(
&self,
request: rmcp::model::GetPromptRequestParam,
context: RequestContext<RoleServer>,
) -> Result<rmcp::model::GetPromptResult, ErrorData> {
// 原子加载后端连接
let inner_guard = self.peer.load();
let inner = inner_guard.as_ref().ok_or_else(|| {
error!("Backend connection is not available (reconnecting)");
ErrorData::internal_error(
"Backend connection is not available, reconnecting...".to_string(),
None,
)
})?;
// 检查后端连接是否已关闭
if inner.peer.is_transport_closed() {
error!("Backend transport is closed");
return Err(ErrorData::internal_error(
"Backend connection closed, please retry".to_string(),
None,
));
}
// Check if the server has prompts capability and forward the request
match self.capabilities().prompts {
Some(_) => {
tokio::select! {
result = inner.peer.get_prompt(request.clone()) => {
match result {
Ok(result) => {
debug!("Proxying get_prompt response");
Ok(result)
}
Err(err) => {
error!("Error getting prompt: {:?}", err);
Err(ErrorData::internal_error(
format!("Error getting prompt: {err}"),
None,
))
}
}
}
_ = context.ct.cancelled() => {
info!("[get_prompt] Request canceled - MCP ID: {}, prompt: {:?}", self.mcp_id, request.name);
Err(ErrorData::internal_error(
"Request cancelled".to_string(),
None,
))
}
}
}
None => {
// Server doesn't support prompts, return error
warn!("Server doesn't support prompts capability");
Ok(rmcp::model::GetPromptResult {
description: None,
messages: Vec::new(),
})
}
}
}
async fn complete(
&self,
request: rmcp::model::CompleteRequestParam,
context: RequestContext<RoleServer>,
) -> Result<rmcp::model::CompleteResult, ErrorData> {
// 原子加载后端连接
let inner_guard = self.peer.load();
let inner = inner_guard.as_ref().ok_or_else(|| {
error!("Backend connection is not available (reconnecting)");
ErrorData::internal_error(
"Backend connection is not available, reconnecting...".to_string(),
None,
)
})?;
// 检查后端连接是否已关闭
if inner.peer.is_transport_closed() {
error!("Backend transport is closed");
return Err(ErrorData::internal_error(
"Backend connection closed, please retry".to_string(),
None,
));
}
tokio::select! {
result = inner.peer.complete(request) => {
match result {
Ok(result) => {
debug!("Proxying complete response");
Ok(result)
}
Err(err) => {
error!("Error completing: {:?}", err);
Err(ErrorData::internal_error(
format!("Error completing: {err}"),
None,
))
}
}
}
_ = context.ct.cancelled() => {
info!("[complete] Request canceled - MCP ID: {}", self.mcp_id);
Err(ErrorData::internal_error(
"Request cancelled".to_string(),
None,
))
}
}
}
async fn on_progress(
&self,
notification: rmcp::model::ProgressNotificationParam,
_context: NotificationContext<RoleServer>,
) {
// 原子加载后端连接
let inner_guard = self.peer.load();
let inner = match inner_guard.as_ref() {
Some(inner) => inner,
None => {
error!("Backend connection is not available, cannot forward progress notification");
return;
}
};
// 检查后端连接是否已关闭
if inner.peer.is_transport_closed() {
error!("Backend transport is closed, cannot forward progress notification");
return;
}
match inner.peer.notify_progress(notification).await {
Ok(_) => {
debug!("Proxying progress notification");
}
Err(err) => {
error!("Error notifying progress: {:?}", err);
}
}
}
async fn on_cancelled(
&self,
notification: rmcp::model::CancelledNotificationParam,
_context: NotificationContext<RoleServer>,
) {
// 原子加载后端连接
let inner_guard = self.peer.load();
let inner = match inner_guard.as_ref() {
Some(inner) => inner,
None => {
error!(
"Backend connection is not available, cannot forward cancelled notification"
);
return;
}
};
// 检查后端连接是否已关闭
if inner.peer.is_transport_closed() {
error!("Backend transport is closed, cannot forward cancelled notification");
return;
}
match inner.peer.notify_cancelled(notification).await {
Ok(_) => {
debug!("Proxying cancelled notification");
}
Err(err) => {
error!("Error notifying cancelled: {:?}", err);
}
}
}
}
impl SseHandler {
/// 获取 capabilities 的引用,避免 clone
#[inline]
fn capabilities(&self) -> &rmcp::model::ServerCapabilities {
&self.cached_info.capabilities
}
/// 创建一个默认的 ServerInfo(用于断开状态)
fn default_server_info(mcp_id: &str) -> ServerInfo {
warn!(
"[SseHandler] Create default ServerInfo - MCP ID: {}",
mcp_id
);
ServerInfo {
protocol_version: ProtocolVersion::V_2024_11_05,
server_info: Implementation {
name: "MCP Proxy".to_string(),
version: "0.1.0".to_string(),
title: None,
website_url: None,
icons: None,
},
instructions: None,
capabilities: Default::default(),
}
}
/// 从 RunningService 提取 ServerInfo
fn extract_server_info(
client: &RunningService<RoleClient, ClientInfo>,
mcp_id: &str,
) -> ServerInfo {
client
.peer_info()
.map(|peer_info| ServerInfo {
protocol_version: peer_info.protocol_version.clone(),
server_info: Implementation {
name: peer_info.server_info.name.clone(),
version: peer_info.server_info.version.clone(),
title: None,
website_url: None,
icons: None,
},
instructions: peer_info.instructions.clone(),
capabilities: peer_info.capabilities.clone(),
})
.unwrap_or_else(|| Self::default_server_info(mcp_id))
}
/// 创建断开状态的 handler(用于初始化)
/// 后续通过 swap_backend() 注入实际的后端连接
pub fn new_disconnected(
mcp_id: String,
tool_filter: ToolFilter,
default_info: ServerInfo,
) -> Self {
info!(
"[SseHandler] Create a disconnected handler - MCP ID: {}",
mcp_id
);
// 记录过滤器配置
if tool_filter.is_enabled() {
if let Some(ref allow_list) = tool_filter.allow_tools {
info!(
"[SseHandler] Tool whitelist enabled - MCP ID: {}, allowed tools: {:?}",
mcp_id, allow_list
);
}
if let Some(ref deny_list) = tool_filter.deny_tools {
info!(
"[SseHandler] Tool blacklist enabled - MCP ID: {}, excluded tools: {:?}",
mcp_id, deny_list
);
}
}
Self {
peer: Arc::new(ArcSwapOption::empty()),
cached_info: default_info,
mcp_id,
tool_filter,
}
}
pub fn new(client: RunningService<RoleClient, ClientInfo>) -> Self {
Self::with_mcp_id(client, "unknown".to_string())
}
pub fn with_mcp_id(client: RunningService<RoleClient, ClientInfo>, mcp_id: String) -> Self {
Self::with_tool_filter(client, mcp_id, ToolFilter::default())
}
/// 创建带工具过滤器的 SseHandler(带初始后端连接)
pub fn with_tool_filter(
client: RunningService<RoleClient, ClientInfo>,
mcp_id: String,
tool_filter: ToolFilter,
) -> Self {
use std::ops::Deref;
// 提取 ServerInfo
let cached_info = Self::extract_server_info(&client, &mcp_id);
// 克隆 Peer 用于并发请求(无需锁)
let peer = client.deref().clone();
// 记录过滤器配置
if tool_filter.is_enabled() {
if let Some(ref allow_list) = tool_filter.allow_tools {
info!(
"[SseHandler] Tool whitelist enabled - MCP ID: {}, allowed tools: {:?}",
mcp_id, allow_list
);
}
if let Some(ref deny_list) = tool_filter.deny_tools {
info!(
"[SseHandler] Tool blacklist enabled - MCP ID: {}, excluded tools: {:?}",
mcp_id, deny_list
);
}
}
// 创建 PeerInner
let inner = PeerInner {
peer,
_running: Arc::new(client),
};
Self {
peer: Arc::new(ArcSwapOption::from(Some(Arc::new(inner)))),
cached_info,
mcp_id,
tool_filter,
}
}
/// 原子性替换后端连接
/// - Some(client): 设置新的后端连接
/// - None: 标记后端断开
pub fn swap_backend(&self, new_client: Option<RunningService<RoleClient, ClientInfo>>) {
use std::ops::Deref;
match new_client {
Some(client) => {
let peer = client.deref().clone();
let inner = PeerInner {
peer,
_running: Arc::new(client),
};
self.peer.store(Some(Arc::new(inner)));
info!(
"[SseHandler] Backend connection updated - MCP ID: {}",
self.mcp_id
);
}
None => {
self.peer.store(None);
info!(
"[SseHandler] Backend connection disconnected - MCP ID: {}",
self.mcp_id
);
}
}
}
/// 检查后端是否可用(快速检查,不发送请求)
pub fn is_backend_available(&self) -> bool {
let inner_guard = self.peer.load();
match inner_guard.as_ref() {
Some(inner) => !inner.peer.is_transport_closed(),
None => false,
}
}
/// 检查 mcp 服务是否正常(异步版本,会发送验证请求)
pub async fn is_mcp_server_ready(&self) -> bool {
!self.is_terminated_async().await
}
/// 检查后端连接是否已关闭(同步版本,仅检查 transport 状态)
pub fn is_terminated(&self) -> bool {
!self.is_backend_available()
}
/// 异步检查后端连接是否已断开(会发送验证请求)
pub async fn is_terminated_async(&self) -> bool {
// 原子加载后端连接
let inner_guard = self.peer.load();
let inner = match inner_guard.as_ref() {
Some(inner) => inner,
None => return true,
};
// 快速检查 transport 状态
if inner.peer.is_transport_closed() {
return true;
}
// 通过发送轻量级请求来验证连接
match inner.peer.list_tools(None).await {
Ok(_) => {
debug!("Backend connection status check: OK");
false
}
Err(e) => {
info!("Backend connection status check: Disconnected, reason: {e}");
true
}
}
}
/// 获取 MCP ID
pub fn mcp_id(&self) -> &str {
&self.mcp_id
}
/// Update backend from an SseClientConnection
///
/// This method allows updating the backend connection using the high-level
/// `SseClientConnection` type, which is more convenient than the raw
/// `RunningService` type.
///
/// # Arguments
/// * `conn` - Some(connection) to set new backend, None to mark disconnected
pub fn swap_backend_from_connection(&self, conn: Option<crate::client::SseClientConnection>) {
match conn {
Some(c) => {
let running = c.into_running_service();
self.swap_backend(Some(running));
}
None => {
self.swap_backend(None);
}
}
}
}