example: add simpling example and test (#289)
Signed-off-by: jokemanfire <hu.dingyang@zte.com.cn>
This commit is contained in:
parent
b9d7d61ebd
commit
1b3db8959c
6 changed files with 638 additions and 26 deletions
|
|
@ -51,4 +51,8 @@ path = "src/collection.rs"
|
|||
|
||||
[[example]]
|
||||
name = "clients_oauth_client"
|
||||
path = "src/auth/oauth_client.rs"
|
||||
path = "src/auth/oauth_client.rs"
|
||||
|
||||
[[example]]
|
||||
name = "clients_sampling_stdio"
|
||||
path = "src/sampling_stdio.rs"
|
||||
|
|
@ -57,6 +57,16 @@ A client demonstrating how to authenticate with an MCP server using OAuth.
|
|||
- Establishes an authorized connection to the MCP server using the acquired access token
|
||||
- Demonstrates how to use the authorized connection to retrieve available tools and prompts
|
||||
|
||||
|
||||
### Sampling Standard I/O Client (`sampling_stdio.rs`)
|
||||
|
||||
A client demonstrating how to use the sampling tool.
|
||||
|
||||
- Launches the server example `servers_sampling_stdio`
|
||||
- Connects to the server
|
||||
- Retrieves server information and list of available tools
|
||||
- Calls the `ask_llm` tool
|
||||
|
||||
## How to Run
|
||||
|
||||
Each example can be run using Cargo:
|
||||
|
|
@ -79,6 +89,9 @@ cargo run --example clients_collection
|
|||
|
||||
# Run the OAuth client example
|
||||
cargo run --example clients_oauth_client
|
||||
|
||||
# Run the sampling standard I/O client example
|
||||
cargo run --example clients_sampling_stdio
|
||||
```
|
||||
|
||||
## Dependencies
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ async fn main() -> Result<()> {
|
|||
|
||||
let mut clients_map = HashMap::new();
|
||||
for idx in 0..10 {
|
||||
let service = ()
|
||||
let client = ()
|
||||
.into_dyn()
|
||||
.serve(TokioChildProcess::new(Command::new("uvx").configure(
|
||||
|cmd| {
|
||||
|
|
@ -34,18 +34,18 @@ async fn main() -> Result<()> {
|
|||
},
|
||||
))?)
|
||||
.await?;
|
||||
clients_map.insert(idx, service);
|
||||
clients_map.insert(idx, client);
|
||||
}
|
||||
|
||||
for (_, service) in clients_map.iter() {
|
||||
for (_, client) in clients_map.iter() {
|
||||
// Initialize
|
||||
let _server_info = service.peer_info();
|
||||
let _server_info = client.peer_info();
|
||||
|
||||
// List tools
|
||||
let _tools = service.list_tools(Default::default()).await?;
|
||||
let _tools = client.list_tools(Default::default()).await?;
|
||||
|
||||
// Call tool 'git_status' with arguments = {"repo_path": "."}
|
||||
let _tool_result = service
|
||||
let _tool_result = client
|
||||
.call_tool(CallToolRequestParam {
|
||||
name: "git_status".into(),
|
||||
arguments: serde_json::json!({ "repo_path": "." }).as_object().cloned(),
|
||||
|
|
|
|||
|
|
@ -19,8 +19,7 @@ async fn main() -> Result<()> {
|
|||
.with(tracing_subscriber::fmt::layer())
|
||||
.init();
|
||||
|
||||
// Start server
|
||||
let service = ()
|
||||
let client = ()
|
||||
.serve(TokioChildProcess::new(Command::new("npx").configure(
|
||||
|cmd| {
|
||||
cmd.arg("-y").arg("@modelcontextprotocol/server-everything");
|
||||
|
|
@ -29,15 +28,15 @@ async fn main() -> Result<()> {
|
|||
.await?;
|
||||
|
||||
// Initialize
|
||||
let server_info = service.peer_info();
|
||||
let server_info = client.peer_info();
|
||||
tracing::info!("Connected to server: {server_info:#?}");
|
||||
|
||||
// List tools
|
||||
let tools = service.list_all_tools().await?;
|
||||
let tools = client.list_all_tools().await?;
|
||||
tracing::info!("Available tools: {tools:#?}");
|
||||
|
||||
// Call tool echo
|
||||
let tool_result = service
|
||||
let tool_result = client
|
||||
.call_tool(CallToolRequestParam {
|
||||
name: "echo".into(),
|
||||
arguments: Some(object!({ "message": "hi from rmcp" })),
|
||||
|
|
@ -46,7 +45,7 @@ async fn main() -> Result<()> {
|
|||
tracing::info!("Tool result for echo: {tool_result:#?}");
|
||||
|
||||
// Call tool longRunningOperation
|
||||
let tool_result = service
|
||||
let tool_result = client
|
||||
.call_tool(CallToolRequestParam {
|
||||
name: "longRunningOperation".into(),
|
||||
arguments: Some(object!({ "duration": 3, "steps": 1 })),
|
||||
|
|
@ -55,11 +54,11 @@ async fn main() -> Result<()> {
|
|||
tracing::info!("Tool result for longRunningOperation: {tool_result:#?}");
|
||||
|
||||
// List resources
|
||||
let resources = service.list_all_resources().await?;
|
||||
let resources = client.list_all_resources().await?;
|
||||
tracing::info!("Available resources: {resources:#?}");
|
||||
|
||||
// Read resource
|
||||
let resource = service
|
||||
let resource = client
|
||||
.read_resource(ReadResourceRequestParam {
|
||||
uri: "test://static/resource/3".into(),
|
||||
})
|
||||
|
|
@ -67,11 +66,11 @@ async fn main() -> Result<()> {
|
|||
tracing::info!("Resource: {resource:#?}");
|
||||
|
||||
// List prompts
|
||||
let prompts = service.list_all_prompts().await?;
|
||||
let prompts = client.list_all_prompts().await?;
|
||||
tracing::info!("Available prompts: {prompts:#?}");
|
||||
|
||||
// Get simple prompt
|
||||
let prompt = service
|
||||
let prompt = client
|
||||
.get_prompt(GetPromptRequestParam {
|
||||
name: "simple_prompt".into(),
|
||||
arguments: None,
|
||||
|
|
@ -80,7 +79,7 @@ async fn main() -> Result<()> {
|
|||
tracing::info!("Prompt - simple: {prompt:#?}");
|
||||
|
||||
// Get complex prompt (returns text & image)
|
||||
let prompt = service
|
||||
let prompt = client
|
||||
.get_prompt(GetPromptRequestParam {
|
||||
name: "complex_prompt".into(),
|
||||
arguments: Some(object!({ "temperature": "0.5", "style": "formal" })),
|
||||
|
|
@ -89,10 +88,10 @@ async fn main() -> Result<()> {
|
|||
tracing::info!("Prompt - complex: {prompt:#?}");
|
||||
|
||||
// List resource templates
|
||||
let resource_templates = service.list_all_resource_templates().await?;
|
||||
let resource_templates = client.list_all_resource_templates().await?;
|
||||
tracing::info!("Available resource templates: {resource_templates:#?}");
|
||||
|
||||
service.cancel().await?;
|
||||
client.cancel().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ async fn main() -> Result<()> {
|
|||
)
|
||||
.with(tracing_subscriber::fmt::layer())
|
||||
.init();
|
||||
let service = ()
|
||||
let client = ()
|
||||
.serve(TokioChildProcess::new(Command::new("uvx").configure(
|
||||
|cmd| {
|
||||
cmd.arg("mcp-server-git");
|
||||
|
|
@ -28,21 +28,21 @@ async fn main() -> Result<()> {
|
|||
// or serve_client((), TokioChildProcess::new(cmd)?).await?;
|
||||
|
||||
// Initialize
|
||||
let server_info = service.peer_info();
|
||||
let server_info = client.peer_info();
|
||||
tracing::info!("Connected to server: {server_info:#?}");
|
||||
|
||||
// List tools
|
||||
let tools = service.list_tools(Default::default()).await?;
|
||||
let tools = client.list_tools(Default::default()).await?;
|
||||
tracing::info!("Available tools: {tools:#?}");
|
||||
|
||||
// Call tool 'git_status' with arguments = {"repo_path": "."}
|
||||
let tool_result = service
|
||||
let tool_result = client
|
||||
.call_tool(CallToolRequestParam {
|
||||
name: "git_status".into(),
|
||||
arguments: serde_json::json!({ "repo_path": "." }).as_object().cloned(),
|
||||
})
|
||||
.await?;
|
||||
tracing::info!("Tool result: {tool_result:#?}");
|
||||
service.cancel().await?;
|
||||
client.cancel().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
124
examples/clients/src/sampling_stdio.rs
Normal file
124
examples/clients/src/sampling_stdio.rs
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
use anyhow::Result;
|
||||
use rmcp::{
|
||||
ClientHandler, ServiceExt,
|
||||
model::*,
|
||||
object,
|
||||
service::{RequestContext, RoleClient},
|
||||
transport::{ConfigureCommandExt, TokioChildProcess},
|
||||
};
|
||||
use tokio::process::Command;
|
||||
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
||||
/// Simple Sampling Demo Client
|
||||
///
|
||||
/// This client demonstrates how to handle sampling requests from servers.
|
||||
/// It includes a mock LLM that generates simple responses.
|
||||
/// Run with: cargo run --example clients_sampling_stdio
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct SamplingDemoClient;
|
||||
|
||||
impl SamplingDemoClient {
|
||||
/// Mock LLM function that generates responses based on the input
|
||||
/// In actual implementation, this would be replaced with a call to an LLM service
|
||||
fn mock_llm_response(
|
||||
&self,
|
||||
_messages: &[SamplingMessage],
|
||||
_system_prompt: Option<&str>,
|
||||
) -> String {
|
||||
"It just a mock response".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl ClientHandler for SamplingDemoClient {
|
||||
async fn create_message(
|
||||
&self,
|
||||
params: CreateMessageRequestParam,
|
||||
_context: RequestContext<RoleClient>,
|
||||
) -> Result<CreateMessageResult, ErrorData> {
|
||||
tracing::info!("Received sampling request with {:?}", params);
|
||||
|
||||
// Generate mock response using our simple LLM
|
||||
let response_text =
|
||||
self.mock_llm_response(¶ms.messages, params.system_prompt.as_deref());
|
||||
|
||||
Ok(CreateMessageResult {
|
||||
message: SamplingMessage {
|
||||
role: Role::Assistant,
|
||||
content: Content::text(response_text),
|
||||
},
|
||||
model: "mock_llm".to_string(),
|
||||
stop_reason: Some(CreateMessageResult::STOP_REASON_END_TURN.to_string()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
// Initialize logging
|
||||
tracing_subscriber::registry()
|
||||
.with(
|
||||
tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| format!("info,{}=debug", env!("CARGO_CRATE_NAME")).into()),
|
||||
)
|
||||
.with(tracing_subscriber::fmt::layer())
|
||||
.init();
|
||||
|
||||
tracing::info!("Starting Sampling Demo Client");
|
||||
|
||||
let client = SamplingDemoClient;
|
||||
|
||||
// Start the sampling server as a child process
|
||||
let servers_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.parent()
|
||||
.expect("CARGO_MANIFEST_DIR is not set")
|
||||
.join("servers");
|
||||
|
||||
let client = client
|
||||
.serve(TokioChildProcess::new(Command::new("cargo").configure(
|
||||
|cmd| {
|
||||
cmd.arg("run")
|
||||
.arg("--example")
|
||||
.arg("servers_sampling_stdio")
|
||||
.current_dir(servers_dir);
|
||||
},
|
||||
))?)
|
||||
.await
|
||||
.inspect_err(|e| {
|
||||
tracing::error!("client error: {:?}", e);
|
||||
})?;
|
||||
|
||||
// Wait for initialization
|
||||
tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await;
|
||||
|
||||
// Get server info
|
||||
let server_info = client.peer_info();
|
||||
tracing::info!("Connected to server: {server_info:#?}");
|
||||
|
||||
// List available tools
|
||||
match client.list_all_tools().await {
|
||||
Ok(tools) => {
|
||||
tracing::info!("Available tools: {tools:#?}");
|
||||
|
||||
// Test the ask_llm tool
|
||||
tracing::info!("Testing ask_llm tool...");
|
||||
match client
|
||||
.call_tool(CallToolRequestParam {
|
||||
name: "ask_llm".into(),
|
||||
arguments: Some(object!({
|
||||
"question": "Hello world"
|
||||
})),
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(result) => tracing::info!("Ask LLM result: {result:#?}"),
|
||||
Err(e) => tracing::error!("Ask LLM error: {e}"),
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::error!("Failed to list tools: {e}"),
|
||||
}
|
||||
|
||||
tracing::info!("Sampling demo completed successfully!");
|
||||
|
||||
tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await;
|
||||
client.cancel().await?;
|
||||
Ok(())
|
||||
}
|
||||
Loading…
Reference in a new issue