Skip to content

Conversation

@snowmead
Copy link
Contributor

@snowmead snowmead commented Aug 4, 2025

Add Prompt Support

This PR introduces a complete prompt system for the MCP Rust SDK, enabling servers to provide reusable prompt templates that LLMs can discover and use. The implementation follows the MCP specification for prompts and provides a developer-friendly API through procedural macros.

Key Features

🎯 Core Functionality

  • Prompt Macros: #[prompt], #[prompt_router], and #[prompt_handler] for easy prompt definition
  • Type-Safe Parameters: Automatic JSON schema generation from Rust types with compile-time validation
  • Unified Architecture: Shared parameter extraction infrastructure between tools and prompts
  • Flexible Handlers: Support for async/sync methods, standalone functions, and closures

🔧 Technical Improvements

  • Extracted Parameters<T> wrapper to dedicated module for better organization
  • Unified trait system using FromContextPart for both tools and prompts (removed duplicate traits)
  • Enhanced Json<T> wrapper with structured output support via IntoCallToolResult
  • Improved error messages with descriptive panics for schema serialization failures
  • Clean architecture with shared extractors reducing code duplication by ~300 lines

Implementation Details

Macro Support

#[prompt(description = "Generate code based on requirements")]
async fn code_generator(params: Parameters<CodeRequest>) -> Vec<PromptMessage> {
    // Type-safe parameter handling with automatic validation
}

Router Integration

#[prompt_router]
impl MyServer {
    #[prompt]
    async fn greeting_prompt(&self, params: Parameters<Args>) -> Vec<PromptMessage> {
        // Automatically registered in router
    }
}

File Structure

  • crates/rmcp-macros/src/prompt*.rs - Macro implementations
  • crates/rmcp/src/handler/server/prompt.rs - Core prompt handling logic
  • crates/rmcp/src/handler/server/wrapper/parameters.rs - Unified parameter extraction
  • examples/servers/src/prompt_stdio.rs - Complete working example

Testing

  • Comprehensive test coverage with 5 new test files
  • Integration tests validating prompt discovery, invocation, and parameter handling
  • Example server demonstrating real-world usage patterns

Breaking Changes

None - The refactoring maintains backward compatibility while unifying the internal architecture.

Migration Guide

For users implementing custom extractors:

  • Replace FromToolCallContextPart with FromContextPart<ToolCallContext>
  • Replace FromPromptContextPart with FromContextPart<PromptContext>
  • Update imports from handler::server::tool::Parameters to handler::server::wrapper::Parameters

Examples

See examples/servers/src/prompt_stdio.rs for a complete implementation including:

  • Weather prompts with typed parameters
  • Code generation templates
  • Data analysis prompts
  • Custom argument validation

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update

Checklist

  • I have read the MCP Documentation
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

@github-actions github-actions bot added T-documentation Documentation improvements T-dependencies Dependencies related changes T-test Testing related changes T-config Configuration file changes T-core Core library changes T-examples Example code changes T-handler Handler implementation changes T-macros Macro changes labels Aug 4, 2025
@4t145 4t145 requested a review from Copilot August 14, 2025 07:08

This comment was marked as outdated.

@4t145
Copy link
Collaborator

4t145 commented Aug 14, 2025

And you can use just fix before commit, this will fix the format and clippy error.

@snowmead snowmead force-pushed the feature/prompt-support branch from c88a7c1 to 45ae1b9 Compare August 19, 2025 14:23
@snowmead snowmead requested a review from 4t145 August 19, 2025 20:43
@4t145 4t145 requested a review from Copilot August 20, 2025 03:49
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR introduces comprehensive prompt support to the Rust SDK, enabling servers to provide reusable prompt templates that LLMs can discover and use. The implementation follows the MCP specification and provides a developer-friendly API through procedural macros.

  • Adds complete prompt system with #[prompt], #[prompt_router], and #[prompt_handler] macros for type-safe parameter handling
  • Refactors parameter extraction infrastructure to be shared between tools and prompts, reducing code duplication
  • Enhances JSON wrapper with structured output support and improved error handling

Reviewed Changes

Copilot reviewed 43 out of 43 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
examples/servers/src/prompt_stdio.rs New comprehensive example server demonstrating prompt functionality
crates/rmcp-macros/src/prompt*.rs New macro implementations for prompt support
crates/rmcp/src/handler/server/prompt.rs Core prompt handling logic and trait implementations
crates/rmcp/src/handler/server/wrapper/parameters.rs Unified parameter extraction infrastructure
examples/*/calculator.rs Updated imports to use new unified parameter location
crates/rmcp/tests/test_prompt_*.rs Comprehensive test coverage for prompt functionality
Comments suppressed due to low confidence (2)

crates/rmcp/src/service.rs:165

  • The lifetime parameter should be explicit to avoid potential lifetime issues. Using BoxFuture<'_, ...> instead of BoxFuture<...> could lead to compilation issues in certain contexts.
    ) -> BoxFuture<'_, Result<R::Resp, McpError>>;

crates/rmcp/src/service.rs:170

  • The lifetime parameter should be explicit to avoid potential lifetime issues. Using BoxFuture<'_, ...> instead of BoxFuture<...> could lead to compilation issues in certain contexts.
    ) -> BoxFuture<'_, Result<(), McpError>>;

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

@4t145
Copy link
Collaborator

4t145 commented Aug 20, 2025

And please fix the document ci

@snowmead snowmead changed the title feat: Add prompt support with typed argument handling feat: Add prompt support Aug 20, 2025
- 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 <[email protected]>
- 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 <[email protected]>
… 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.
@snowmead snowmead force-pushed the feature/prompt-support branch from 86e812b to ad7b2d9 Compare August 20, 2025 15:11
@snowmead
Copy link
Contributor Author

Note: Had to force push to change the commit messages to pass commitlint

Copy link
Collaborator

@4t145 4t145 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@4t145 4t145 merged commit 9349f5c into modelcontextprotocol:main Aug 21, 2025
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

T-config Configuration file changes T-core Core library changes T-dependencies Dependencies related changes T-documentation Documentation improvements T-examples Example code changes T-handler Handler implementation changes T-macros Macro changes T-test Testing related changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants