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
This commit is contained in:
Michael Assaf 2025-08-20 23:22:19 -04:00 • committed by GitHub
commit 9349f5cb26
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -0,0 +1,181 @@
use darling::{FromMeta, ast::NestedMeta};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::{Expr, Ident, ImplItemFn, ReturnType};
use crate::common::{extract_doc_line, none_expr};
#[derive(FromMeta, Default, Debug)]
#[darling(default)]
pub struct PromptAttribute {
/// The name of the prompt
pub name: Option<String>,
/// Optional description of what the prompt does
pub description: Option<String>,
/// Arguments that can be passed to the prompt
pub arguments: Option<Expr>,
}
pub struct ResolvedPromptAttribute {
pub name: String,
pub description: Option<String>,
pub arguments: Expr,
}
impl ResolvedPromptAttribute {
pub fn into_fn(self, fn_ident: Ident) -> syn::Result<ImplItemFn> {
let Self {
name,
description,
arguments,
} = self;
let description = if let Some(description) = description {
quote! { Some(#description.into()) }
} else {
quote! { None }
};
let tokens = quote! {
pub fn #fn_ident() -> rmcp::model::Prompt {
rmcp::model::Prompt {
name: #name.into(),
description: #description,
arguments: #arguments,
}
}
};
syn::parse2::<ImplItemFn>(tokens)
}
}
pub fn prompt(attr: TokenStream, input: TokenStream) -> syn::Result<TokenStream> {
let attribute = if attr.is_empty() {
Default::default()
} else {
let attr_args = NestedMeta::parse_meta_list(attr)?;
PromptAttribute::from_list(&attr_args)?
};
let mut fn_item = syn::parse2::<ImplItemFn>(input.clone())?;
let fn_ident = &fn_item.sig.ident;
let prompt_attr_fn_ident = format_ident!("{}_prompt_attr", fn_ident);
// Try to find prompt parameters from function parameters
let arguments_expr = if let Some(arguments) = attribute.arguments {
arguments
} else {
// Look for a type named Parameters in the function signature
let params_ty = crate::common::find_parameters_type_impl(&fn_item);
if let Some(params_ty) = params_ty {
// Generate arguments from the type's schema with caching
syn::parse2::<Expr>(quote! {
rmcp::handler::server::prompt::cached_arguments_from_schema::<#params_ty>()
})?
} else {
// No arguments
none_expr()?
}
};
let name = attribute.name.unwrap_or_else(|| fn_ident.to_string());
let description = attribute
.description
.or_else(|| fn_item.attrs.iter().fold(None, extract_doc_line));
let arguments = arguments_expr;
let resolved_prompt_attr = ResolvedPromptAttribute {
name: name.clone(),
description: description.clone(),
arguments: arguments.clone(),
};
let prompt_attr_fn = resolved_prompt_attr.into_fn(prompt_attr_fn_ident.clone())?;
// Modify the input function for async support (same as tool macro)
if fn_item.sig.asyncness.is_some() {
// 1. remove asyncness from sig
// 2. make return type: `futures::future::BoxFuture<'_, #ReturnType>`
// 3. make body: { Box::pin(async move { #body }) }
let new_output = syn::parse2::<ReturnType>({
let mut lt = quote! { 'static };
if let Some(receiver) = fn_item.sig.receiver() {
if let Some((_, receiver_lt)) = receiver.reference.as_ref() {
if let Some(receiver_lt) = receiver_lt {
lt = quote! { #receiver_lt };
} else {
lt = quote! { '_ };
}
}
}
match &fn_item.sig.output {
syn::ReturnType::Default => {
quote! { -> futures::future::BoxFuture<#lt, ()> }
}
syn::ReturnType::Type(_, ty) => {
quote! { -> futures::future::BoxFuture<#lt, #ty> }
}
}
})?;
let prev_block = &fn_item.block;
let new_block = syn::parse2::<syn::Block>(quote! {
{ Box::pin(async move #prev_block ) }
})?;
fn_item.sig.asyncness = None;
fn_item.sig.output = new_output;
fn_item.block = new_block;
}
Ok(quote! {
#prompt_attr_fn
#fn_item
})
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_prompt_macro() -> syn::Result<()> {
let attr = quote! {
name = "example-prompt",
description = "An example prompt"
};
let input = quote! {
async fn example_prompt(&self, Parameters(args): Parameters<ExampleArgs>) -> Result<String> {
Ok("Example prompt response".to_string())
}
};
let result = prompt(attr, input)?;
// Verify the output contains both the attribute function and the modified function
let result_str = result.to_string();
assert!(result_str.contains("example_prompt_prompt_attr"));
assert!(
result_str.contains("rmcp")
&& result_str.contains("model")
&& result_str.contains("Prompt")
);
Ok(())
}
#[test]
fn test_doc_comment_description() -> syn::Result<()> {
let attr = quote! {}; // No explicit description
let input = quote! {
/// This is a test prompt description
/// with multiple lines
fn test_prompt(&self) -> Result<String> {
Ok("Test".to_string())
}
};
let result = prompt(attr, input)?;
// The output should contain the description from doc comments
let result_str = result.to_string();
assert!(result_str.contains("This is a test prompt description"));
assert!(result_str.contains("with multiple lines"));
Ok(())
}
}