pub struct ServerTransportFactory;
Expand description
Server transport factory
Implementations§
Source§impl ServerTransportFactory
impl ServerTransportFactory
Sourcepub fn create(&self, config: TransportConfig) -> Result<Box<dyn Transport>>
pub fn create(&self, config: TransportConfig) -> Result<Box<dyn Transport>>
Create a new transport instance
Examples found in repository?
examples/ping_example.rs (line 61)
47async fn run_server() -> Result<()> {
48 // 配置服务器
49 // Configure server
50 let config = TransportConfig {
51 transport_type: TransportType::Http {
52 base_url: SERVER_URL.to_string(),
53 auth_token: Some(AUTH_TOKEN.to_string()),
54 },
55 parameters: None,
56 };
57
58 // 创建服务器实例
59 // Create server instance
60 let factory = ServerTransportFactory;
61 let mut server = factory.create(config)?;
62
63 // 初始化服务器
64 // Initialize server
65 server.initialize().await?;
66 eprintln!(
67 "Server started and waiting for ping requests on port {}",
68 SERVER_PORT
69 );
70
71 // 等待退出信号或超时
72 // Wait for exit signal or timeout
73 let (tx, mut rx) = tokio::sync::oneshot::channel::<()>();
74
75 let exit_signal = async move {
76 rx.await.ok();
77 };
78
79 tokio::select! {
80 _ = exit_signal => {
81 eprintln!("Server received exit signal");
82 }
83 _ = tokio::time::sleep(SERVER_TIMEOUT) => {
84 eprintln!("Server timeout after {} seconds", SERVER_TIMEOUT.as_secs());
85 }
86 }
87
88 server.close().await?;
89 eprintln!("Server stopped");
90 Ok(())
91}
More examples
examples/stdio_server.rs (line 29)
11async fn main() -> Result<()> {
12 // 跟踪会话中使用的请求 ID
13 // Track request IDs used in the session
14 let mut session_ids = HashSet::new();
15
16 // 配置 Stdio 服务器
17 // Configure Stdio server
18 let config = TransportConfig {
19 transport_type: TransportType::Stdio {
20 server_path: None,
21 server_args: None,
22 },
23 parameters: None,
24 };
25
26 // 创建服务器实例
27 // Create server instance
28 let factory = ServerTransportFactory;
29 let mut server = factory.create(config)?;
30
31 // 初始化服务器
32 // Initialize server
33 server.initialize().await?;
34 eprintln!("Server initialized and ready to receive messages...");
35
36 // 持续接收和处理消息
37 // Continuously receive and process messages
38 loop {
39 match server.receive().await {
40 Ok(message) => {
41 eprintln!("Received message: {:?}", message);
42
43 // 根据消息类型处理
44 // Process messages based on type
45 match message {
46 Message::Request(request) => {
47 // 验证请求 ID 的唯一性
48 // Validate request ID uniqueness
49 if !request.validate_id_uniqueness(&mut session_ids) {
50 let error = Message::Response(Response::error(
51 message::ResponseError {
52 code: message::error_codes::INVALID_REQUEST,
53 message: "Request ID has already been used".to_string(),
54 data: None,
55 },
56 request.id,
57 ));
58 if let Err(e) = server.send(error).await {
59 eprintln!("Error sending error response: {}", e);
60 break;
61 }
62 continue;
63 }
64
65 match request.method.as_str() {
66 "prompts/execute" => {
67 // 创建响应消息
68 // Create response message
69 let response = Message::Response(Response::success(
70 json!({
71 "content": "Hello from server!",
72 "role": "assistant"
73 }),
74 request.id,
75 ));
76
77 // 发送响应
78 // Send response
79 if let Err(e) = server.send(response).await {
80 eprintln!("Error sending response: {}", e);
81 break;
82 }
83 }
84 _ => {
85 eprintln!("Unknown method: {}", request.method);
86 let error = Message::Response(Response::error(
87 message::ResponseError {
88 code: message::error_codes::METHOD_NOT_FOUND,
89 message: "Method not found".to_string(),
90 data: None,
91 },
92 request.id,
93 ));
94 if let Err(e) = server.send(error).await {
95 eprintln!("Error sending error response: {}", e);
96 break;
97 }
98 }
99 }
100 }
101 _ => {
102 eprintln!("Unexpected message type");
103 }
104 }
105 }
106 Err(e) => {
107 eprintln!("Error receiving message: {}", e);
108 break;
109 }
110 }
111 }
112
113 // 关闭服务器
114 // Close server
115 server.close().await?;
116 Ok(())
117}
examples/lifecycle_server.rs (line 30)
12async fn main() -> Result<()> {
13 // 跟踪会话中使用的请求 ID
14 // Track request IDs used in the session
15 let mut session_ids = HashSet::new();
16
17 // 配置 Stdio 服务器
18 // Configure Stdio server
19 let config = TransportConfig {
20 transport_type: TransportType::Stdio {
21 server_path: None,
22 server_args: None,
23 },
24 parameters: None,
25 };
26
27 // 创建服务器实例
28 // Create server instance
29 let factory = ServerTransportFactory;
30 let mut server = factory.create(config)?;
31 let mut initialized = false;
32
33 // 启动服务器
34 // Start server
35 eprintln!("Server starting...");
36 server.initialize().await?;
37
38 // 处理消息循环
39 // Message handling loop
40 loop {
41 match server.receive().await {
42 Ok(message) => {
43 match message {
44 Message::Request(request) => {
45 // 验证请求 ID 的唯一性
46 // Validate request ID uniqueness
47 if !request.validate_id_uniqueness(&mut session_ids) {
48 let error = ResponseError {
49 code: error_codes::INVALID_REQUEST,
50 message: "Request ID has already been used".to_string(),
51 data: None,
52 };
53 let response = Response::error(error, request.id);
54 server.send(Message::Response(response)).await?;
55 continue;
56 }
57
58 match request.method.as_str() {
59 "initialize" => {
60 // 处理初始化请求
61 // Handle initialize request
62 eprintln!("Received initialize request");
63
64 // 解析客户端能力和版本
65 // Parse client capabilities and version
66 if let Some(params) = request.params {
67 let client_version = params
68 .get("protocolVersion")
69 .and_then(|v| v.as_str())
70 .unwrap_or("unknown");
71
72 // 版本检查
73 // Version check
74 if client_version != PROTOCOL_VERSION {
75 // 发送错误响应
76 // Send error response
77 let error = ResponseError {
78 code: error_codes::INVALID_REQUEST,
79 message: "Unsupported protocol version".to_string(),
80 data: Some(json!({
81 "supported": [PROTOCOL_VERSION],
82 "requested": client_version
83 })),
84 };
85 let response = Response::error(error, request.id);
86 server.send(Message::Response(response)).await?;
87 continue;
88 }
89
90 // 发送成功响应
91 // Send success response
92 let response = Response::success(
93 json!({
94 "protocolVersion": PROTOCOL_VERSION,
95 "capabilities": ServerCapabilities {
96 prompts: None,
97 resources: None,
98 tools: None,
99 logging: Some(json!({})),
100 experimental: None,
101 },
102 "serverInfo": ImplementationInfo {
103 name: "Example Server".to_string(),
104 version: "1.0.0".to_string(),
105 }
106 }),
107 request.id,
108 );
109 server.send(Message::Response(response)).await?;
110 }
111 }
112 "shutdown" => {
113 if !initialized {
114 // 如果未初始化,发送错误
115 // If not initialized, send error
116 let error = ResponseError {
117 code: error_codes::SERVER_NOT_INITIALIZED,
118 message: "Server not initialized".to_string(),
119 data: None,
120 };
121 let response = Response::error(error, request.id);
122 server.send(Message::Response(response)).await?;
123 continue;
124 }
125
126 // 发送成功响应
127 // Send success response
128 let response = Response::success(json!(null), request.id);
129 server.send(Message::Response(response)).await?;
130
131 // 等待退出通知
132 // Wait for exit notification
133 eprintln!("Server shutting down...");
134 break;
135 }
136 _ => {
137 if !initialized {
138 // 如果未初始化,拒绝其他请求
139 // If not initialized, reject other requests
140 let error = ResponseError {
141 code: error_codes::SERVER_NOT_INITIALIZED,
142 message: "Server not initialized".to_string(),
143 data: None,
144 };
145 let response = Response::error(error, request.id);
146 server.send(Message::Response(response)).await?;
147 }
148 }
149 }
150 }
151 Message::Notification(notification) => match notification.method.as_str() {
152 "initialized" => {
153 eprintln!("Server initialized");
154 initialized = true;
155 }
156 "exit" => {
157 eprintln!("Received exit notification");
158 break;
159 }
160 _ => {}
161 },
162 _ => {}
163 }
164 }
165 Err(e) => {
166 eprintln!("Error receiving message: {}", e);
167 break;
168 }
169 }
170 }
171
172 // 关闭服务器
173 // Close server
174 server.close().await?;
175 eprintln!("Server stopped");
176 Ok(())
177}
Auto Trait Implementations§
impl Freeze for ServerTransportFactory
impl RefUnwindSafe for ServerTransportFactory
impl Send for ServerTransportFactory
impl Sync for ServerTransportFactory
impl Unpin for ServerTransportFactory
impl UnwindSafe for ServerTransportFactory
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more