mcpr 0.2.3

Rust implementation of Anthropic's Model Context Protocol
Documentation
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
//! Templates for generating MCP server and client stubs

pub mod sse;
pub mod stdio;
// WebSocket templates will be implemented in a future release

// Re-export all templates from transport modules
pub use sse::{
    PROJECT_CLIENT_CARGO_TEMPLATE as SSE_CLIENT_CARGO_TEMPLATE,
    PROJECT_CLIENT_TEMPLATE as SSE_CLIENT_TEMPLATE,
    PROJECT_SERVER_CARGO_TEMPLATE as SSE_SERVER_CARGO_TEMPLATE,
    PROJECT_SERVER_TEMPLATE as SSE_SERVER_TEMPLATE,
    PROJECT_TEST_SCRIPT_TEMPLATE as SSE_TEST_SCRIPT_TEMPLATE,
};

pub use stdio::{
    PROJECT_CLIENT_CARGO_TEMPLATE as STDIO_CLIENT_CARGO_TEMPLATE,
    PROJECT_CLIENT_TEMPLATE as STDIO_CLIENT_TEMPLATE,
    PROJECT_SERVER_CARGO_TEMPLATE as STDIO_SERVER_CARGO_TEMPLATE,
    PROJECT_SERVER_TEMPLATE as STDIO_SERVER_TEMPLATE,
    PROJECT_TEST_SCRIPT_TEMPLATE as STDIO_TEST_SCRIPT_TEMPLATE,
};

// WebSocket templates will be added when the WebSocket transport is implemented

// Original templates from templates.rs
/// Template for server main.rs
pub const SERVER_MAIN_TEMPLATE: &str = r#"//! MCP Server: {{name}}

use clap::Parser;
use mcpr::schema::{
    CallToolParams, CallToolResult, Implementation, InitializeResult, JSONRPCError, JSONRPCMessage,
    JSONRPCResponse, ServerCapabilities, TextContent, Tool, ToolInputSchema, ToolResultContent,
    ToolsCapability,
};
use mcpr::transport::stdio::StdioTransport;
use serde_json::{json, Value};
use std::error::Error;
use std::collections::HashMap;
use log::{info, error, debug, warn};

/// CLI arguments
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Args {
    /// Enable debug output
    #[arg(short, long)]
    debug: bool,
}

fn main() -> Result<(), Box<dyn Error>> {
    // Parse command line arguments
    let args = Args::parse();

    // Initialize logging
    if args.debug {
        std::env::set_var("RUST_LOG", "debug,mcpr=debug");
    } else {
        std::env::set_var("RUST_LOG", "info,mcpr=info");
    }
    env_logger::init();

    // Create a transport
    let transport = StdioTransport::new();

    // Create a server
    let mut server = mcpr::server::Server::new(
        mcpr::server::ServerConfig::new()
            .with_name("{{name}}")
            .with_version("0.1.0")
            .with_tool(Tool {
                name: "hello".to_string(),
                description: "A simple tool that greets a person by name".to_string(),
                parameters_schema: json!({
                    "type": "object",
                    "properties": {
                        "name": {
                            "type": "string",
                            "description": "The name of the person to greet"
                        }
                    },
                    "required": ["name"]
                }),
            }),
    );

    // Register tool handlers
    server.register_tool_handler("hello", |params| {
        let name = params["name"].as_str().unwrap_or("World");
        Ok(json!({
            "message": format!("Hello, {}!", name)
        }))
    })?;

    // Start the server
    info!("Starting MCP server");
    server.start(transport)?;

    Ok(())
}
"#;

/// Template for server Cargo.toml
pub const SERVER_CARGO_TEMPLATE: &str = r#"[package]
name = "{{name}}"
version = "0.1.0"
edition = "2021"
description = "MCP server generated using mcpr CLI"

[dependencies]
mcpr = "0.2.3"
clap = { version = "4.4", features = ["derive"] }
serde_json = "1.0"
log = "0.4"
env_logger = "0.10"
"#;

/// Template for client main.rs
pub const CLIENT_MAIN_TEMPLATE: &str = r#"//! MCP Client: {{name}}

use clap::Parser;
use mcpr::client::Client;
use mcpr::transport::stdio::StdioTransport;
use serde_json::{json, Value};
use std::error::Error;
use std::io::{self, Write};
use std::process::{Command, Stdio};
use log::{info, error, debug, warn};

/// CLI arguments
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Args {
    /// Enable debug output
    #[arg(short, long)]
    debug: bool,

    /// Run in interactive mode
    #[arg(short, long)]
    interactive: bool,

    /// Name to greet (for non-interactive mode)
    #[arg(short, long)]
    name: Option<String>,

    /// Connect to an existing server
    #[arg(short, long)]
    connect: bool,

    /// Server command to run
    #[arg(long, default_value = "../server/target/debug/{{name}}")]
    server_cmd: String,
}

fn main() -> Result<(), Box<dyn Error>> {
    // Parse command line arguments
    let args = Args::parse();

    // Initialize logging
    if args.debug {
        std::env::set_var("RUST_LOG", "debug,mcpr=debug");
    } else {
        std::env::set_var("RUST_LOG", "info,mcpr=info");
    }
    env_logger::init();

    // Create a transport
    let transport = if args.connect {
        info!("Connecting to existing server");
        StdioTransport::new()
    } else {
        info!("Starting server process: {}", args.server_cmd);
        let server_process = Command::new(&args.server_cmd)
            .stdout(Stdio::piped())
            .stdin(Stdio::piped())
            .spawn()?;
        
        StdioTransport::from_process(server_process)
    };

    // Create a client
    let mut client = Client::new(transport);

    // Initialize the client
    info!("Initializing client");
    let init_result = client.initialize()?;
    info!("Connected to server: {} v{}", init_result.name, init_result.version);
    
    if let Some(tools) = init_result.capabilities.tools {
        info!("Available tools:");
        for tool in tools.tools {
            info!("  - {}: {}", tool.name, tool.description);
        }
    }

    if args.interactive {
        // Interactive mode
        loop {
            print!("Enter tool name (or 'exit' to quit): ");
            io::stdout().flush()?;
            
            let mut tool_name = String::new();
            io::stdin().read_line(&mut tool_name)?;
            let tool_name = tool_name.trim();
            
            if tool_name == "exit" {
                break;
            }
            
            if tool_name == "hello" {
                print!("Enter name to greet: ");
                io::stdout().flush()?;
                
                let mut name = String::new();
                io::stdin().read_line(&mut name)?;
                let name = name.trim();
                
                let result: Value = client.call_tool(tool_name, &json!({
                    "name": name
                }))?;
                
                println!("Result: {}", result["message"]);
            } else {
                println!("Unknown tool: {}", tool_name);
            }
        }
    } else if let Some(name) = args.name {
        // One-shot mode
        let result: Value = client.call_tool("hello", &json!({
            "name": name
        }))?;
        
        println!("{}", result["message"]);
    } else {
        println!("Please specify a name with --name or use --interactive mode");
    }

    // Shutdown the client
    info!("Shutting down client");
    client.shutdown()?;

    Ok(())
}
"#;

/// Template for client Cargo.toml
pub const CLIENT_CARGO_TEMPLATE: &str = r#"[package]
name = "{{name}}"
version = "0.1.0"
edition = "2021"
description = "MCP client generated using mcpr CLI"

[dependencies]
mcpr = "0.2.3"
clap = { version = "4.4", features = ["derive"] }
serde_json = "1.0"
log = "0.4"
env_logger = "0.10"
"#;

// Common templates that are not transport-specific
pub const SERVER_README_TEMPLATE: &str = r#"# {{name}}

An MCP server implementation generated using the MCPR CLI.

## Features

- Implements the Model Context Protocol (MCP)
- Provides a simple "hello" tool for demonstration
- Configurable logging levels

## Building

```bash
cargo build
```

## Running

```bash
cargo run
```

## Available Tools

- `hello`: A simple tool that greets a person by name

## Adding New Tools

To add a new tool, modify the `main.rs` file:

1. Add a new tool definition in the server configuration
2. Register a handler for the tool
3. Implement the tool's functionality in the handler

## Configuration

- `--debug`: Enable debug logging
"#;

pub const CLIENT_README_TEMPLATE: &str = r#"# {{name}}

An MCP client implementation generated using the MCPR CLI.

## Features

- Implements the Model Context Protocol (MCP)
- Supports both interactive and one-shot modes
- Can connect to an existing server or start a new server process
- Configurable logging levels

## Building

```bash
cargo build
```

## Running

### Interactive Mode

```bash
cargo run -- --interactive
```

### One-shot Mode

```bash
cargo run -- --name "Your Name"
```

### Connecting to an Existing Server

```bash
cargo run -- --connect --name "Your Name"
```

## Configuration

- `--debug`: Enable debug logging
- `--interactive`: Run in interactive mode
- `--name <NAME>`: Name to greet (for non-interactive mode)
- `--connect`: Connect to an existing server
- `--server-cmd <CMD>`: Server command to run (default: "../server/target/debug/{{name}}")
"#;

pub const PROJECT_README_SSE_TEMPLATE: &str = r#"# {{name}} - MCP Project

A complete MCP project with both client and server components, using SSE transport.

## Features

- **Server-Sent Events Transport**: HTTP-based transport with proper client registration and message handling
- **Multiple Client Support**: Server can handle multiple clients simultaneously
- **Interactive Mode**: Choose tools and provide parameters interactively
- **One-shot Mode**: Run queries directly from the command line
- **Comprehensive Logging**: Detailed logging for debugging and monitoring

## Project Structure

- `client/`: The MCP client implementation
- `server/`: The MCP server implementation with tools
- `test.sh`: A test script to run both client and server

## Building

```bash
# Build the server
cd server
cargo build

# Build the client
cd ../client
cargo build
```

## Running

### Start the Server

```bash
cd server
cargo run -- --port 8080
```

### Run the Client

```bash
cd client
cargo run -- --uri "http://localhost:8080" --name "Your Name"
```

### Interactive Mode

```bash
cd client
cargo run -- --uri "http://localhost:8080" --interactive
```

## Testing

```bash
./test.sh
```

## Available Tools

- `hello`: A simple tool that greets a person by name
"#;

pub const PROJECT_README_STDIO_TEMPLATE: &str = r#"# {{name}} - MCP Project

A complete MCP project with both client and server components, using stdio transport.

## Features

- **Robust Communication**: Reliable stdio transport with proper error handling and timeout management
- **Multiple Connection Methods**: Connect to an already running server or start a new server process
- **Interactive Mode**: Choose tools and provide parameters interactively
- **One-shot Mode**: Run queries directly from the command line
- **Comprehensive Logging**: Detailed logging for debugging and monitoring

## Project Structure

- `client/`: The MCP client implementation
- `server/`: The MCP server implementation with tools
- `test.sh`: A test script to run both client and server

## Building

```bash
# Build the server
cd server
cargo build

# Build the client
cd ../client
cargo build
```

## Running

### Start the Server

```bash
cd server
cargo run
```

### Run the Client

```bash
cd client
cargo run -- --name "Your Name"
```

### Interactive Mode

```bash
cd client
cargo run -- --interactive
```

## Testing

```bash
./test.sh
```

## Available Tools

- `hello`: A simple tool that greets a person by name
"#;