refactor: Transport trait and worker transport, and streamable http client with those new features. (#167)

* refactor: a transport trait and streamable http client

* test: test with js streamable http server

* refactor: separate sse stream connection

* fix(test): streamable http client test with js

* fix(test): wait longer time for js server startup
This commit is contained in:
4t145 2025-05-17 23:53:38 +08:00 • committed by GitHub
commit 9a771fb157
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 2761 additions and 1315 deletions

View file

@ -1,4 +1,4 @@
use std::{net::SocketAddr, sync::Arc, time::Duration};
use std::{net::SocketAddr, sync::Arc};
use anyhow::{Context, Result};
use axum::{
@ -10,7 +10,11 @@ use axum::{
use rmcp::{
ServiceExt,
model::ClientInfo,
transport::{auth::OAuthState, create_authorized_transport, sse::SseTransportRetryConfig},
transport::{
SseClientTransport,
auth::{AuthClient, OAuthState},
sse_client::SseClientConfig,
},
};
use serde::Deserialize;
use tokio::{
@ -92,11 +96,6 @@ async fn main() -> Result<()> {
let server_url = MCP_SERVER_URL.to_string();
tracing::info!("Using MCP server URL: {}", server_url);
// Configure retry settings
let retry_config = SseTransportRetryConfig {
max_times: Some(3),
min_duration: Duration::from_secs(1),
};
// Initialize oauth state machine
let mut oauth_state = OAuthState::new(&server_url, None)
.await
@ -141,16 +140,18 @@ async fn main() -> Result<()> {
// Create authorized transport, this transport is authorized by the oauth state machine
tracing::info!("Establishing authorized connection to MCP server...");
let transport =
match create_authorized_transport(MCP_SSE_URL.to_string(), oauth_state, Some(retry_config))
.await
{
Ok(t) => t,
Err(e) => {
tracing::error!("Failed to create authorized transport: {}", e);
return Err(anyhow::anyhow!("Connection failed: {}", e));
}
};
let am = oauth_state
.into_authorization_manager()
.ok_or_else(|| anyhow::anyhow!("Failed to get authorization manager"))?;
let client = AuthClient::new(reqwest::Client::default(), am);
let transport = SseClientTransport::start_with_client(
client,
SseClientConfig {
uri: MCP_SSE_URL.into(),
..Default::default()
},
)
.await?;
// Create client and connect to MCP server
let client_service = ClientInfo::default();

View file

@ -2,7 +2,7 @@ use anyhow::Result;
use rmcp::{
ServiceExt,
model::{CallToolRequestParam, ClientCapabilities, ClientInfo, Implementation},
transport::SseTransport,
transport::SseClientTransport,
};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
@ -16,7 +16,7 @@ async fn main() -> Result<()> {
)
.with(tracing_subscriber::fmt::layer())
.init();
let transport = SseTransport::start("http://localhost:8000/sse").await?;
let transport = SseClientTransport::start("http://localhost:8000/sse").await?;
let client_info = ClientInfo {
protocol_version: Default::default(),
capabilities: ClientCapabilities::default(),

View file

@ -0,0 +1,49 @@
use anyhow::Result;
use rmcp::{
ServiceExt,
model::{CallToolRequestParam, ClientCapabilities, ClientInfo, Implementation},
transport::StreamableHttpClientTransport,
};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[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();
let transport = StreamableHttpClientTransport::from_uri("http://localhost:8000");
let client_info = ClientInfo {
protocol_version: Default::default(),
capabilities: ClientCapabilities::default(),
client_info: Implementation {
name: "test sse client".to_string(),
version: "0.0.1".to_string(),
},
};
let client = client_info.serve(transport).await.inspect_err(|e| {
tracing::error!("client error: {:?}", e);
})?;
// Initialize
let server_info = client.peer_info();
tracing::info!("Connected to server: {server_info:#?}");
// List tools
let tools = client.list_tools(Default::default()).await?;
tracing::info!("Available tools: {tools:#?}");
let tool_result = client
.call_tool(CallToolRequestParam {
name: "increment".into(),
arguments: serde_json::json!({}).as_object().cloned(),
})
.await?;
tracing::info!("Tool result: {tool_result:#?}");
client.cancel().await?;
Ok(())
}