-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathmain.rs
More file actions
249 lines (222 loc) · 8.72 KB
/
main.rs
File metadata and controls
249 lines (222 loc) · 8.72 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
use std::env;
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use anyhow::Result;
use clap::{Parser, Subcommand};
use mcp_server::{
handle_prompts_list, handle_resources_list, handle_tools_call, handle_tools_list,
LifecycleManager,
};
use rmcp::model::{
CallToolRequestParam, CallToolResult, ErrorData, ListPromptsResult, ListResourcesResult,
ListToolsResult, PaginatedRequestParam, ServerCapabilities, ServerInfo, ToolsCapability,
};
use rmcp::service::{serve_server, RequestContext, RoleServer};
use rmcp::transport::{stdio as stdio_transport, SseServer};
use rmcp::ServerHandler;
use tracing_subscriber::layer::SubscriberExt as _;
use tracing_subscriber::util::SubscriberInitExt as _;
const BIND_ADDRESS: &str = "127.0.0.1:9001";
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
Serve {
#[arg(long, default_value_t = get_component_dir().into_os_string().into_string().unwrap())]
plugin_dir: String,
/// Enable stdio transport
#[arg(long)]
stdio: bool,
/// Enable HTTP transport
#[arg(long)]
http: bool,
},
}
/// Get the default component directory path based on the OS
fn get_component_dir() -> PathBuf {
if cfg!(target_os = "windows") {
let local_app_data = env::var("LOCALAPPDATA")
.unwrap_or_else(|_| env::var("USERPROFILE").unwrap_or_else(|_| "C:\\".to_string()));
PathBuf::from(local_app_data)
.join("wassette")
.join("components")
} else if cfg!(target_os = "macos") {
let home = env::var("HOME").unwrap_or_else(|_| "/".to_string());
PathBuf::from(home)
.join("Library")
.join("Application Support")
.join("wassette")
.join("components")
} else {
let xdg_data_home = env::var("XDG_DATA_HOME").unwrap_or_else(|_| {
let home = env::var("HOME").unwrap_or_else(|_| "/".to_string());
format!("{home}/.local/share")
});
PathBuf::from(xdg_data_home)
.join("wassette")
.join("components")
}
}
#[derive(Clone)]
pub struct McpServer {
lifecycle_manager: LifecycleManager,
}
impl McpServer {
pub fn new(lifecycle_manager: LifecycleManager) -> Self {
Self { lifecycle_manager }
}
}
#[allow(refining_impl_trait_reachable)]
impl ServerHandler for McpServer {
fn get_info(&self) -> ServerInfo {
ServerInfo {
capabilities: ServerCapabilities {
tools: Some(ToolsCapability {
list_changed: Some(true),
}),
..Default::default()
},
instructions: Some(
r#"This server runs tools in sandboxed WebAssembly environments with no default access to host resources.
Key points:
- Tools must be loaded before use: "Load component from oci://registry/tool:version" or "file:///path/to/tool.wasm"
- When the server starts, it will load all tools present in the plugin directory.
- You can list loaded tools with 'list-components' tool.
- Each tool only accesses resources explicitly granted by a policy file (filesystem paths, network domains, etc.)
- You MUST never modify the policy file directly, use tools to grant permissions instead.
- Tools needs permission for that resource
- If access is denied, suggest alternatives within allowed permissions or propose to grant permission"#.to_string(),
),
..Default::default()
}
}
fn call_tool<'a>(
&'a self,
params: CallToolRequestParam,
ctx: RequestContext<RoleServer>,
) -> Pin<Box<dyn Future<Output = Result<CallToolResult, ErrorData>> + Send + 'a>> {
let peer_clone = ctx.peer.clone();
Box::pin(async move {
let result = handle_tools_call(params, &self.lifecycle_manager, peer_clone).await;
match result {
Ok(value) => serde_json::from_value(value).map_err(|e| {
ErrorData::parse_error(format!("Failed to parse result: {e}"), None)
}),
Err(err) => Err(ErrorData::parse_error(err.to_string(), None)),
}
})
}
fn list_tools<'a>(
&'a self,
_params: Option<PaginatedRequestParam>,
_ctx: RequestContext<RoleServer>,
) -> Pin<Box<dyn Future<Output = Result<ListToolsResult, ErrorData>> + Send + 'a>> {
Box::pin(async move {
let result = handle_tools_list(&self.lifecycle_manager).await;
match result {
Ok(value) => serde_json::from_value(value).map_err(|e| {
ErrorData::parse_error(format!("Failed to parse result: {e}"), None)
}),
Err(err) => Err(ErrorData::parse_error(err.to_string(), None)),
}
})
}
fn list_prompts<'a>(
&'a self,
_params: Option<PaginatedRequestParam>,
_ctx: RequestContext<RoleServer>,
) -> Pin<Box<dyn Future<Output = Result<ListPromptsResult, ErrorData>> + Send + 'a>> {
Box::pin(async move {
let result = handle_prompts_list(serde_json::Value::Null).await;
match result {
Ok(value) => serde_json::from_value(value).map_err(|e| {
ErrorData::parse_error(format!("Failed to parse result: {e}"), None)
}),
Err(err) => Err(ErrorData::parse_error(err.to_string(), None)),
}
})
}
fn list_resources<'a>(
&'a self,
_params: Option<PaginatedRequestParam>,
_ctx: RequestContext<RoleServer>,
) -> Pin<Box<dyn Future<Output = Result<ListResourcesResult, ErrorData>> + Send + 'a>> {
Box::pin(async move {
let result = handle_resources_list(serde_json::Value::Null).await;
match result {
Ok(value) => serde_json::from_value(value).map_err(|e| {
ErrorData::parse_error(format!("Failed to parse result: {e}"), None)
}),
Err(err) => Err(ErrorData::parse_error(err.to_string(), None)),
}
})
}
}
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| {
"info,cranelift_codegen=warn,cranelift_entity=warn,cranelift_bforest=warn,cranelift_frontend=warn"
.to_string()
.into()
}),
)
.with(tracing_subscriber::fmt::layer())
.init();
let cli = Cli::parse();
match &cli.command {
Commands::Serve {
plugin_dir,
stdio,
http,
} => {
let components_dir = PathBuf::from(plugin_dir);
let lifecycle_manager = LifecycleManager::new(&components_dir).await?;
let server = McpServer::new(lifecycle_manager);
match (*stdio, *http) {
(false, false) => {
// Default case: use stdio transport
tracing::info!("Starting MCP server with stdio transport (default)");
let transport = stdio_transport();
let running_service = serve_server(server, transport).await?;
tokio::signal::ctrl_c().await?;
let _ = running_service.cancel().await;
}
(true, false) => {
// Stdio transport only
tracing::info!("Starting MCP server with stdio transport");
let transport = stdio_transport();
let running_service = serve_server(server, transport).await?;
tokio::signal::ctrl_c().await?;
let _ = running_service.cancel().await;
}
(false, true) => {
// HTTP transport only
tracing::info!(
"Starting MCP server on {} with HTTP transport",
BIND_ADDRESS
);
let ct = SseServer::serve(BIND_ADDRESS.parse().unwrap())
.await?
.with_service(move || server.clone());
tokio::signal::ctrl_c().await?;
ct.cancel();
}
(true, true) => {
return Err(anyhow::anyhow!(
"Running both stdio and HTTP transports simultaneously is not supported. Please choose one."
));
}
}
tracing::info!("MCP server shutting down");
}
}
Ok(())
}