turul_mcp_builders/lib.rs
1//! Runtime builders for MCP (Model Context Protocol) components
2//!
3//! This crate provides builder patterns for all MCP areas, enabling runtime construction
4//! of tools, resources, prompts, and other protocol components. This is "Level 3" of the
5//! MCP creation spectrum - runtime flexibility for dynamic/configuration-driven systems.
6//!
7//! # Quick Start
8//!
9//! ```rust
10//! use turul_mcp_builders::prelude::*;
11//!
12//! // All builders and common types available
13//! ```
14//!
15//! # Features
16//! - Runtime tool construction with `ToolBuilder`
17//! - Dynamic resource creation with `ResourceBuilder`
18//! - Prompt template building with `PromptBuilder`
19//! - Message composition with `MessageBuilder`
20//! - Completion context building with `CompletionBuilder`
21//! - Root directory configuration with `RootBuilder`
22//! - User input collection with `ElicitationBuilder`
23//! - Notification creation with `NotificationBuilder`
24//! - Logging message construction with `LoggingBuilder`
25//!
26//! # Example
27//! ```rust
28//! use turul_mcp_builders::{
29//! ToolBuilder, ResourceBuilder, PromptBuilder, MessageBuilder,
30//! CompletionBuilder, RootBuilder, ElicitationBuilder,
31//! NotificationBuilder, LoggingBuilder
32//! };
33//! use serde_json::json;
34//! use std::collections::HashMap;
35//!
36//! # #[tokio::main]
37//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
38//! // Create a calculator tool at runtime
39//! let tool = ToolBuilder::new("calculator")
40//! .description("Add two numbers")
41//! .number_param("a", "First number")
42//! .number_param("b", "Second number")
43//! .execute(|args| async move {
44//! let a = args.get("a").and_then(|v| v.as_f64()).ok_or("Missing 'a'")?;
45//! let b = args.get("b").and_then(|v| v.as_f64()).ok_or("Missing 'b'")?;
46//! Ok(json!({"result": a + b}))
47//! })
48//! .build()?;
49//!
50//! // Create a resource at runtime
51//! let resource = ResourceBuilder::new("file:///config.json")
52//! .name("app_config")
53//! .description("Application configuration file")
54//! .json_content(json!({"version": "1.0", "debug": false}))
55//! .build()?;
56//!
57//! // Create a prompt template at runtime
58//! let prompt = PromptBuilder::new("greeting")
59//! .description("Generate personalized greetings")
60//! .string_argument("name", "Person to greet")
61//! .user_message("Hello {name}! How are you today?")
62//! .assistant_message("Nice to meet you!")
63//! .build()?;
64//!
65//! // Execute the tool
66//! let result = tool.execute(json!({"a": 5.0, "b": 3.0})).await?;
67//! assert_eq!(result, json!({"result": 8.0}));
68//!
69//! // Read the resource
70//! let content = resource.read().await?;
71//! // content is ResourceContent::Text with JSON data
72//!
73//! // Get the prompt with arguments
74//! let mut args = HashMap::new();
75//! args.insert("name".to_string(), "Alice".to_string());
76//! let prompt_result = prompt.get(args).await?;
77//! // prompt_result contains processed messages with "Alice" substituted
78//!
79//! // Additional builders available:
80//!
81//! // Create sampling messages for LLM interaction
82//! let message_request = MessageBuilder::new()
83//! .max_tokens(500)
84//! .temperature(0.7)
85//! .user_text("Explain quantum computing")
86//! .build_request();
87//!
88//! // Create completion requests for autocomplete
89//! let completion = CompletionBuilder::prompt_argument("greeting", "name")
90//! .context_argument("user_id", "123")
91//! .build();
92//!
93//! // Create root directory configurations
94//! let source_root = RootBuilder::source_code_root("/home/user/project")
95//! .name("My Project")
96//! .build()?;
97//!
98//! // Create elicitation forms for user input
99//! let form_request = ElicitationBuilder::new("Please enter your details")
100//! .string_field("name", "Your full name")
101//! .integer_field_with_range("age", "Your age", Some(0.0), Some(120.0))
102//! .boolean_field("subscribe", "Subscribe to newsletter")
103//! .require_fields(vec!["name".to_string(), "age".to_string()])
104//! .build();
105//!
106//! // Create notifications for server events
107//! let progress_notification = NotificationBuilder::progress("task-123", 75)
108//! .total(100)
109//! .message("Processing files...")
110//! .build();
111//!
112//! let resource_updated = NotificationBuilder::resource_updated("file:///data.json")
113//! .meta_value("change_type", json!("modified"))
114//! .build();
115//!
116//! // Create logging messages
117//! let error_log = LoggingBuilder::error(json!({"error": "Connection failed", "retry_count": 3}))
118//! .logger("database")
119//! .meta_value("session_id", json!("sess-456"))
120//! .build();
121//!
122//! let performance_log = LoggingBuilder::structured(
123//! turul_mcp_protocol::logging::LoggingLevel::Info,
124//! [("operation", json!("query_execution")), ("duration_ms", json!(142.5))]
125//! .into_iter().map(|(k, v)| (k.to_string(), v)).collect()
126//! ).logger("perf-monitor").build();
127//! # Ok(())
128//! # }
129//! ```
130
131pub mod prelude;
132pub mod traits;
133pub mod protocol_impls;
134
135pub mod completion;
136pub mod elicitation;
137pub mod logging;
138pub mod message;
139pub mod notification;
140pub mod prompt;
141pub mod resource;
142pub mod root;
143pub mod tool;
144
145// Schemars integration for JSON schema generation
146pub mod schemars_helpers;
147pub use schemars_helpers::{ToolSchemaExt, convert_value_to_json_schema, convert_value_to_json_schema_with_defs};
148
149// Schema provider with automatic JsonSchema detection
150// schema_provider module removed - schemars detection now happens directly in derive macros
151
152// Re-export schemars for use in generated code
153// This ensures schemars::schema_for!() works in user code without requiring
154// users to add schemars as an explicit dependency
155pub use schemars;
156
157// Re-export all framework traits for convenience
158pub use traits::*;
159
160// Re-export all builders for convenience
161/// Builder for completion provider configuration with sampling parameters
162pub use completion::CompletionBuilder;
163/// Builders for interactive data collection and result formatting
164pub use elicitation::{ElicitResultBuilder, ElicitationBuilder};
165/// Builders for structured logging messages and level configuration
166pub use logging::{LoggingBuilder, SetLevelBuilder};
167/// Builder for constructing prompt messages with role and content
168pub use message::MessageBuilder;
169/// Builders for various MCP notification types (progress, cancellation, resource updates)
170pub use notification::{
171 CancelledNotificationBuilder, NotificationBuilder, ProgressNotificationBuilder,
172 ResourceUpdatedNotificationBuilder,
173};
174/// Builder for prompt templates with arguments and message composition
175pub use prompt::PromptBuilder;
176/// Builder for resource definitions with content and metadata
177pub use resource::ResourceBuilder;
178/// Builders for root directory listings and workspace notifications
179pub use root::{ListRootsRequestBuilder, RootBuilder, RootsNotificationBuilder};
180/// Builder for executable tool definitions with parameters and handlers
181pub use tool::ToolBuilder;
182
183// Common types used across builders
184/// JSON value type for dynamic content construction
185pub use serde_json::{Value, json};
186/// Hash map type for parameter collections and metadata
187pub use std::collections::HashMap;