No description
Find a file
Stanley Horwood e9a5ae9901
feat(model): add json schema generation support for all model types (#176)
* feat(model): add json schema generation support for all model types

This commit adds JSON Schema support for all model types by implementing
`schemars::JsonSchema` trait. The feature is gated behind the new
`schemars` feature flag. This enables automatic schema generation for
API documentation and validation purposes. Added tests to verify schema
generation for client and server JSON-RPC messages.

* fix(model): add manual json schema implementation for `NumberOrString`

This commit adds a manual implementation of `JsonSchema` trait for the
`NumberOrString` enum to properly represent its union type nature in
JSON Schema. The schema now correctly specifies that the type can be
either a number or a string using the `oneOf` validation keyword.

* fix(model): skip extensions field in json schema generation

The `Extensions` type was incorrectly included in JSON schema
generation, which could lead to confusing API documentation. This commit
adds `#[schemars(skip)]` attribute to all `extensions` fields in request
and notification structs, and removes the manual `JsonSchema`
implementation for the `Extensions` type since it's an internal
implementation detail that shouldn't be exposed in the schema.
2025-05-15 23:56:31 +08:00
.devcontainer Adopt Devcontainer for Development Environment (#81) 2025-04-02 12:16:49 +08:00
.github/workflows ci: security (#133) 2025-04-15 09:10:04 +08:00
crates feat(model): add json schema generation support for all model types (#176) 2025-05-15 23:56:31 +08:00
docs chore: add oauth2 support (#130) 2025-04-29 17:52:59 +08:00
examples feat(examples): Add func call support (#168) 2025-05-12 13:52:57 +08:00
.gitignore Initial commit 2025-02-18 10:55:26 +00:00
Cargo.toml fix(test): fix tool deserialization error (#68) 2025-03-31 13:05:35 +08:00
clippy.toml feat: add clippy config (#162) 2025-05-08 10:15:17 +08:00
LICENSE Initial commit 2025-02-18 10:55:26 +00:00
README.md feat(model): add json schema generation support for all model types (#176) 2025-05-15 23:56:31 +08:00
rust-toolchain.toml Move whole rmcp crate to offcial rust sdk (#44) 2025-03-27 17:33:41 -04:00
rustfmt.toml style: fmt the project (#54) 2025-03-28 23:50:46 +08:00

RMCP

Crates.io Version Release status docs.rs

An official rust Model Context Protocol SDK implementation with tokio async runtime.

Usage

Import

rmcp = { version = "0.1", features = ["server"] }
## or dev channel
rmcp = { git = "https://github.com/modelcontextprotocol/rust-sdk", branch = "main" }

Quick start

Start a client in one line:

use rmcp::{ServiceExt, transport::TokioChildProcess};
use tokio::process::Command;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = ().serve(
        TokioChildProcess::new(Command::new("npx").arg("-y").arg("@modelcontextprotocol/server-everything"))?
    ).await?;
    Ok(())
}
1. Build a transport
use tokio::io::{stdin, stdout};
let transport = (stdin(), stdout());

The transport type must implemented IntoTransport trait, which allow split into a sink and a stream.

For client, the sink item is ClientJsonRpcMessage and stream item is ServerJsonRpcMessage

For server, the sink item is ServerJsonRpcMessage and stream item is ClientJsonRpcMessage

These types is automatically implemented IntoTransport trait
  1. The types that already implement both Sink and Stream trait.
  2. A tuple of sink Tx and stream Rx: (Tx, Rx).
  3. The type that implement both [tokio::io::AsyncRead] and [tokio::io::AsyncWrite] trait.
  4. A tuple of [tokio::io::AsyncRead] R and [tokio::io::AsyncWrite] W: (R, W).

For example, you can see how we build a transport through TCP stream or http upgrade so easily. examples

2. Build a service

You can easily build a service by using ServerHandler or ClientHandler.

let service = common::counter::Counter::new();
3. Serve them together
// this call will finish the initialization process
let server = service.serve(transport).await?;
4. Interact with the server

Once the server is initialized, you can send requests or notifications:

// request 
let roots = server.list_roots().await?;

// or send notification
server.notify_cancelled(...).await?;
5. Waiting for service shutdown
let quit_reason = server.waiting().await?;
// or cancel it
let quit_reason = server.cancel().await?;

Use macros to declaring tool

Use toolbox and tool macros to create tool quickly.

Example: Calculator Tool

Check this file.

use rmcp::{ServerHandler, model::ServerInfo, schemars, tool};

use super::counter::Counter;

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct SumRequest {
    #[schemars(description = "the left hand side number")]
    pub a: i32,
    #[schemars(description = "the right hand side number")]
    pub b: i32,
}
#[derive(Debug, Clone)]
pub struct Calculator;

// create a static toolbox to store the tool attributes
#[tool(tool_box)]
impl Calculator {
    // async function
    #[tool(description = "Calculate the sum of two numbers")]
    async fn sum(&self, #[tool(aggr)] SumRequest { a, b }: SumRequest) -> String {
        (a + b).to_string()
    }

    // sync function
    #[tool(description = "Calculate the difference of two numbers")]
    fn sub(
        &self,
        #[tool(param)]
        // this macro will transfer the schemars and serde's attributes
        #[schemars(description = "the left hand side number")]
        a: i32,
        #[tool(param)]
        #[schemars(description = "the right hand side number")]
        b: i32,
    ) -> String {
        (a - b).to_string()
    }
}

// impl call_tool and list_tool by querying static toolbox
#[tool(tool_box)]
impl ServerHandler for Calculator {
    fn get_info(&self) -> ServerInfo {
        ServerInfo {
            instructions: Some("A simple calculator".into()),
            ..Default::default()
        }
    }
}

The only thing you should do is to make the function's return type implement IntoCallToolResult.

And you can just implement IntoContents, and the return value will be marked as success automatically.

If you return a type of Result<T, E> where T and E both implemented IntoContents, it's also OK.

Manage Multi Services

For many cases you need to manage several service in a collection, you can call into_dyn to convert services into the same type.

let service = service.into_dyn();

OAuth Support

See docs/OAUTH_SUPPORT.md for details.

Examples

See examples

Features

  • client: use client side sdk
  • server: use server side sdk
  • macros: macros default
  • schemars: implement JsonSchema for all model structs

Transports

  • transport-io: Server stdio transport
  • transport-sse-server: Server SSE transport
  • transport-child-process: Client stdio transport
  • transport-sse: Client sse transport
  • transport-streamable-http-server streamable http server transport

Development with Dev Container

See docs/DEVCONTAINER.md for instructions on using Dev Container for development.