Rust MCP Server Generator

Rust MCP Server Generator

Generates a complete Rust Model Context Protocol server project with tools, prompts, resources and tests using the official rmcp SDK, after asking for project details.

Skill files1 file
SKILL.md578 lines
1
---
2
name: rust-mcp-server-generator
3
description: 'Generate a complete Rust Model Context Protocol server project with tools, prompts, resources, and tests using the official rmcp SDK'
4
---
5
6
# Rust MCP Server Generator
7
8
You are a Rust MCP server generator. Create a complete, production-ready Rust MCP server project using the official `rmcp` SDK.
9
10
## Project Requirements
11
12
Ask the user for:
13
1. **Project name** (e.g., "my-mcp-server")
14
2. **Server description** (e.g., "A weather data MCP server")
15
3. **Transport type** (stdio, sse, http, or all)
16
4. **Tools to include** (e.g., "weather lookup", "forecast", "alerts")
17
5. **Whether to include prompts and resources**
18
19
## Project Structure
20
21
Generate this structure:
22
23
```
24
{project-name}/
25
├── Cargo.toml
26
├── .gitignore
27
├── README.md
28
├── src/
29
│ ├── main.rs
30
│ ├── handler.rs
31
│ ├── tools/
32
│ │ ├── mod.rs
33
│ │ └── {tool_name}.rs
34
│ ├── prompts/
35
│ │ ├── mod.rs
36
│ │ └── {prompt_name}.rs
37
│ ├── resources/
38
│ │ ├── mod.rs
39
│ │ └── {resource_name}.rs
40
│ └── state.rs
41
└── tests/
42
└── integration_test.rs
43
```
44
45
## File Templates
46
47
### Cargo.toml
48
49
```toml
50
[package]
51
name = "{project-name}"
52
version = "0.1.0"
53
edition = "2021"
54
55
[dependencies]
56
rmcp = { version = "0.8.1", features = ["server"] }
57
rmcp-macros = "0.8"
58
tokio = { version = "1", features = ["full"] }
59
serde = { version = "1.0", features = ["derive"] }
60
serde_json = "1.0"
61
anyhow = "1.0"
62
tracing = "0.1"
63
tracing-subscriber = "0.3"
64
schemars = { version = "0.8", features = ["derive"] }
65
async-trait = "0.1"
66
67
# Optional: for HTTP transports
68
axum = { version = "0.7", optional = true }
69
tower-http = { version = "0.5", features = ["cors"], optional = true }
70
71
[dev-dependencies]
72
tokio-test = "0.4"
73
74
[features]
75
default = []
76
http = ["dep:axum", "dep:tower-http"]
77
78
[[bin]]
79
name = "{project-name}"
80
path = "src/main.rs"
81
```
82
83
### .gitignore
84
85
```gitignore
86
/target
87
Cargo.lock
88
*.swp
89
*.swo
90
*~
91
.DS_Store
92
```
93
94
### README.md
95
96
```markdown
97
# {Project Name}
98
99
{Server description}
100
101
## Installation
102
103
```bash
104
cargo build --release
105
```
106
107
## Usage
108
109
### Stdio Transport
110
111
```bash
112
cargo run
113
```
114
115
### SSE Transport
116
117
```bash
118
cargo run --features http -- --transport sse
119
```
120
121
### HTTP Transport
122
123
```bash
124
cargo run --features http -- --transport http
125
```
126
127
## Configuration
128
129
Configure in your MCP client (e.g., Claude Desktop):
130
131
```json
132
{
133
"mcpServers": {
134
"{project-name}": {
135
"command": "path/to/target/release/{project-name}",
136
"args": []
137
}
138
}
139
}
140
```
141
142
## Tools
143
144
- **{tool_name}**: {Tool description}
145
146
## Development
147
148
Run tests:
149
150
```bash
151
cargo test
152
```
153
154
Run with logging:
155
156
```bash
157
RUST_LOG=debug cargo run
158
```
159
```
160
161
### src/main.rs
162
163
```rust
164
use anyhow::Result;
165
use rmcp::{
166
protocol::ServerCapabilities,
167
server::Server,
168
transport::StdioTransport,
169
};
170
use tokio::signal;
171
use tracing_subscriber;
172
173
mod handler;
174
mod state;
175
mod tools;
176
mod prompts;
177
mod resources;
178
179
use handler::McpHandler;
180
181
#[tokio::main]
182
async fn main() -> Result<()> {
183
// Initialize tracing
184
tracing_subscriber::fmt()
185
.with_max_level(tracing::Level::INFO)
186
.with_target(false)
187
.init();
188
189
tracing::info!("Starting {project-name} MCP server");
190
191
// Create handler
192
let handler = McpHandler::new();
193
194
// Create transport (stdio by default)
195
let transport = StdioTransport::new();
196
197
// Build server with capabilities
198
let server = Server::builder()
199
.with_handler(handler)
200
.with_capabilities(ServerCapabilities {
201
tools: Some(Default::default()),
202
prompts: Some(Default::default()),
203
resources: Some(Default::default()),
204
..Default::default()
205
})
206
.build(transport)?;
207
208
tracing::info!("Server started, waiting for requests");
209
210
// Run server until Ctrl+C
211
server.run(signal::ctrl_c()).await?;
212
213
tracing::info!("Server shutting down");
214
Ok(())
215
}
216
```
217
218
### src/handler.rs
219
220
```rust
221
use rmcp::{
222
model::*,
223
protocol::*,
224
server::{RequestContext, ServerHandler, RoleServer, ToolRouter},
225
ErrorData,
226
};
227
use rmcp::{tool_router, tool_handler};
228
use async_trait::async_trait;
229
230
use crate::state::ServerState;
231
use crate::tools;
232
233
pub struct McpHandler {
234
state: ServerState,
235
tool_router: ToolRouter,
236
}
237
238
#[tool_router]
239
impl McpHandler {
240
// Include tool definitions from tools module
241
#[tool(
242
name = "example_tool",
243
description = "An example tool",
244
annotations(read_only_hint = true)
245
)]
246
async fn example_tool(params: Parameters<tools::ExampleParams>) -> Result<String, String> {
247
tools::example::execute(params).await
248
}
249
250
pub fn new() -> Self {
251
Self {
252
state: ServerState::new(),
253
tool_router: Self::tool_router(),
254
}
255
}
256
}
257
258
#[tool_handler]
259
#[async_trait]
260
impl ServerHandler for McpHandler {
261
async fn list_prompts(
262
&self,
263
_request: Option<PaginatedRequestParam>,
264
_context: RequestContext<RoleServer>,
265
) -> Result<ListPromptsResult, ErrorData> {
266
let prompts = vec![
267
Prompt {
268
name: "example-prompt".to_string(),
269
description: Some("An example prompt".to_string()),
270
arguments: Some(vec![
271
PromptArgument {
272
name: "topic".to_string(),
273
description: Some("The topic to discuss".to_string()),
274
required: Some(true),
275
},
276
]),
277
},
278
];
279
280
Ok(ListPromptsResult { prompts })
281
}
282
283
async fn get_prompt(
284
&self,
285
request: GetPromptRequestParam,
286
_context: RequestContext<RoleServer>,
287
) -> Result<GetPromptResult, ErrorData> {
288
match request.name.as_str() {
289
"example-prompt" => {
290
let topic = request.arguments
291
.as_ref()
292
.and_then(|args| args.get("topic"))
293
.ok_or_else(|| ErrorData::invalid_params("topic required"))?;
294
295
Ok(GetPromptResult {
296
description: Some("Example prompt".to_string()),
297
messages: vec![
298
PromptMessage::user(format!("Let's discuss: {}", topic)),
299
],
300
})
301
}
302
_ => Err(ErrorData::invalid_params("Unknown prompt")),
303
}
304
}
305
306
async fn list_resources(
307
&self,
308
_request: Option<PaginatedRequestParam>,
309
_context: RequestContext<RoleServer>,
310
) -> Result<ListResourcesResult, ErrorData> {
311
let resources = vec![
312
Resource {
313
uri: "example://data/info".to_string(),
314
name: "Example Resource".to_string(),
315
description: Some("An example resource".to_string()),
316
mime_type: Some("text/plain".to_string()),
317
},
318
];
319
320
Ok(ListResourcesResult { resources })
321
}
322
323
async fn read_resource(
324
&self,
325
request: ReadResourceRequestParam,
326
_context: RequestContext<RoleServer>,
327
) -> Result<ReadResourceResult, ErrorData> {
328
match request.uri.as_str() {
329
"example://data/info" => {
330
Ok(ReadResourceResult {
331
contents: vec![
332
ResourceContents::text("Example resource content".to_string())
333
.with_uri(request.uri)
334
.with_mime_type("text/plain"),
335
],
336
})
337
}
338
_ => Err(ErrorData::invalid_params("Unknown resource")),
339
}
340
}
341
}
342
```
343
344
### src/state.rs
345
346
```rust
347
use std::sync::Arc;
348
use tokio::sync::RwLock;
349
350
#[derive(Clone)]
351
pub struct ServerState {
352
// Add shared state here
353
counter: Arc<RwLock<i32>>,
354
}
355
356
impl ServerState {
357
pub fn new() -> Self {
358
Self {
359
counter: Arc::new(RwLock::new(0)),
360
}
361
}
362
363
pub async fn increment(&self) -> i32 {
364
let mut counter = self.counter.write().await;
365
*counter += 1;
366
*counter
367
}
368
369
pub async fn get(&self) -> i32 {
370
*self.counter.read().await
371
}
372
}
373
```
374
375
### src/tools/mod.rs
376
377
```rust
378
pub mod example;
379
380
pub use example::ExampleParams;
381
```
382
383
### src/tools/example.rs
384
385
```rust
386
use rmcp::model::Parameters;
387
use serde::{Deserialize, Serialize};
388
use schemars::JsonSchema;
389
390
#[derive(Debug, Deserialize, JsonSchema)]
391
pub struct ExampleParams {
392
pub input: String,
393
}
394
395
pub async fn execute(params: Parameters<ExampleParams>) -> Result<String, String> {
396
let input = &params.inner().input;
397
398
// Tool logic here
399
Ok(format!("Processed: {}", input))
400
}
401
402
#[cfg(test)]
403
mod tests {
404
use super::*;
405
406
#[tokio::test]
407
async fn test_example_tool() {
408
let params = Parameters::new(ExampleParams {
409
input: "test".to_string(),
410
});
411
412
let result = execute(params).await.unwrap();
413
assert!(result.contains("test"));
414
}
415
}
416
```
417
418
### src/prompts/mod.rs
419
420
```rust
421
// Prompt implementations can go here if needed
422
```
423
424
### src/resources/mod.rs
425
426
```rust
427
// Resource implementations can go here if needed
428
```
429
430
### tests/integration_test.rs
431
432
```rust
433
use rmcp::{
434
model::*,
435
protocol::*,
436
server::{RequestContext, ServerHandler, RoleServer},
437
};
438
439
// Replace with your actual project name in snake_case
440
// Example: if project is "my-mcp-server", use my_mcp_server
441
use my_mcp_server::handler::McpHandler;
442
443
#[tokio::test]
444
async fn test_list_tools() {
445
let handler = McpHandler::new();
446
let context = RequestContext::default();
447
448
let result = handler.list_tools(None, context).await.unwrap();
449
450
assert!(!result.tools.is_empty());
451
assert!(result.tools.iter().any(|t| t.name == "example_tool"));
452
}
453
454
#[tokio::test]
455
async fn test_call_tool() {
456
let handler = McpHandler::new();
457
let context = RequestContext::default();
458
459
let request = CallToolRequestParam {
460
name: "example_tool".to_string(),
461
arguments: Some(serde_json::json!({
462
"input": "test"
463
})),
464
};
465
466
let result = handler.call_tool(request, context).await;
467
assert!(result.is_ok());
468
}
469
470
#[tokio::test]
471
async fn test_list_prompts() {
472
let handler = McpHandler::new();
473
let context = RequestContext::default();
474
475
let result = handler.list_prompts(None, context).await.unwrap();
476
assert!(!result.prompts.is_empty());
477
}
478
479
#[tokio::test]
480
async fn test_list_resources() {
481
let handler = McpHandler::new();
482
let context = RequestContext::default();
483
484
let result = handler.list_resources(None, context).await.unwrap();
485
assert!(!result.resources.is_empty());
486
}
487
```
488
489
## Implementation Guidelines
490
491
1. **Use rmcp-macros**: Leverage `#[tool]`, `#[tool_router]`, and `#[tool_handler]` macros for cleaner code
492
2. **Type Safety**: Use `schemars::JsonSchema` for all parameter types
493
3. **Error Handling**: Return `Result` types with proper error messages
494
4. **Async/Await**: All handlers must be async
495
5. **State Management**: Use `Arc<RwLock<T>>` for shared state
496
6. **Testing**: Include unit tests for tools and integration tests for handlers
497
7. **Logging**: Use `tracing` macros (`info!`, `debug!`, `warn!`, `error!`)
498
8. **Documentation**: Add doc comments to all public items
499
500
## Example Tool Patterns
501
502
### Simple Read-Only Tool
503
504
```rust
505
#[derive(Debug, Deserialize, JsonSchema)]
506
pub struct GreetParams {
507
pub name: String,
508
}
509
510
#[tool(
511
name = "greet",
512
description = "Greets a user by name",
513
annotations(read_only_hint = true, idempotent_hint = true)
514
)]
515
async fn greet(params: Parameters<GreetParams>) -> String {
516
format!("Hello, {}!", params.inner().name)
517
}
518
```
519
520
### Tool with Error Handling
521
522
```rust
523
#[derive(Debug, Deserialize, JsonSchema)]
524
pub struct DivideParams {
525
pub a: f64,
526
pub b: f64,
527
}
528
529
#[tool(name = "divide", description = "Divides two numbers")]
530
async fn divide(params: Parameters<DivideParams>) -> Result<f64, String> {
531
let p = params.inner();
532
if p.b == 0.0 {
533
Err("Cannot divide by zero".to_string())
534
} else {
535
Ok(p.a / p.b)
536
}
537
}
538
```
539
540
### Tool with State
541
542
```rust
543
#[tool(
544
name = "increment",
545
description = "Increments the counter",
546
annotations(destructive_hint = true)
547
)]
548
async fn increment(state: &ServerState) -> i32 {
549
state.increment().await
550
}
551
```
552
553
## Running the Generated Server
554
555
After generation:
556
557
```bash
558
cd {project-name}
559
cargo build
560
cargo test
561
cargo run
562
```
563
564
For Claude Desktop integration:
565
566
```json
567
{
568
"mcpServers": {
569
"{project-name}": {
570
"command": "path/to/{project-name}/target/release/{project-name}",
571
"args": []
572
}
573
}
574
}
575
```
576
577
Now generate the complete project based on the user's requirements!
578

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 13,336 prompts

More by @OpenSourceBuffGuy

See all
Clumsy delivery boy animated comedy short prompt image

Clumsy delivery boy animated comedy short

Describes a Pixar-style 3D animated comedy short in which a clumsy delivery boy causes a chain of slapstick chaos and ends up a hero in a seaside city.

video-prompt, animation, pixar-style, comedy, humorous, short-film, storytelling, camera-movement, tracking-shot, scene-transitions, music-video, widescreen, family-friendly, cozy, vibrant-colors, cartoon, whimsical, cityscape, summer, for-filmmakers, long-form, encouraging, structured-output, 3d-render, text-rendering

Young woman packs gym bag in bedroom prompt image

Young woman packs gym bag in bedroom

Generates a 30-second early-2000s Japanese gym-day vlog in MiniDV camcorder style, with second-by-second beats and a locked character, era and continuity.

video-prompt, vlog, home-video, timed-beats, character-consistency, reference-image, handheld, multi-shot, photorealistic, japan, woman, fitness, guardrails, seedance, candid, long-form, vintage, tracking-shot

Woman stares blankly into open refrigerator prompt image

Woman stares blankly into open refrigerator

Generates a 30-second, 12-shot candid home-video montage of a woman in her messy apartment with her dog, with Korean dialogue, handheld drift and detailed ambient sound.

video-prompt, reference-image, face-reference, character-consistency, timed-beats, multi-shot, handheld, home-video, film-grain, candid, lip-sync, animals, pet-care, natural-light, camera-movement, humorous, casual, woman, korea, structured-output, long-form, vlog, cozy

Reviews

Loading reviews…

Discussion

Loading comments…