Skip to main content

mcp_skill_framework/
lib.rs

1//! # mcp-skill-framework
2//!
3//! A small framework for building [Model Context Protocol][mcp] servers on top
4//! of [`rmcp`] as a uniform layer of self-contained tools called **skills**.
5//!
6//! Each tool you expose is a [`Skill`]: a type with a `name`, a `description`,
7//! a JSON-schema'd argument struct, and an async `call` body. The framework
8//! adds the cross-cutting machinery every skill ends up wanting:
9//!
10//! - **Declarative input validation** ([`validation`]) — assert ranges, enums,
11//!   mutual exclusion, regex, and length as data ([`Rule`]s). The dispatcher
12//!   evaluates them before your body runs and returns a structured
13//!   `{"validation_failed": [...]}` payload a calling model can correct from.
14//! - **Capability probes** ([`SkillCapability`]) — answer "can this host
15//!   actually run this tool?" (a binary on `$PATH`, a reachable socket)
16//!   separately from whether the operator enabled it.
17//!   [`capability::resolve`] combines each tool's probe with its family's
18//!   ("family `Unavailable` wins"), and [`routes_gated`] blocks unavailable
19//!   tools at dispatch with a reason + hint the caller can act on.
20//! - **Family metadata** ([`FamilyMeta`]) — group related skills, describe
21//!   them, and probe their shared host requirement as a unit.
22//! - **Rich descriptions** ([`describe`]) — render a skill or family
23//!   (description, use cases, worked examples, validation rules, argument
24//!   schema) for an on-demand introspection tool.
25//! - **A ready-made dispatcher** ([`route_skill`]) — adapt a [`Skill`] into an
26//!   [`rmcp`] tool route with the validation gate already wired in.
27//!
28//! The [`Skill`] trait is generic over a server-state type `S` — whatever
29//! shared state your tools need (HTTP clients, DB handles, config). The
30//! framework never inspects `S`; it just hands each call a `&S`.
31//!
32//! ## Quickstart
33//!
34//! ```no_run
35//! use std::sync::Arc;
36//! use futures::future::BoxFuture;
37//! use mcp_skill_framework::{schema_for, text_result, Rule, Skill, SkillCtx, SkillExample};
38//! use rmcp::model::{CallToolResult, JsonObject};
39//! use rmcp::ErrorData as McpError;
40//! use serde::Deserialize;
41//!
42//! struct App; // your shared server state
43//!
44//! #[derive(Deserialize, schemars::JsonSchema)]
45//! struct FormatArgs {
46//!     /// Total seconds to format.
47//!     seconds: i64,
48//!     /// Output style: `human` or `hms`.
49//!     #[serde(default)]
50//!     style: Option<String>,
51//! }
52//!
53//! struct Format;
54//! impl Skill<App> for Format {
55//!     fn name(&self) -> &'static str { "duration_format" }
56//!     fn description(&self) -> &'static str { "Format seconds as `human` or `hms`." }
57//!     fn schema(&self) -> Arc<JsonObject> { schema_for::<FormatArgs>() }
58//!     fn validation_rules(&self) -> &'static [Rule] {
59//!         &[Rule::OneOf { field: "style", values: &["human", "hms"] }]
60//!     }
61//!     fn examples(&self) -> &'static [SkillExample] {
62//!         &[SkillExample { title: "HH:MM:SS", args: r#"{"seconds": 9045, "style": "hms"}"#, note: None }]
63//!     }
64//!     fn call<'a>(&self, ctx: SkillCtx<'a, App>) -> BoxFuture<'a, Result<CallToolResult, McpError>> {
65//!         Box::pin(async move {
66//!             let (_app, a) = ctx.parse::<FormatArgs>()?;
67//!             Ok(text_result(format!("{} seconds", a.seconds)))
68//!         })
69//!     }
70//! }
71//!
72//! // Register with an rmcp ToolRouter:
73//! // let mut router = rmcp::handler::server::router::tool::ToolRouter::new();
74//! // router.add_route(mcp_skill_framework::route_skill(Box::new(Format)));
75//! ```
76//!
77//! ## Relationship to `rmcp`
78//!
79//! This is a thin layer on top of [`rmcp`], not a wall around it. [`Skill`] and
80//! [`route_skill`] are defined directly in terms of rmcp's own types
81//! (`CallToolResult`, `ErrorData`, `JsonObject`, `ToolRoute`), so you keep full
82//! access to everything rmcp offers: you build the `ToolRouter`, implement
83//! `ServerHandler`, and choose a transport with rmcp, and just `add_route` the
84//! routes this crate produces.
85//!
86//! rmcp is re-exported as [`mcp_skill_framework::rmcp`](rmcp) so you can name
87//! those types and stay pinned to one compatible version without adding rmcp
88//! yourself. If you want an rmcp transport *feature* for the server side (stdio,
89//! streamable HTTP, …), add `rmcp` to your own `Cargo.toml` with that feature —
90//! Cargo unifies it with the version re-exported here. Your argument structs
91//! still derive `serde::Deserialize` + `schemars::JsonSchema` as in any
92//! schema'd-serde crate, so add those two; [`schemars`](crate::schemars) is
93//! re-exported for version reference. The [`prelude`] glob-imports the handful
94//! of names a skill body needs.
95//!
96//! [mcp]: https://modelcontextprotocol.io
97
98pub mod capability;
99pub mod describe;
100pub mod dispatch;
101pub mod family;
102pub mod skill;
103pub mod validation;
104
105pub use capability::{Capabilities, SkillCapability};
106pub use dispatch::{route_skill, route_skill_gated, routes_gated, with_extra_property};
107pub use family::FamilyMeta;
108pub use skill::{schema_for, NoArgs, Skill, SkillCtx, SkillExample};
109pub use validation::{evaluate, FieldViolation, Rule, ValidationResult};
110
111// Re-export the foundational crates whose types appear in this crate's public
112// API, so consumers name them through a single, version-compatible path and
113// don't have to add (and keep in lockstep) a separate dependency.
114
115/// The [`rmcp`] this crate is built on, re-exported. Use it to name the types in
116/// a [`Skill::call`] signature and to build your `ToolRouter` / `ServerHandler`
117/// / transport against the exact version this crate expects.
118pub use rmcp;
119
120/// The [`schemars`] whose `JsonSchema` [`schema_for`] requires, re-exported so
121/// you can pin a matching version — and point the derive at it with
122/// `#[schemars(crate = "mcp_skill_framework::schemars")]` if you'd rather not
123/// add `schemars` to your own manifest.
124pub use schemars;
125
126/// `BoxFuture`, the return type of [`Skill::call`], re-exported from `futures`.
127pub use futures::future::BoxFuture;
128
129use rmcp::model::{CallToolResult, Content};
130use rmcp::ErrorData as McpError;
131
132/// Everything a skill body typically needs, in one glob import.
133///
134/// ```
135/// use std::sync::Arc;
136/// use mcp_skill_framework::prelude::*;
137///
138/// struct App;
139///
140/// #[derive(serde::Deserialize, schemars::JsonSchema)]
141/// struct Args {
142///     /// Who to greet.
143///     name: String,
144/// }
145///
146/// struct Greet;
147/// impl Skill<App> for Greet {
148///     fn name(&self) -> &'static str { "greet" }
149///     fn description(&self) -> &'static str { "Greet someone." }
150///     fn schema(&self) -> Arc<JsonObject> { schema_for::<Args>() }
151///     fn call<'a>(&self, ctx: SkillCtx<'a, App>) -> BoxFuture<'a, Result<CallToolResult, McpError>> {
152///         Box::pin(async move {
153///             let (_app, a) = ctx.parse::<Args>()?;
154///             Ok(text_result(format!("Hello, {}!", a.name)))
155///         })
156///     }
157/// }
158/// ```
159pub mod prelude {
160    pub use crate::{
161        internal, invalid, route_skill, route_skill_gated, routes_gated, schema_for, text_result,
162        BoxFuture, Capabilities, FamilyMeta, NoArgs, Rule, Skill, SkillCapability, SkillCtx,
163        SkillExample, ValidationResult,
164    };
165    pub use rmcp::model::{CallToolResult, JsonObject};
166    pub use rmcp::ErrorData as McpError;
167}
168
169/// Wrap a string as a successful single-text-content tool result. The
170/// idiomatic return for a skill body that produced one textual answer (often
171/// a JSON string built with [`serde_json`]).
172pub fn text_result(s: impl Into<String>) -> CallToolResult {
173    CallToolResult::success(vec![Content::text(s.into())])
174}
175
176/// Build an `invalid_params` MCP error from anything `Display`. Use for bad
177/// caller input that the declarative [`validation`] layer didn't catch.
178pub fn invalid(e: impl std::fmt::Display) -> McpError {
179    McpError::invalid_params(e.to_string(), None)
180}
181
182/// Build an `internal_error` MCP error from anything `Display`. Use for
183/// failures that aren't the caller's fault (an upstream API, a socket, a parse
184/// of data you fetched).
185pub fn internal(e: impl std::fmt::Display) -> McpError {
186    McpError::internal_error(e.to_string(), None)
187}