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
use crate::client::Client;
use crate::client::transport::sse::SseClientTransport;
use crate::client::transport::stdio::StdioClientTransport;
use crate::server::core::FastMCPServer;
use crate::server::transport::Transport;
use crate::server::transport::http::HttpTransport;
use crate::server::transport::stdio::StdioTransport;
use std::process::exit;
use tracing::{error, info};
pub async fn run(
transport_type: &str,
port: u16,
config_path: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
let server = FastMCPServer::new("rs-fast-mcp", "0.1.0");
// Determine config path
let config_path = config_path
.map(std::path::Path::new)
.unwrap_or_else(|| std::path::Path::new("fastmcp.json"));
if config_path.exists() {
info!("Loading configuration from {}", config_path.display());
match crate::mcp::config::ServerConfig::load_from_file(config_path) {
Ok(config) => {
if let Some(_name) = config.name {
// Re-create server with new name if needed, or we just rely on the default since name is immutable in FastMCPServer struct without setters (except creating new).
// Since FastMCPServer wraps Arc<FastMCP>, we can't mutate name easily.
// For now, let's just log it or if we really wanted to change it we'd need to reconstruct.
// But we already created it.
// Optimization: Move creation *after* loading config?
}
// Register Tools
for (name, tool_config) in config.tools {
match tool_config {
crate::mcp::config::ToolConfig::Command {
command,
args,
env,
description,
} => {
let _tool_name = name.clone();
let tool_cmd = command.clone();
let tool_args = args.clone();
let tool_env = env.clone();
let tool = crate::tools::tool::Tool {
name: name.clone(),
title: None,
description: description.or(Some(format!("Run {}", command))),
enabled: true,
key: None,
tags: std::collections::HashSet::new(),
meta: None,
data: crate::tools::tool::ToolKind::Function(
crate::tools::tool::ToolFunction {
name: name.clone(),
description: None,
input_schema: serde_json::json!({
"type": "object",
"additionalProperties": true
}), // Allow any args for now, passed as JSON string maybe?
output_schema: None,
compiled_schema: None,
fn_handler: std::sync::Arc::new(Box::new(
move |_ctx, args| {
let cmd = tool_cmd.clone();
let t_args = tool_args.clone();
let t_env = tool_env.clone();
Box::pin(async move {
use tokio::process::Command;
let mut child = Command::new(&cmd);
child.args(&t_args);
child.envs(&t_env);
// Pass arguments as JSON to stdin? Or env vars?
// For simple command tools, maybe just arguments.
// Let's pass arguments as a JSON string in FASTMCP_ARGS
child.env("FASTMCP_ARGS", serde_json::to_string(&args).unwrap_or_default());
match child.output().await {
Ok(output) => {
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
if output.status.success() {
Ok(crate::tools::tool::ToolResult {
content: vec![crate::mcp::types::ContentBlock::Text(crate::mcp::types::TextContent {
type_: "text".to_string(),
text: stdout,
annotations: None,
})],
structured_content: None,
})
} else {
Err(crate::error::FastMCPError::Tool(crate::error::ErrorData {
code: Some(1),
message: format!("Command failed: {}", stderr),
data: None,
}))
}
}
Err(e) => Err(crate::error::FastMCPError::Tool(crate::error::ErrorData {
code: Some(1),
message: e.to_string(),
data: None,
})),
}
}) as std::pin::Pin<Box<dyn std::future::Future<Output = Result<crate::tools::tool::ToolResult, crate::error::FastMCPError>> + Send>>
},
)),
},
),
};
server
.add_tool(tool)
.unwrap_or_else(|e| error!("Failed to add tool {}: {}", name, e));
}
}
}
// Register Resources
for (name, resource_config) in config.resources {
match resource_config {
crate::mcp::config::ResourceConfig::File { path, mime_type } => {
let resource = crate::mcp::types::Resource {
uri: name.clone(),
description: Some(format!("File: {}", path)),
mime_type,
tags: None,
base_metadata: crate::mcp::types::BaseMetadata {
name: name.clone(),
title: None,
},
size: None,
annotations: None,
icons: None,
};
let file_path = path.clone();
let handler = Box::new(
move |_uri: String, _ctx: crate::server::context::Context| {
let p = file_path.clone();
Box::pin(async move {
match tokio::fs::read_to_string(&p).await {
Ok(content) => {
Ok(vec![crate::mcp::types::ResourceContents {
uri: _uri,
mime_type: None,
text: Some(content),
blob: None,
}])
}
Err(e) => Err(crate::error::FastMCPError::Resource(
crate::error::ErrorData {
code: Some(1),
message: e.to_string(),
data: None,
},
)),
}
})
as std::pin::Pin<
Box<
dyn std::future::Future<
Output = Result<
Vec<
crate::mcp::types::ResourceContents,
>,
crate::error::FastMCPError,
>,
> + Send,
>,
>
},
);
server
.add_resource(resource, Some(std::sync::Arc::new(handler)))
.unwrap_or_else(|e| {
error!("Failed to add resource {}: {}", name, e)
});
}
crate::mcp::config::ResourceConfig::Text { content, mime_type } => {
let resource = crate::mcp::types::Resource {
uri: name.clone(),
description: Some("Static text".to_string()),
mime_type: mime_type.clone(),
tags: None,
base_metadata: crate::mcp::types::BaseMetadata {
name: name.clone(),
title: None,
},
size: None,
annotations: None,
icons: None,
};
let text_content = content.clone();
let handler = Box::new(move |uri: String, _| {
let t = text_content.clone();
let m = mime_type.clone();
Box::pin(async move {
Ok(vec![crate::mcp::types::ResourceContents {
uri,
mime_type: m,
text: Some(t),
blob: None,
}])
})
as std::pin::Pin<
Box<
dyn std::future::Future<
Output = Result<
Vec<crate::mcp::types::ResourceContents>,
crate::error::FastMCPError,
>,
> + Send,
>,
>
});
server
.add_resource(resource, Some(std::sync::Arc::new(handler)))
.unwrap_or_else(|e| {
error!("Failed to add resource {}: {}", name, e)
});
}
}
}
}
Err(e) => error!("Failed to load fastmcp.json: {}", e),
}
}
// Prepare handler and notification receiver
let handler = std::sync::Arc::new(server.clone());
let rx = Some(server.subscribe_notifications());
match transport_type {
"stdio" => {
let transport = StdioTransport::new();
transport.start(handler, rx).await?;
}
"sse" | "http" => {
let transport = HttpTransport::new("127.0.0.1", port);
transport.start(handler, rx).await?;
}
_ => {
error!("Unknown transport type: {}", transport_type);
exit(1);
}
}
Ok(())
}
pub async fn client(
server_url: Option<&str>,
command: Option<&str>,
_args: &[String], // Args might be used later if we spawn subprocess
) -> Result<(), Box<dyn std::error::Error>> {
let transport: Box<dyn crate::client::ClientTransport> = if let Some(url) = server_url {
if url.starts_with("http") {
Box::new(SseClientTransport::new(url.to_string(), None))
} else {
error!("Invalid server URL for SSE: {}", url);
exit(1);
}
} else if let Some(cmd) = command {
// Spawn the command
Box::new(StdioClientTransport::new_process(cmd, _args).map_err(|e| e.to_string())?)
} else {
error!("Either --server-url or --command must be provided");
exit(1);
};
let client = Client::new(transport);
info!("Client connected. Listing tools...");
match client.list_tools().await {
Ok(tools) => {
println!("Tools available:");
for tool in tools {
println!("- {}", tool.base_metadata.name);
}
}
Err(e) => error!("Failed to list tools: {}", e),
}
Ok(())
}
pub async fn inspect(
server_url: Option<&str>,
command: Option<&str>,
args: &[String],
) -> Result<(), Box<dyn std::error::Error>> {
// Reuse client logic but more inspection
client(server_url, command, args).await
}
pub async fn dev(
config_path: Option<&str>,
npx_path: String,
) -> Result<(), Box<dyn std::error::Error>> {
// 1. Determine the command to run the server (ourselves)
// We want to run this binary with `run` subcommand.
// If we were launched with `cargo run`, we assume we can just use `cargo run`.
// But getting `cargo` invocation is tricky.
// Safest bet is `current_exe()` which points to the binary.
let current_exe = std::env::current_exe()?;
let server_cmd = current_exe.to_string_lossy().to_string();
let mut server_args = vec![
"run".to_string(),
"--transport".to_string(),
"stdio".to_string(),
];
if let Some(cfg) = config_path {
server_args.push("--config".to_string());
server_args.push(cfg.to_string());
}
info!("Starting MCP Inspector via {}...", npx_path);
// The inspector expects: npx @modelcontextprotocol/inspector <command> <args...>
use tokio::process::Command;
let mut child = Command::new(&npx_path)
.arg("@modelcontextprotocol/inspector")
.arg(server_cmd)
.args(server_args)
.spawn()
.map_err(|e| format!("Failed to spawn inspector ({}): {}", npx_path, e))?;
let status = child.wait().await?;
if !status.success() {
return Err("Inspector exited with error".into());
}
Ok(())
}
pub async fn version() -> Result<(), Box<dyn std::error::Error>> {
println!("rs-fast-mcp v{}", env!("CARGO_PKG_VERSION"));
Ok(())
}