mcport 0.6.1

Fast, bounded, Tokio-free MCP stdio runtime with FastMCP-like Rust tools
Documentation
//! High-level tool registration, natural results, and lightweight schemas.

use crate::{json, Map, ToolReply, Value};
use serde::Serialize;
use std::fmt;

/// MCP tool annotation hints. These describe intended behaviour; they are not
/// a sandbox and do not prevent a handler from doing other work.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ToolAnnotations {
    /// Advertises that the tool does not modify its environment.
    pub read_only_hint: Option<bool>,
    /// Advertises that the tool may perform destructive updates.
    pub destructive_hint: Option<bool>,
    /// Advertises that repeating the call with the same arguments is safe.
    pub idempotent_hint: Option<bool>,
    /// Advertises that the tool may interact with an open world.
    pub open_world_hint: Option<bool>,
}

impl ToolAnnotations {
    /// Returns whether any annotation is set.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.read_only_hint.is_none()
            && self.destructive_hint.is_none()
            && self.idempotent_hint.is_none()
            && self.open_world_hint.is_none()
    }

    /// Serializes the non-empty annotation object used in `tools/list`.
    #[must_use]
    pub fn to_value(&self) -> Option<Value> {
        if self.is_empty() {
            return None;
        }
        let mut object = Map::new();
        if let Some(value) = self.read_only_hint {
            object.insert("readOnlyHint".to_owned(), Value::Bool(value));
        }
        if let Some(value) = self.destructive_hint {
            object.insert("destructiveHint".to_owned(), Value::Bool(value));
        }
        if let Some(value) = self.idempotent_hint {
            object.insert("idempotentHint".to_owned(), Value::Bool(value));
        }
        if let Some(value) = self.open_world_hint {
            object.insert("openWorldHint".to_owned(), Value::Bool(value));
        }
        Some(Value::Object(object))
    }
}

/// Descriptor accepted by the builder without requiring a handwritten trait.
#[derive(Debug, Clone)]
pub struct ToolDefinition {
    /// Tool name advertised to the client.
    pub name: String,
    /// One-line description advertised to the client.
    pub description: String,
    /// Optional display title.
    pub title: Option<String>,
    /// JSON Schema for tool arguments.
    pub input_schema: Value,
    /// JSON Schema for structured results, when known.
    pub output_schema: Option<Value>,
    /// Untrusted behavioural hints.
    pub annotations: ToolAnnotations,
}

impl ToolDefinition {
    /// Creates a name/description/schema descriptor.
    #[must_use]
    pub fn new(
        name: impl Into<String>,
        description: impl Into<String>,
        input_schema: Value,
    ) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            title: None,
            input_schema,
            output_schema: None,
            annotations: ToolAnnotations::default(),
        }
    }
}

pub(crate) enum PreparedInvoke<S> {
    Stateless(fn(&str) -> ToolReply),
    Stateful(fn(&mut S, &str) -> ToolReply),
}

/// Prepared adapter generated by `#[tool]` or built by hand.
pub struct PreparedTool<S> {
    pub(crate) definition: ToolDefinition,
    pub(crate) replace: bool,
    pub(crate) invoke: PreparedInvoke<S>,
}

impl<S> PreparedTool<S> {
    /// Wraps a stateless raw adapter. The state argument is ignored.
    #[must_use]
    pub fn stateless(definition: ToolDefinition, invoke: fn(&str) -> ToolReply) -> Self {
        Self {
            definition,
            replace: false,
            invoke: PreparedInvoke::Stateless(invoke),
        }
    }

    /// Wraps a stateful raw adapter.
    #[must_use]
    pub fn stateful(definition: ToolDefinition, invoke: fn(&mut S, &str) -> ToolReply) -> Self {
        Self {
            definition,
            replace: false,
            invoke: PreparedInvoke::Stateful(invoke),
        }
    }

    pub(crate) fn stateless_fn(&self) -> Option<fn(&str) -> ToolReply> {
        match self.invoke {
            PreparedInvoke::Stateless(invoke) => Some(invoke),
            PreparedInvoke::Stateful(_) => None,
        }
    }
}

/// Public tool-level failure. The message is sent to the client; do not put
/// secrets or raw third-party `Display` text here without reviewing it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolError {
    message: String,
}

impl ToolError {
    /// Creates a client-visible tool error.
    #[must_use]
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }

    /// Client-visible message.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }
}

impl fmt::Display for ToolError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl std::error::Error for ToolError {}

impl From<String> for ToolError {
    fn from(message: String) -> Self {
        Self::new(message)
    }
}

impl From<&str> for ToolError {
    fn from(message: &str) -> Self {
        Self::new(message)
    }
}

/// Explicit JSON result wrapper for types that already implement [`Serialize`].
pub struct Json<T>(pub T);

/// Converts a Rust return value into a [`ToolReply`] for the convenience API.
pub trait IntoToolReply {
    /// Consumes the value and builds a protocol reply.
    fn into_tool_reply(self) -> ToolReply;
}

impl IntoToolReply for ToolReply {
    fn into_tool_reply(self) -> ToolReply {
        self
    }
}

impl IntoToolReply for () {
    fn into_tool_reply(self) -> ToolReply {
        ToolReply::structured(json!({}))
    }
}

impl IntoToolReply for String {
    fn into_tool_reply(self) -> ToolReply {
        ToolReply::literal_text(self)
    }
}

impl IntoToolReply for &'static str {
    fn into_tool_reply(self) -> ToolReply {
        ToolReply::literal_text(self)
    }
}

impl IntoToolReply for Value {
    fn into_tool_reply(self) -> ToolReply {
        ToolReply::structured(self)
    }
}

impl<T: IntoToolReply> IntoToolReply for Result<T, ToolError> {
    fn into_tool_reply(self) -> ToolReply {
        match self {
            Ok(value) => value.into_tool_reply(),
            Err(error) => ToolReply::error(error.message),
        }
    }
}

impl<T: Serialize> IntoToolReply for Json<T> {
    fn into_tool_reply(self) -> ToolReply {
        ToolReply::structured(self.0)
    }
}

macro_rules! impl_primitive_result {
    ($($ty:ty),+ $(,)?) => {$(
        impl IntoToolReply for $ty {
            fn into_tool_reply(self) -> ToolReply {
                ToolReply::structured(json!({ "result": self }))
            }
        }
    )+};
}

impl_primitive_result!(bool, i8, i16, i32, i64, i128, u8, u16, u32, u64, u128, f32, f64);

impl<T: Serialize> IntoToolReply for Vec<T> {
    fn into_tool_reply(self) -> ToolReply {
        ToolReply::structured(json!({ "result": self }))
    }
}

/// Lightweight JSON Schema fragment for a supported Rust type.
pub trait ToolSchema {
    /// Schema node for this type.
    fn tool_schema() -> Value;

    /// Whether a field of this type is required when used as a tool argument.
    #[must_use]
    fn is_required() -> bool {
        true
    }
}

macro_rules! impl_integer_schema {
    ($($ty:ty),+ $(,)?) => {$(
        impl ToolSchema for $ty {
            fn tool_schema() -> Value {
                json!({"type": "integer"})
            }
        }
    )+};
}

impl_integer_schema!(i8, i16, i32, i64, i128, u8, u16, u32, u64, u128);

impl ToolSchema for f32 {
    fn tool_schema() -> Value {
        json!({"type": "number"})
    }
}

impl ToolSchema for f64 {
    fn tool_schema() -> Value {
        json!({"type": "number"})
    }
}

impl ToolSchema for bool {
    fn tool_schema() -> Value {
        json!({"type": "boolean"})
    }
}

impl ToolSchema for String {
    fn tool_schema() -> Value {
        json!({"type": "string"})
    }
}

impl ToolSchema for &str {
    fn tool_schema() -> Value {
        json!({"type": "string"})
    }
}

impl<T: ToolSchema> ToolSchema for Option<T> {
    fn tool_schema() -> Value {
        T::tool_schema()
    }

    fn is_required() -> bool {
        false
    }
}

impl<T: ToolSchema> ToolSchema for Vec<T> {
    fn tool_schema() -> Value {
        json!({"type": "array", "items": T::tool_schema()})
    }
}

impl<T: ToolSchema> ToolSchema for [T] {
    fn tool_schema() -> Value {
        json!({"type": "array", "items": T::tool_schema()})
    }
}

/// Builds an object schema with `additionalProperties: false`.
#[must_use]
pub fn object_schema(properties: Map<String, Value>, required: Vec<String>) -> Value {
    let required = required.into_iter().map(Value::String).collect::<Vec<_>>();
    json!({
        "type": "object",
        "properties": Value::Object(properties),
        "required": required,
        "additionalProperties": false
    })
}

/// Adds description, default, and numeric bounds to a schema node.
#[must_use]
pub fn decorate_schema(
    mut schema: Value,
    description: Option<&str>,
    default: Option<Value>,
    minimum: Option<f64>,
    maximum: Option<f64>,
) -> Value {
    let Some(object) = schema.as_object_mut() else {
        return schema;
    };
    if let Some(description) = description {
        object.insert(
            "description".to_owned(),
            Value::String(description.to_owned()),
        );
    }
    if let Some(default) = default {
        object.insert("default".to_owned(), default);
    }
    if let Some(minimum) = minimum {
        object.insert("minimum".to_owned(), json!(minimum));
    }
    if let Some(maximum) = maximum {
        object.insert("maximum".to_owned(), json!(maximum));
    }
    schema
}

#[cfg(test)]
mod tests {
    use super::{IntoToolReply, Json, ToolError};
    use crate::ToolReply;

    #[test]
    fn literal_strings_do_not_take_the_json_quote_layer() {
        let ToolReply::Literal { text } = "hello".into_tool_reply() else {
            panic!("string results must use literal text");
        };
        assert_eq!(text, "hello");
    }

    #[test]
    fn numbers_use_a_stable_object_wrapper() {
        let ToolReply::Serialized { value, .. } = 42_i64.into_tool_reply() else {
            panic!("numbers must serialize through structured output");
        };
        assert_eq!(value.get(), r#"{"result":42}"#);
    }

    #[test]
    fn result_err_is_a_tool_error_not_an_ok_enum() {
        let reply: ToolReply =
            Result::<i32, ToolError>::Err(ToolError::new("overflow")).into_tool_reply();
        assert!(matches!(reply, ToolReply::Error(message) if message == "overflow"));
    }

    #[test]
    fn json_wrapper_serializes_the_inner_value() {
        match Json(vec![1, 2]).into_tool_reply() {
            ToolReply::Serialized { value, .. } | ToolReply::StructuredAny { value } => {
                assert_eq!(value.get(), "[1,2]");
            }
            other => panic!("Json<T> must serialize T, got {other:?}"),
        }
    }
}