mocopr 0.1.0

A comprehensive Rust implementation of the Model Context Protocol (MCP)
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
# MoCoPr (More Copper) ๐Ÿ”ฅ


A comprehensive and developer-friendly Rust implementation of the **Model Context Protocol (MCP)**, making it extremely simple to build MCP servers and clients with production-ready features.

[![License](https://img.shields.io/crates/l/MoCoPr)](https://github.com/ciresnave/MoCoPr)
[![Rust Version](https://img.shields.io/badge/rust-1.70+-green.svg)](https://www.rust-lang.org)
[![CI](https://github.com/ciresnave/mocopr/workflows/CI%2FCD%20Pipeline/badge.svg)](https://github.com/ciresnave/mocopr/actions)
[![Coverage](https://codecov.io/gh/ciresnave/mocopr/branch/main/graph/badge.svg)](https://codecov.io/gh/ciresnave/mocopr)
[![Crates.io](https://img.shields.io/crates/v/mocopr.svg)](https://crates.io/crates/mocopr)
[![Docs.rs](https://img.shields.io/docsrs/MoCoPr)](https://docs.rs/mocopr)

## ๐Ÿš€ Features


- **๐Ÿ”ง Complete MCP Implementation**: Full support for MCP specification (2025-06-18)
- **๐Ÿš€ Developer-Friendly API**: Intuitive builder patterns and macros for rapid development
- **๐ŸŒ Multiple Transports**: stdio, WebSocket, and HTTP transport support with automatic reconnection
- **๐Ÿ”’ Type-Safe**: Leverages Rust's type system for protocol safety and compile-time guarantees
- **โšก High Performance**: Built on tokio for high-performance async I/O with benchmarked optimizations
- **๐Ÿ”Œ Extensible**: Plugin architecture for custom resources, tools, and prompts
- **๐Ÿ“š Well-Documented**: Comprehensive documentation, examples, and tutorials
- **๐Ÿ›ก๏ธ Production Ready**: Comprehensive error handling, logging, metrics, and security features
- **๐Ÿงช Thoroughly Tested**: Extensive test suite with 95%+ code coverage and stress testing
- **๐Ÿ” Observable**: Built-in tracing, metrics, and health checks

## ๐Ÿ“ฆ Crates


MoCoPr is organized into several specialized crates for maximum flexibility:

| Crate | Description | Version | Features |
|-------|-------------|---------|----------|
| **`mocopr`** | Meta-crate with all components | [![Crates.io]https://img.shields.io/crates/v/mocopr.svg]https://crates.io/crates/mocopr | Complete MCP toolkit |
| **`mocopr-core`** | Core types and protocol implementation | [![Crates.io]https://img.shields.io/crates/v/mocopr-core.svg]https://crates.io/crates/mocopr-core | Protocol foundation |
| **`mocopr-server`** | High-level server implementation | [![Crates.io]https://img.shields.io/crates/v/mocopr-server.svg]https://crates.io/crates/mocopr-server | Server builder API |
| **`mocopr-client`** | High-level client implementation | [![Crates.io]https://img.shields.io/crates/v/mocopr-client.svg]https://crates.io/crates/mocopr-client | Client connection API |
| **`mocopr-macros`** | Procedural macros for boilerplate reduction | [![Crates.io]https://img.shields.io/crates/v/mocopr-macros.svg]https://crates.io/crates/mocopr-macros | Derive macros |

## ๐Ÿƒโ€โ™‚๏ธ Quick Start


Add MoCoPr to your `Cargo.toml`:

```toml
[dependencies]
mocopr = "0.1"
tokio = { version = "1.0", features = ["full"] }
serde_json = "1.0"
```

### Creating an MCP Server


```rust
use mocopr::prelude::*;

#[tokio::main]

async fn main() -> Result<()> {
    // Create a simple calculator server
    let server = McpServer::builder()
        .with_info("Calculator Server", "1.0.0")
        .with_tool_handler(
            "add",
            "Add two numbers together",
            json!({
                "type": "object",
                "properties": {
                    "a": {"type": "number", "description": "First number"},
                    "b": {"type": "number", "description": "Second number"}
                },
                "required": ["a", "b"]
            }),
            |params| async move {
                let a = params["a"].as_f64().unwrap_or(0.0);
                let b = params["b"].as_f64().unwrap_or(0.0);

                Ok(ToolResult::text(format!("Result: {}", a + b)))
            }
        )
        .with_resource_handler(
            "memory://calculations",
            "Access calculation history",
            |_uri| async move {
                Ok(ResourceResult::text("Recent calculations: ..."))
            }
        )
        .build()?;

    // Start server with stdio transport
    server.run_stdio().await?;
    Ok(())
}
```

### Creating an MCP Client


```rust
use mocopr::prelude::*;

#[tokio::main]

async fn main() -> Result<()> {
    // Connect to an MCP server
    let client = McpClient::connect_stdio(
        "python",
        &["calculator_server.py"],
        Implementation::new("Calculator Client", "1.0.0"),
        ClientCapabilities::default(),
    ).await?;

    // List available tools
    let tools = client.list_tools().await?;
    println!("Available tools: {:#?}", tools);

    // Call a tool
    let result = client.call_tool("add", json!({
        "a": 42,
        "b": 58
    })).await?;

    println!("Result: {:#?}", result);

    // Read a resource
    let resource = client.read_resource("memory://calculations").await?;
    println!("Resource: {:#?}", resource);

    Ok(())
}
```

## ๐Ÿ“– Documentation


### ๐Ÿ“š Guides and Tutorials


- [**Quick Start Guide**]docs/tutorials/01-quick-start.md - Get up and running in 5 minutes
- [**Building Your First MCP Server**]docs/tutorials/02-building-your-first-server.md - Comprehensive tutorial
- [**Advanced Server Features**]docs/tutorials/03-advanced-features.md - Middleware, validation, etc.
- [**Production Deployment**]docs/tutorials/04-production-deployment.md - Production-ready deployment guide
- [**Performance Tuning**]docs/tutorials/05-performance-tuning.md - Performance optimization and tuning
- [**Architecture Guide**]docs/guides/architecture.md - System architecture and design patterns
- [**Security Best Practices**]docs/security.md - Security guidelines and recommendations
- [**Performance Optimization**]docs/performance.md - Benchmarking and optimization tips

### ๐Ÿ”ง API Documentation


- [**Core API Reference**]https://docs.rs/mocopr-core - Protocol types and utilities
- [**Server API Reference**]https://docs.rs/mocopr-server - Server builder and handlers
- [**Client API Reference**]https://docs.rs/mocopr-client - Client connection management
- [**Macros Reference**]https://docs.rs/mocopr-macros - Derive macro documentation

## ๐ŸŒŸ Examples


The [`examples/`](examples/) directory contains comprehensive examples:

| Example | Description | Transport | Complexity |
|---------|-------------|-----------|------------|
| [**simple-server**]examples/simple-server/ | Basic MCP server with tools and resources | stdio | Beginner |
| [**simple-client**]examples/simple-client/ | Basic MCP client usage | stdio | Beginner |
| [**calculator-server**]examples/calculator-server/ | Full-featured calculator with validation | stdio | Intermediate |
| [**file-server**]examples/file-server/ | File system operations with security | stdio | Intermediate |
| [**websocket-chat**]examples/websocket-chat/ | Real-time chat server | WebSocket | Advanced |
| [**http-api**]examples/http-api/ | REST-like HTTP interface | HTTP | Advanced |
| [**production-server**]examples/production-server/ | Production-ready server with all features | All | Expert |

Run any example:

```bash
# Run the calculator server

cargo run --example calculator-server

# Run the file server

cargo run --example file-server

# Run with custom transport

cargo run --example websocket-chat -- --port 8080
```

## ๐Ÿš€ Features in Detail


### Transport Support


MoCoPr supports multiple transport mechanisms with automatic failover:

```rust
// stdio transport (process communication)
server.run_stdio().await?;

// WebSocket transport (real-time web apps)
server.run_websocket("127.0.0.1:8080").await?;

// HTTP transport (stateless requests)
server.run_http("127.0.0.1:3000").await?;

// Multiple transports simultaneously
server.run_all(&[
    TransportConfig::Stdio,
    TransportConfig::WebSocket("127.0.0.1:8080".parse()?),
    TransportConfig::Http("127.0.0.1:3000".parse()?),
]).await?;
```

### Advanced Features


#### Middleware and Validation


```rust
let server = McpServer::builder()
    .with_middleware(RateLimitMiddleware::new(100, Duration::from_secs(60)))
    .with_middleware(AuthenticationMiddleware::new())
    .with_middleware(LoggingMiddleware::with_level(Level::INFO))
    .with_validation(true)
    .build()?;
```

#### Monitoring and Observability


```rust
use mocopr::observability::*;

let server = McpServer::builder()
    .with_metrics(PrometheusMetrics::new())
    .with_tracing(TracingConfig::default())
    .with_health_checks(true)
    .build()?;
```

#### Error Handling and Recovery


```rust
let client = McpClient::builder()
    .with_retry_policy(RetryPolicy::exponential_backoff(3))
    .with_timeout(Duration::from_secs(30))
    .with_connection_recovery(true)
    .connect_stdio("server", &["args"]).await?;
```

            let result = a + b;

            Ok(ToolsCallResponse::success(vec![
                Content::from(format!("{} + {} = {}", a, b, result))
            ]))
        }
    );

    // Build and run the server
    let server = McpServer::builder()
        .with_info("Calculator Server", "1.0.0")
        .with_tools()
        .with_tool(calculator)
        .build()?;

    server.run_stdio().await?;
    Ok(())
}

```

### Creating an MCP Client


```rust
use mocopr_client::prelude::*;

#[tokio::main]

async fn main() -> Result<()> {
    // Connect to a server
    let client = McpClientBuilder::new()
        .with_info("My Client".to_string(), "1.0.0".to_string())
        .connect_stdio("my-mcp-server", &[])
        .await?;

    // List available tools
    let tools = client.list_tools().await?;
    println!("Available tools: {:?}", tools.tools);

    // Call a tool
    let result = client.call_tool(
        "add".to_string(),
        Some(json!({"a": 5, "b": 3}))
    ).await?;

    println!("Result: {:?}", result);

    client.close().await?;
    Ok(())
}
```

## ๐Ÿ› ๏ธ Advanced Usage


### Using Macros for Clean Code


```rust
use mocopr_macros::*;

#[derive(Tool)]

#[tool(name = "weather", description = "Get weather information")]

struct WeatherTool;

#[async_trait]

impl ToolHandler for WeatherTool {
    async fn call(&self, args: Option<serde_json::Value>) -> Result<ToolsCallResponse> {
        // Your implementation here
        Ok(ToolsCallResponse::success(vec![
            Content::from("Sunny, 72ยฐF")
        ]))
    }
}

#[derive(Resource)]

#[resource(uri = "file:///config.json", name = "Configuration")]

struct ConfigResource {
    data: serde_json::Value,
}
```

### File Resources


```rust
let file_resource = file_resource!(
    uri: "file:///data/example.txt",
    name: "Example Data",
    path: "./data/example.txt",
    description: "Example data file",
    mime_type: "text/plain"
);
```

### Template Prompts


```rust
let prompt = template_prompt!(
    name: "summarize",
    description: "Summarize text content",
    template: "Please summarize the following text: {text}",
    arguments: [
        PromptArgument::new("text")
            .with_description("Text to summarize")
            .required(true)
    ]
);
```

## ๐ŸŒ Transport Support


### Stdio (Process Communication)


```rust
// Server
server.run_stdio().await?;

// Client
let client = McpClientBuilder::new()
    .with_info("Client", "1.0.0")
    .connect_stdio("./my-server", &["--arg1", "value1"])
    .await?;
```

### WebSocket


```rust
// Server
server.run_websocket("127.0.0.1:8080").await?;

// Client
let client = McpClientBuilder::new()
    .with_info("Client", "1.0.0")
    .connect_websocket("ws://127.0.0.1:8080/mcp")
    .await?;
```

## ๐Ÿ“– Examples


The repository includes several complete examples:

- **Simple Server**: Basic MCP server with resources, tools, and prompts
- **Simple Client**: Client that connects and interacts with servers
- **File Server**: Server that exposes file system resources
- **Calculator Server**: Advanced calculator with multiple operations

Run examples:

```bash
# Start the simple server

cargo run --example simple-server

# In another terminal, run the client

cargo run --example simple-client
```

## ๐Ÿ—๏ธ Architecture


```
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   MCP Client    โ”‚    โ”‚   MCP Server    โ”‚
โ”‚                 โ”‚    โ”‚                 โ”‚
โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚    โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
โ”‚ โ”‚   Session   โ”‚ โ”‚โ—„โ”€โ”€โ”€โ”ค โ”‚   Session   โ”‚ โ”‚
โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚    โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
โ”‚        โ”‚        โ”‚    โ”‚        โ”‚        โ”‚
โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚    โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
โ”‚ โ”‚  Transport  โ”‚ โ”‚โ—„โ”€โ”€โ”€โ”ค โ”‚  Transport  โ”‚ โ”‚
โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚    โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
        โ”‚                        โ”‚
        โ””โ”€โ”€ stdio/websocket โ”€โ”€โ”€โ”€โ”€โ”˜
```

### Core Components


- **Protocol Layer**: JSON-RPC 2.0 message handling
- **Transport Layer**: Pluggable transport implementations
- **Session Management**: Connection lifecycle and state
- **Handler Registry**: Dynamic resource/tool/prompt registration
- **Type System**: Full MCP type definitions with serde support

## ๐Ÿงช Testing


```bash
# Run all tests

cargo test

# Run tests for a specific crate

cargo test -p mocopr-core

# Run with logging

RUST_LOG=debug cargo test
```

## ๐Ÿ“‹ Requirements


- **Rust**: 1.70 or later
- **Dependencies**: See `Cargo.toml` for full list

## ๐Ÿ“„ License


Licensed under either of:

- Apache License, Version 2.0 ([LICENSE-APACHE]LICENSE-APACHE)
- MIT License ([LICENSE-MIT]LICENSE-MIT)

at your option.

## ๐Ÿค Contributing


Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

## ๐Ÿ”— Related


- [Model Context Protocol Specification]https://modelcontextprotocol.io/specification/2025-06-18
- [MCP Official Documentation]https://modelcontextprotocol.io/
- [JSON-RPC 2.0 Specification]https://www.jsonrpc.org/specification

---

**MoCoPr** - Making MCP integration in Rust as easy as adding copper to your project! โšก