Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A type-safe implementation of the official Model Context Protocol (MCP) schema in Rust.

License

NotificationsYou must be signed in to change notification settings

rust-mcp-stack/rust-mcp-schema

Repository files navigation

Description

Model Context Protocol (MCP) Schema for Rust

crates.iodocs.rsbuild status

A type-safe Rust implementation of the official Model Context Protocol (MCP) schema, supporting all official MCP Protocol versions:

  • 2025-11-25
  • 2025-06-18
  • 2025-03-26
  • 2024-11-05
  • draft

The MCP schemas in this repository areautomatically generated from the official Model Context Protocol, ensuring they are always up-to-date and aligned with the latest official specifications.


Note: This crateonly provides an implementation of the MCP schema.

If you are looking for a high-performance, asynchronous toolkit for building MCP servers and clients, checkoutrust-mcp-sdk.Focus on your app's logic whilerust-mcp-sdk takes care of the rest!


Contents:

Features

  • 🧩 Type-safe implementation of the MCP protocol specification.
  • 💎 Auto-generated schemas are always synchronized with the official schema specifications.
  • 📜 Includes all official released versions :2025-11-25,2025-06-18,2025-03-26,2024-11-05 anddraft version for early adoption.
  • 🛠 Complimentary schema utility module (schema_utils) to boost productivity and ensure development integrity.

How can this crate be used?

This Crate provides Rust implementation of the official Model Context Protocol (MCP) schema.

Model Context Protocol (MCP) is an open protocol that enables seamless integration between LLM applications and external data sources and tools. Whether you’re building an AI-powered IDE, enhancing a chat interface, or creating custom AI workflows, MCP provides a standardized way to connect LLMs with the context they need.

This crate includes the schema withserialization /deserialization support via serde_json, along with a minimal implementation of the necessary traits for structs and enums. This helps in creating and using various MCP messages such as requests, responses, notifications, and errors.

This crate could be used for developing anMCP Server orMCP Client in Rust.For more information on the MCP architecture, refer to theofficial documentation.


Check outrust-mcp-sdk , a high-performance, asynchronous toolkit for building MCP servers and clients which is based onrust-mcp-schema. Focus on your app's logic whilerust-mcp-sdk takes care of the rest!


Schema Versions

This repository provides all official released versions the schema , including draft version, enabling you to prepare and adapt your applications ahead of upcoming official schema releases.

How to switch between different schema versions?

By default, the latest version of the MCP Protocol schema is enabled.

Each schema version has a corresponding Cargo feature that can be enabled in your project's Cargo.toml.

Multiple schema versions may be enabled concurrently if needed. Non-default versions are available under explicitly named modules, for example:

  • rust_mcp_schema::mcp_2025_06_18
  • rust_mcp_schema::mcp_draft"

Example: enable2025-06-18 version of the schema:

# Cargo.tomlrust-mcp-schema = { version: 0.9.1 ,default-features =false,features=["2025_06_18"] }

Example: enable `draft`` version of the schema :

#Cargo.tomlrust-mcp-schema = { version: 0.9.1 ,default-features =false,features=["draft"] }

How are Schemas generated?

Schemas are generated from the officialschema.ts andschema.json files available in the originalModel Context Protocol (MCP) repository.

Using a customized version oftypify, along with additional pre-processing and post-processing steps, the schema specifications are transformed into Rust code.

📌 Note

The code used to generate schemas fromschema.ts andschema.json is not included in this repository. However, I am considering making it available as a CLI tool in the future, allowing developers to generate MCP schemas as Rust code that can be directly integrated into their projects.

What isschema_utils?

The Rust implementations of the MCP schemas in this crate are automatically generated from the official MCP GitHub repository.

mcp_schema.rs provides all the core structures and enums with serialization/deserialization support, allowing you to use them as needed and extend their functionality.

To streamline development, improve compile-time type checking, and reduce the potential for errors, we’ve implemented utility types and functions that offer more strongly-typed objects and implementations, all without modifying the originally generated schema.

Please refer toschema_utils.rs for more details.

📌 Note

Using schema_utils is optional. It is enabled by default through the schema_utils Cargo feature and can be used fromrust_mcp_schema::schema_utils.

If you prefer not to use schema_utils, you can directly work with the enums and structs provided inmcp_schema.rs, adapting them to your needs and creating your own utility types and functions around them.

VisitUsage Examples (WithoutUsing schema_utils) to see an alternative approach.

What does the schema_utils do?

The official schema defines a unifiedJsonrpcMessage type that encompasses all messages and notifications within the MCP protocol.

To enhance type safety and usability,schema_utils divides JsonrpcMessage into two distinct categories:ClientMessage andServerMessage. Each category includes the relevant types for both standard and custom messages.

Please refer toschema_utils.rs and theUsage Examples section for more details.

Usage Examples

👉 The following examples focus solely on the serialization and deserialization of schema messages, assuming the JSON-RPC message has already been received in the application as a string.

Detecting anInitializeRequest Message on an MCP Server

The following code snippet demonstrates how an MCP message, represented as a JSON string, can be deserialized into a ClientMessage and how to identify it as an InitializeRequest message.

Note: ClientMessage represents MCP messages sent from an MCP client. The following code demonstrates how an MCP server can deserialize received messages from an MCP client.

pubfnhandle_messagew(message_payload:&str) -> std::result::Result<(),RpcError>{// Deserialize message into ClientMessage.let message =ClientMessage::from_str(&message_payload)?;// Check if the message is a RequestifletClientMessage::Request(message_object) = message{// Check if it's an InitializeRequestifletClientRequest::InitializeRequest(initialize_request) = client_request{// Process the InitializeRequest (and eventually send back a InitializedNotification back to the server)handle_initialize_request(initialize_request);}}Ok(())}

Refer toexamples/mcp_server_handle_message.rs for a complete match implementation that handles all possibleClientMessage variants.

Creating anInitializeResult Response on an MCP Server.

In response to an InitializeRequest, the MCP Server is expected to return an InitializeResult message.

This code snippet demonstrates how to create an InitializeRequest, serialize it into a string, and send it back to the client via the transport layer.

// create InitializeResult objectlet initial_result =InitializeResult{capabilities:ServerCapabilities{logging:None,prompts:Some(ServerCapabilitiesPrompts{list_changed:Some(true)}),resources:Some(ServerCapabilitiesResources{list_changed:Some(true),subscribe:Some(true)}),tools:Some(ServerCapabilitiesTools{list_changed:Some(true)}),completions:None,tasks:Some(ServerTasks{cancel:Some(Map::new()),list:Some(Map::new()),requests:None}),experimental:None,},instructions:Some(String::from("mcp server instructions....")),meta:Some(json!({"meta 1": serde_json::Value::String("meta-value".into()),"meta 2": serde_json::Value::Number(serde_json::Number::from(225)),"feature-xyz": serde_json::Value::Bool(true)}).as_object().unwrap().to_owned(),),protocol_version:ProtocolVersion::V2025_11_25.into(),server_info:Implementation{name:String::from("rust mcp server"),title:Some("Cool mcp server!".into()),version:String::from("1.0.0"),description:Some("your rust mcp server description....".into()),icons:vec![],website_url:Some("https://github.com/rust-mcp-stack/rust-mcp-schema".into()),},};// JsonrpcResultResponse  vs  JsonrpcResponse// Create a ServerMessage (a message intended to be sent from the server)let message =ServerJsonrpcResponse::new(RequestId::Integer(0), initial_result.into());// Serialize the MCP message into a valid JSON string for sending to the clientlet json_payload = serde_json::to_string(&message).unwrap();println!("{}", json_payload);

output:

{"id":0,"jsonrpc":"2.0","result": {"capabilities": {"prompts": {"listChanged":true },"resources": {"listChanged":true,"subscribe":true },"tasks": {"cancel": {},"list": {} },"tools": {"listChanged":true }    },"instructions":"mcp server instructions....","protocolVersion":"2025-11-25","serverInfo": {"description":"your rust mcp server description....","name":"rust mcp server","title":"Cool mcp server!","version":"1.0.0","websiteUrl":"https://github.com/rust-mcp-stack/rust-mcp-schema"    },"_meta": {"feature-xyz":true,"meta 1":"meta-value","meta 2":225 }  }}

Detecting anInitializeResult Response Message in an MCP Client:

fnhandle_message(message_payload:&str) -> std::result::Result<(),AppError>{// Deserialize message into ServerMessage.// ServerMessage represents a message sent by an MCP Server and received by an MCP Client.let mcp_message =ServerMessage::from_str(message_payload)?;// Check if the message is a Response type of messageifletServerMessage::Response(server_response) = mcp_message{// Check if it's a InitializeResult responseifletServerResult::InitializeResult(initialize_result) = server_response.result{//Process the InitializeResult and send an InitializedNotification back to the server for acknowledgment.handle_initialize_result(initialize_request);}}Ok(())}

Refer tomcp_client_handle_message.rs for a complete match implementation that handles all possibleServerMessage variants.

Usage Examples (Without Utilizingschema_utils)

If you prefer not to use schema_utils, you can directly work with the generated types in your application or build custom utilities around them.

Detecting an InitializeRequest Message on an MCP Server (without schema_utils)

The following code example illustrates how to detect an InitializeRequest message on an MCP server:

fnhandle_message(message_payload:&str) -> std::result::Result<(),AppError>{// Deserialize json string into JsonrpcMessagelet message:JsonrpcMessage = serde_json::from_str(message_payload).unwrap();// Check it's a Request type of messageifletJsonrpcMessage::Request(client_message) = message{let client_request:ClientRequest = serde_json::from_value(client_message.params.into()).unwrap();// Check method to detect is a "initialize" requestifletClientRequest::InitializeRequest(initialize_request) = client_request{// Now that we can handle the message, we simply print out the details.println!("Initialize request received!");println!("Client name : {:?} ", initialize_request.params.client_info.name);println!("Client version : {:?} ", initialize_request.params.client_info.version);}}Ok(())}

Contributing

We welcome everyone who wishes to contribute! Please refer to thecontributing guidelines for more details.

All contributions, including issues and pull requests, must followRust's Code of Conduct.

Unless explicitly stated otherwise, any contribution you submit for inclusion inrust-mcp-schema is provided under the terms of the MIT License, without any additional conditions or restrictions.

About

A type-safe implementation of the official Model Context Protocol (MCP) schema in Rust.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors2

  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp