rust-sdk/examples/servers/src/common/generic_service.rs
Michael Assaf 9349f5cb26
feat: Add prompt support (#351)
* feat: add prompt support with typed argument handling

- Implement #[prompt], #[prompt_router], and #[prompt_handler] macros
- Add automatic JSON schema generation from Rust types for arguments
- Support flexible async handler signatures with automatic adaptation
- Create PromptRouter for efficient prompt dispatch
- Include comprehensive tests and example implementation

This enables MCP servers to provide reusable prompt templates that
LLMs can discover and invoke with strongly-typed parameters, similar
to the existing tool system but optimized for prompt use cases.

🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: unify parameter handling between tools and prompts

- Replace Arguments<T> with Parameters<T> for consistent API
- Create shared common module for tool/prompt utilities
- Modernize async handling with futures::future::BoxFuture
- Move cached_schema_for_type to common module for reuse
- Update error types from rmcp::Error to rmcp::ErrorData
- Add comprehensive trait implementations for parameter extraction

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: extract Parameters wrapper to shared module and unify trait usage

- Move Parameters type from common.rs to dedicated wrapper/parameters.rs module
- Unify extractor traits by using FromContextPart for both tools and prompts
- Remove duplicate FromToolCallContextPart and FromPromptContextPart traits
- Add structured output support to Json wrapper with IntoCallToolResult impl
- Improve error messages with more descriptive panic for schema serialization
- Update all imports across codebase to use new module path
- Clean up trailing whitespace and formatting inconsistencies

This consolidates parameter extraction logic and reduces code duplication
between tool and prompt handlers while maintaining backward compatibility.

* chore: remove committed .egg-info directory and update gitignore

* docs: fix documentation formatting
2025-08-21 11:22:19 +08:00

86 lines
2 KiB
Rust

use std::sync::Arc;
use rmcp::{
ServerHandler,
handler::server::{router::tool::ToolRouter, wrapper::Parameters},
model::{ServerCapabilities, ServerInfo},
schemars, tool, tool_handler, tool_router,
};
#[allow(dead_code)]
pub trait DataService: Send + Sync + 'static {
fn get_data(&self) -> String;
fn set_data(&mut self, data: String);
}
#[derive(Debug, Clone)]
pub struct MemoryDataService {
data: String,
}
impl MemoryDataService {
#[allow(dead_code)]
pub fn new(initial_data: impl Into<String>) -> Self {
Self {
data: initial_data.into(),
}
}
}
impl DataService for MemoryDataService {
fn get_data(&self) -> String {
self.data.clone()
}
fn set_data(&mut self, data: String) {
self.data = data;
}
}
#[derive(Debug, Clone)]
pub struct GenericService<DS: DataService> {
#[allow(dead_code)]
data_service: Arc<DS>,
tool_router: ToolRouter<Self>,
}
#[derive(Debug, schemars::JsonSchema, serde::Deserialize, serde::Serialize)]
pub struct SetDataRequest {
pub data: String,
}
#[tool_router]
impl<DS: DataService> GenericService<DS> {
#[allow(dead_code)]
pub fn new(data_service: DS) -> Self {
Self {
data_service: Arc::new(data_service),
tool_router: Self::tool_router(),
}
}
#[tool(description = "get memory from service")]
pub async fn get_data(&self) -> String {
self.data_service.get_data()
}
#[tool(description = "set memory to service")]
pub async fn set_data(
&self,
Parameters(SetDataRequest { data }): Parameters<SetDataRequest>,
) -> String {
let new_data = data.clone();
format!("Current memory: {}", new_data)
}
}
#[tool_handler]
impl<DS: DataService> ServerHandler for GenericService<DS> {
fn get_info(&self) -> ServerInfo {
ServerInfo {
instructions: Some("generic data service".into()),
capabilities: ServerCapabilities::builder().enable_tools().build(),
..Default::default()
}
}
}