Rust MCP 客户端与服务端 SDK

Rust MCP 客户端与服务端 SDK

一个易于配置的 Rust 实现的 MCP 客户端和服务端 SDK。

快速入门

依赖配置

Cargo.toml 中添加以下内容:

[dependencies]
neva = { version = "0.0.5", features = ["full"] }
tokio = { version = "1", features = ["full"] }

使用 MCP 客户端

以下代码展示如何创建并使用 MCP 客户端:

use std::time::Duration;
use neva::Client;
use neva::error::Error;

#[tokio::main]
async fn main() -> Result<(), Error> {
    let mut client = Client::new()
        .with_options(|opt| opt
            .with_stdio("npx", ["-y", "@modelcontextprotocol/server-everything"])
            .with_timeout(Duration::from_secs(5)));
    
    client.connect().await?;

    // 列出工具
    let tools = client.list_tools(None).await?;
    for tool in tools.tools {
        println!("- {}", tool.name);
    }

    // 调用工具
    let args = [
        ("message", "Hello MCP!")
    ];
    let result = client.call_tool("echo", Some(args)).await?;
    println!("{:?}", result.content);

    client.disconnect().await
}

使用 MCP 服务端

以下代码展示如何创建并运行 MCP 服务端:

use neva::{App, tool, resource, prompt};

#[tool(descr = "A say hello tool")]
async fn hello(name: String) -> String {
    format!("Hello, {name}!")
}

#[resource(uri = "res://{name}", descr = "Some details about resource")]
async fn get_res(name: String) -> (String, String) {
    (
        format!("res://{name}"),
        format!("Some details about resource: {name}")
    )
}

#[tokio::main]
async fn main() {
    let mut app = App::new()
        .with_options(|opt| opt
            .with_stdio()
            .with_name("Sample MCP server")
            .with_version("1.0.0"));

    map_hello(&mut app);
    map_get_res(&mut app);

    app.run().await;
}

更多示例和文档,请访问 API 文档示例代码