Struct MicrokernelServer

Source
pub struct MicrokernelServer<P: OAuthProviderTrait<S, DefaultClientManager<S>> + 'static, S: OAuthStorage + Clone + 'static, M: McpServerHandler = McpServer> { /* private fields */ }
Expand description

Microkernel server builder that composes independent handlers

This builder demonstrates the microkernel principle where services are composed from independent, single-responsibility components. Now supports any OAuth provider, storage backend, MCP server, and custom routers through trait abstraction.

Implementations§

Source§

impl<P: OAuthProviderTrait<S, DefaultClientManager<S>> + 'static, S: OAuthStorage + Clone + 'static, M: McpServerHandler> MicrokernelServer<P, S, M>

Source

pub fn new() -> Self

Create a new microkernel server builder

Examples found in repository?
examples/simple_custom_router_test.rs (line 51)
30async fn main() -> Result<(), Box<dyn std::error::Error>> {
31    println!("🧪 Testing custom router functionality...");
32
33    // Create OAuth provider
34    let github_config = OAuthProviderConfig::with_oauth_config(
35        "test_client_id".to_string(),
36        "test_client_secret".to_string(),
37        "http://localhost:8080/oauth/callback".to_string(),
38        "read:user".to_string(),
39        "github".to_string(),
40    );
41
42    let github_oauth_provider = GitHubOAuthProvider::new_github(github_config);
43    let oauth_provider = OAuthProvider::new(github_oauth_provider, oauth_provider_rs::http_integration::config::OAuthProviderConfig::default());
44
45    // Create custom routers
46    let health_router = Router::new().route("/health", get(health_check));
47
48    let api_router = Router::new().route("/status", get(api_status));
49
50    // Build microkernel server with custom routers
51    let microkernel: GitHubMicrokernelServer = MicrokernelServer::new()
52        .with_oauth_provider(oauth_provider)
53        .with_custom_router(health_router)
54        .with_custom_router_config(api_router, CustomRouterConfig::with_prefix("/api"));
55
56    // Test that the router can be built
57    let router = microkernel.build_router()?;
58    println!("✅ Router built successfully!");
59
60    // Print available endpoints
61    println!("\n📋 Server would have these endpoints:");
62    println!("  OAuth:");
63    println!("    GET  /oauth/login");
64    println!("    GET  /oauth/callback");
65    println!("    POST /oauth/token");
66    println!("  Custom:");
67    println!("    GET  /health");
68    println!("    GET  /api/status");
69
70    println!("\n🎉 Custom router functionality is working correctly!");
71    println!("   The server can be built and all routers are properly attached.");
72
73    Ok(())
74}
More examples
Hide additional examples
examples/custom_mcp_server_example.rs (line 469)
416async fn main() -> AppResult<()> {
417    // Load environment variables
418    dotenv::dotenv().ok();
419
420    // Initialize tracing
421    init_tracing()?;
422
423    tracing::info!("Starting Custom MCP Server example with Cognito and DynamoDB storage...");
424
425    // Create Cognito OAuth configuration
426    let cognito_config = get_cognito_oauth_provider_config()?;
427
428    // Get DynamoDB configuration
429    let table_name =
430        env::var("DYNAMODB_TABLE_NAME").unwrap_or_else(|_| "oauth-storage".to_string());
431    let create_table = env::var("DYNAMODB_CREATE_TABLE")
432        .unwrap_or_else(|_| "true".to_string())
433        .parse::<bool>()
434        .unwrap_or(true);
435
436    // Log configuration
437    log_startup_info(&table_name, create_table);
438
439    // Create DynamoDB storage
440    let (storage, client_manager) = create_dynamodb_storage(
441        table_name.clone(),
442        create_table,
443        Some("expires_at".to_string()),
444    )
445    .await
446    .map_err(|e| {
447        remote_mcp_kernel::error::AppError::Internal(format!(
448            "Failed to create DynamoDB storage: {}",
449            e
450        ))
451    })?;
452
453    // Create Cognito OAuth provider with DynamoDB storage
454    let oauth_handler = oauth_provider_rs::CognitoOAuthHandler::new_simple(
455        storage,
456        client_manager,
457        cognito_config,
458        get_cognito_domain()?,
459        get_cognito_region()?,
460        get_cognito_user_pool_id()?,
461    );
462
463    let oauth_provider = OAuthProvider::new(oauth_handler, oauth_provider_rs::http_integration::config::OAuthProviderConfig::default());
464
465    // Create custom MCP server
466    let custom_mcp_server = CustomMcpServer::new("Custom File & System MCP Server".to_string());
467
468    // Build microkernel with custom MCP server using convenience methods
469    let microkernel = MicrokernelServer::new()
470        .with_oauth_provider(oauth_provider)
471        .with_mcp_streamable_handler(custom_mcp_server.clone())
472        .with_mcp_sse_handler(custom_mcp_server, SseHandlerConfig::default());
473
474    // Start the microkernel server
475    let bind_address = get_bind_socket_addr()?;
476    tracing::info!("🚀 Starting microkernel server on {}", bind_address);
477    microkernel.serve(bind_address).await?;
478
479    Ok(())
480}
examples/custom_router_example.rs (line 167)
109async fn main() -> Result<(), Box<dyn std::error::Error>> {
110    // Initialize tracing for logging
111    tracing_subscriber::fmt::init();
112
113    // Create GitHub OAuth provider
114    let github_config = OAuthProviderConfig::with_oauth_config(
115        std::env::var("GITHUB_CLIENT_ID")
116            .unwrap_or_else(|_| "demo_client_id".to_string()),
117        std::env::var("GITHUB_CLIENT_SECRET")
118            .unwrap_or_else(|_| "demo_client_secret".to_string()),
119        "http://localhost:8080/oauth/callback".to_string(),
120        "read:user".to_string(),
121        "github".to_string(),
122    );
123
124    let github_oauth_provider = GitHubOAuthProvider::new_github(github_config);
125    let oauth_provider = OAuthProvider::new(github_oauth_provider, oauth_provider_rs::http_integration::config::OAuthProviderConfig::default());
126
127    // Create custom routers
128
129    // 1. Health and basic endpoints router
130    let health_router = Router::new()
131        .route("/health", get(health_check))
132        .route("/webhooks", post(webhook_handler));
133
134    // 2. Monitoring router with path prefix
135    let monitoring_router = Router::new().route("/metrics", get(metrics));
136
137    // 3. API router with versioned endpoints
138    let api_router = Router::new()
139        .route("/v1/status", get(api_status))
140        .route("/{version}/status", get(api_status));
141
142    // 4. Admin router with HTML interface
143    let admin_router = Router::new().route("/", get(admin_dashboard));
144
145    // Configure custom routers with different configurations
146    let custom_routers = vec![
147        // Health router without prefix (attached to root)
148        (health_router, CustomRouterConfig::default()),
149        // Monitoring router with prefix and name
150        (
151            monitoring_router,
152            CustomRouterConfig::with_name_and_prefix("Monitoring", "/monitoring"),
153        ),
154        // API router with prefix
155        (
156            api_router,
157            CustomRouterConfig::with_name_and_prefix("API", "/api"),
158        ),
159        // Admin router with prefix
160        (
161            admin_router,
162            CustomRouterConfig::with_name_and_prefix("Admin Dashboard", "/admin"),
163        ),
164    ];
165
166    // Build the microkernel server with OAuth provider and custom routers
167    let microkernel: GitHubMicrokernelServer = MicrokernelServer::new()
168        .with_oauth_provider(oauth_provider)
169        .with_custom_routers(custom_routers);
170
171    // Define the bind address
172    let bind_address: SocketAddr = "127.0.0.1:8080".parse()?;
173
174    // Print available endpoints
175    println!("🚀 Starting microkernel server with custom routers...");
176    println!("📍 Server listening on: http://{}", bind_address);
177    println!("\n📋 Available endpoints:");
178    println!("  OAuth:");
179    println!("    GET  /oauth/login");
180    println!("    GET  /oauth/callback");
181    println!("    POST /oauth/token");
182    println!("  Custom Endpoints:");
183    println!("    GET  /health                  - Health check");
184    println!("    POST /webhooks                - Webhook handler");
185    println!("    GET  /monitoring/metrics      - System metrics");
186    println!("    GET  /api/v1/status           - API status");
187    println!("    GET  /api/{{version}}/status   - Versioned API status");
188    println!("    GET  /admin                   - Admin dashboard");
189    println!("\n🔧 Try these commands:");
190    println!("  curl http://localhost:8080/health");
191    println!("  curl http://localhost:8080/monitoring/metrics");
192    println!("  curl http://localhost:8080/api/v1/status");
193    println!("  open http://localhost:8080/admin");
194
195    // Start the server
196    microkernel.serve(bind_address).await?;
197
198    Ok(())
199}
Source

pub fn with_oauth_provider(self, oauth_provider: OAuthProvider<P, S>) -> Self

Add OAuth provider handler

Examples found in repository?
examples/simple_custom_router_test.rs (line 52)
30async fn main() -> Result<(), Box<dyn std::error::Error>> {
31    println!("🧪 Testing custom router functionality...");
32
33    // Create OAuth provider
34    let github_config = OAuthProviderConfig::with_oauth_config(
35        "test_client_id".to_string(),
36        "test_client_secret".to_string(),
37        "http://localhost:8080/oauth/callback".to_string(),
38        "read:user".to_string(),
39        "github".to_string(),
40    );
41
42    let github_oauth_provider = GitHubOAuthProvider::new_github(github_config);
43    let oauth_provider = OAuthProvider::new(github_oauth_provider, oauth_provider_rs::http_integration::config::OAuthProviderConfig::default());
44
45    // Create custom routers
46    let health_router = Router::new().route("/health", get(health_check));
47
48    let api_router = Router::new().route("/status", get(api_status));
49
50    // Build microkernel server with custom routers
51    let microkernel: GitHubMicrokernelServer = MicrokernelServer::new()
52        .with_oauth_provider(oauth_provider)
53        .with_custom_router(health_router)
54        .with_custom_router_config(api_router, CustomRouterConfig::with_prefix("/api"));
55
56    // Test that the router can be built
57    let router = microkernel.build_router()?;
58    println!("✅ Router built successfully!");
59
60    // Print available endpoints
61    println!("\n📋 Server would have these endpoints:");
62    println!("  OAuth:");
63    println!("    GET  /oauth/login");
64    println!("    GET  /oauth/callback");
65    println!("    POST /oauth/token");
66    println!("  Custom:");
67    println!("    GET  /health");
68    println!("    GET  /api/status");
69
70    println!("\n🎉 Custom router functionality is working correctly!");
71    println!("   The server can be built and all routers are properly attached.");
72
73    Ok(())
74}
More examples
Hide additional examples
examples/custom_mcp_server_example.rs (line 470)
416async fn main() -> AppResult<()> {
417    // Load environment variables
418    dotenv::dotenv().ok();
419
420    // Initialize tracing
421    init_tracing()?;
422
423    tracing::info!("Starting Custom MCP Server example with Cognito and DynamoDB storage...");
424
425    // Create Cognito OAuth configuration
426    let cognito_config = get_cognito_oauth_provider_config()?;
427
428    // Get DynamoDB configuration
429    let table_name =
430        env::var("DYNAMODB_TABLE_NAME").unwrap_or_else(|_| "oauth-storage".to_string());
431    let create_table = env::var("DYNAMODB_CREATE_TABLE")
432        .unwrap_or_else(|_| "true".to_string())
433        .parse::<bool>()
434        .unwrap_or(true);
435
436    // Log configuration
437    log_startup_info(&table_name, create_table);
438
439    // Create DynamoDB storage
440    let (storage, client_manager) = create_dynamodb_storage(
441        table_name.clone(),
442        create_table,
443        Some("expires_at".to_string()),
444    )
445    .await
446    .map_err(|e| {
447        remote_mcp_kernel::error::AppError::Internal(format!(
448            "Failed to create DynamoDB storage: {}",
449            e
450        ))
451    })?;
452
453    // Create Cognito OAuth provider with DynamoDB storage
454    let oauth_handler = oauth_provider_rs::CognitoOAuthHandler::new_simple(
455        storage,
456        client_manager,
457        cognito_config,
458        get_cognito_domain()?,
459        get_cognito_region()?,
460        get_cognito_user_pool_id()?,
461    );
462
463    let oauth_provider = OAuthProvider::new(oauth_handler, oauth_provider_rs::http_integration::config::OAuthProviderConfig::default());
464
465    // Create custom MCP server
466    let custom_mcp_server = CustomMcpServer::new("Custom File & System MCP Server".to_string());
467
468    // Build microkernel with custom MCP server using convenience methods
469    let microkernel = MicrokernelServer::new()
470        .with_oauth_provider(oauth_provider)
471        .with_mcp_streamable_handler(custom_mcp_server.clone())
472        .with_mcp_sse_handler(custom_mcp_server, SseHandlerConfig::default());
473
474    // Start the microkernel server
475    let bind_address = get_bind_socket_addr()?;
476    tracing::info!("🚀 Starting microkernel server on {}", bind_address);
477    microkernel.serve(bind_address).await?;
478
479    Ok(())
480}
examples/custom_router_example.rs (line 168)
109async fn main() -> Result<(), Box<dyn std::error::Error>> {
110    // Initialize tracing for logging
111    tracing_subscriber::fmt::init();
112
113    // Create GitHub OAuth provider
114    let github_config = OAuthProviderConfig::with_oauth_config(
115        std::env::var("GITHUB_CLIENT_ID")
116            .unwrap_or_else(|_| "demo_client_id".to_string()),
117        std::env::var("GITHUB_CLIENT_SECRET")
118            .unwrap_or_else(|_| "demo_client_secret".to_string()),
119        "http://localhost:8080/oauth/callback".to_string(),
120        "read:user".to_string(),
121        "github".to_string(),
122    );
123
124    let github_oauth_provider = GitHubOAuthProvider::new_github(github_config);
125    let oauth_provider = OAuthProvider::new(github_oauth_provider, oauth_provider_rs::http_integration::config::OAuthProviderConfig::default());
126
127    // Create custom routers
128
129    // 1. Health and basic endpoints router
130    let health_router = Router::new()
131        .route("/health", get(health_check))
132        .route("/webhooks", post(webhook_handler));
133
134    // 2. Monitoring router with path prefix
135    let monitoring_router = Router::new().route("/metrics", get(metrics));
136
137    // 3. API router with versioned endpoints
138    let api_router = Router::new()
139        .route("/v1/status", get(api_status))
140        .route("/{version}/status", get(api_status));
141
142    // 4. Admin router with HTML interface
143    let admin_router = Router::new().route("/", get(admin_dashboard));
144
145    // Configure custom routers with different configurations
146    let custom_routers = vec![
147        // Health router without prefix (attached to root)
148        (health_router, CustomRouterConfig::default()),
149        // Monitoring router with prefix and name
150        (
151            monitoring_router,
152            CustomRouterConfig::with_name_and_prefix("Monitoring", "/monitoring"),
153        ),
154        // API router with prefix
155        (
156            api_router,
157            CustomRouterConfig::with_name_and_prefix("API", "/api"),
158        ),
159        // Admin router with prefix
160        (
161            admin_router,
162            CustomRouterConfig::with_name_and_prefix("Admin Dashboard", "/admin"),
163        ),
164    ];
165
166    // Build the microkernel server with OAuth provider and custom routers
167    let microkernel: GitHubMicrokernelServer = MicrokernelServer::new()
168        .with_oauth_provider(oauth_provider)
169        .with_custom_routers(custom_routers);
170
171    // Define the bind address
172    let bind_address: SocketAddr = "127.0.0.1:8080".parse()?;
173
174    // Print available endpoints
175    println!("🚀 Starting microkernel server with custom routers...");
176    println!("📍 Server listening on: http://{}", bind_address);
177    println!("\n📋 Available endpoints:");
178    println!("  OAuth:");
179    println!("    GET  /oauth/login");
180    println!("    GET  /oauth/callback");
181    println!("    POST /oauth/token");
182    println!("  Custom Endpoints:");
183    println!("    GET  /health                  - Health check");
184    println!("    POST /webhooks                - Webhook handler");
185    println!("    GET  /monitoring/metrics      - System metrics");
186    println!("    GET  /api/v1/status           - API status");
187    println!("    GET  /api/{{version}}/status   - Versioned API status");
188    println!("    GET  /admin                   - Admin dashboard");
189    println!("\n🔧 Try these commands:");
190    println!("  curl http://localhost:8080/health");
191    println!("  curl http://localhost:8080/monitoring/metrics");
192    println!("  curl http://localhost:8080/api/v1/status");
193    println!("  open http://localhost:8080/admin");
194
195    // Start the server
196    microkernel.serve(bind_address).await?;
197
198    Ok(())
199}
Source

pub fn with_streamable_handler( self, streamable_handler: StreamableHttpHandler<M>, ) -> Self

Add streamable HTTP handler

Source

pub fn with_sse_handler( self, sse_handler: SseHandler<M>, config: SseHandlerConfig, ) -> Self

Add SSE handler with configuration

Source

pub fn with_mcp_sse_handler( self, mcp_server: M, config: SseHandlerConfig, ) -> Self

Create SSE handler with MCP server and configuration

Examples found in repository?
examples/custom_mcp_server_example.rs (line 472)
416async fn main() -> AppResult<()> {
417    // Load environment variables
418    dotenv::dotenv().ok();
419
420    // Initialize tracing
421    init_tracing()?;
422
423    tracing::info!("Starting Custom MCP Server example with Cognito and DynamoDB storage...");
424
425    // Create Cognito OAuth configuration
426    let cognito_config = get_cognito_oauth_provider_config()?;
427
428    // Get DynamoDB configuration
429    let table_name =
430        env::var("DYNAMODB_TABLE_NAME").unwrap_or_else(|_| "oauth-storage".to_string());
431    let create_table = env::var("DYNAMODB_CREATE_TABLE")
432        .unwrap_or_else(|_| "true".to_string())
433        .parse::<bool>()
434        .unwrap_or(true);
435
436    // Log configuration
437    log_startup_info(&table_name, create_table);
438
439    // Create DynamoDB storage
440    let (storage, client_manager) = create_dynamodb_storage(
441        table_name.clone(),
442        create_table,
443        Some("expires_at".to_string()),
444    )
445    .await
446    .map_err(|e| {
447        remote_mcp_kernel::error::AppError::Internal(format!(
448            "Failed to create DynamoDB storage: {}",
449            e
450        ))
451    })?;
452
453    // Create Cognito OAuth provider with DynamoDB storage
454    let oauth_handler = oauth_provider_rs::CognitoOAuthHandler::new_simple(
455        storage,
456        client_manager,
457        cognito_config,
458        get_cognito_domain()?,
459        get_cognito_region()?,
460        get_cognito_user_pool_id()?,
461    );
462
463    let oauth_provider = OAuthProvider::new(oauth_handler, oauth_provider_rs::http_integration::config::OAuthProviderConfig::default());
464
465    // Create custom MCP server
466    let custom_mcp_server = CustomMcpServer::new("Custom File & System MCP Server".to_string());
467
468    // Build microkernel with custom MCP server using convenience methods
469    let microkernel = MicrokernelServer::new()
470        .with_oauth_provider(oauth_provider)
471        .with_mcp_streamable_handler(custom_mcp_server.clone())
472        .with_mcp_sse_handler(custom_mcp_server, SseHandlerConfig::default());
473
474    // Start the microkernel server
475    let bind_address = get_bind_socket_addr()?;
476    tracing::info!("🚀 Starting microkernel server on {}", bind_address);
477    microkernel.serve(bind_address).await?;
478
479    Ok(())
480}
Source

pub fn with_mcp_streamable_handler(self, mcp_server: M) -> Self

Create streamable HTTP handler with MCP server

Examples found in repository?
examples/custom_mcp_server_example.rs (line 471)
416async fn main() -> AppResult<()> {
417    // Load environment variables
418    dotenv::dotenv().ok();
419
420    // Initialize tracing
421    init_tracing()?;
422
423    tracing::info!("Starting Custom MCP Server example with Cognito and DynamoDB storage...");
424
425    // Create Cognito OAuth configuration
426    let cognito_config = get_cognito_oauth_provider_config()?;
427
428    // Get DynamoDB configuration
429    let table_name =
430        env::var("DYNAMODB_TABLE_NAME").unwrap_or_else(|_| "oauth-storage".to_string());
431    let create_table = env::var("DYNAMODB_CREATE_TABLE")
432        .unwrap_or_else(|_| "true".to_string())
433        .parse::<bool>()
434        .unwrap_or(true);
435
436    // Log configuration
437    log_startup_info(&table_name, create_table);
438
439    // Create DynamoDB storage
440    let (storage, client_manager) = create_dynamodb_storage(
441        table_name.clone(),
442        create_table,
443        Some("expires_at".to_string()),
444    )
445    .await
446    .map_err(|e| {
447        remote_mcp_kernel::error::AppError::Internal(format!(
448            "Failed to create DynamoDB storage: {}",
449            e
450        ))
451    })?;
452
453    // Create Cognito OAuth provider with DynamoDB storage
454    let oauth_handler = oauth_provider_rs::CognitoOAuthHandler::new_simple(
455        storage,
456        client_manager,
457        cognito_config,
458        get_cognito_domain()?,
459        get_cognito_region()?,
460        get_cognito_user_pool_id()?,
461    );
462
463    let oauth_provider = OAuthProvider::new(oauth_handler, oauth_provider_rs::http_integration::config::OAuthProviderConfig::default());
464
465    // Create custom MCP server
466    let custom_mcp_server = CustomMcpServer::new("Custom File & System MCP Server".to_string());
467
468    // Build microkernel with custom MCP server using convenience methods
469    let microkernel = MicrokernelServer::new()
470        .with_oauth_provider(oauth_provider)
471        .with_mcp_streamable_handler(custom_mcp_server.clone())
472        .with_mcp_sse_handler(custom_mcp_server, SseHandlerConfig::default());
473
474    // Start the microkernel server
475    let bind_address = get_bind_socket_addr()?;
476    tracing::info!("🚀 Starting microkernel server on {}", bind_address);
477    microkernel.serve(bind_address).await?;
478
479    Ok(())
480}
Source

pub fn with_custom_router(self, router: Router) -> Self

Attach a custom router to the microkernel server

This method allows attaching arbitrary axum Routers to the microkernel server, enabling extension of the server with custom endpoints while maintaining microkernel architecture principles.

§Arguments
  • router - The axum Router to attach
§Examples
use axum::{Router, routing::get, response::Html};
use remote_mcp_kernel::microkernel::GitHubMicrokernelServer;

async fn hello() -> Html<&'static str> {
    Html("<h1>Hello, World!</h1>")
}

let custom_router = Router::new()
    .route("/hello", get(hello));

let server: GitHubMicrokernelServer = GitHubMicrokernelServer::new()
    .with_custom_router(custom_router);
Examples found in repository?
examples/simple_custom_router_test.rs (line 53)
30async fn main() -> Result<(), Box<dyn std::error::Error>> {
31    println!("🧪 Testing custom router functionality...");
32
33    // Create OAuth provider
34    let github_config = OAuthProviderConfig::with_oauth_config(
35        "test_client_id".to_string(),
36        "test_client_secret".to_string(),
37        "http://localhost:8080/oauth/callback".to_string(),
38        "read:user".to_string(),
39        "github".to_string(),
40    );
41
42    let github_oauth_provider = GitHubOAuthProvider::new_github(github_config);
43    let oauth_provider = OAuthProvider::new(github_oauth_provider, oauth_provider_rs::http_integration::config::OAuthProviderConfig::default());
44
45    // Create custom routers
46    let health_router = Router::new().route("/health", get(health_check));
47
48    let api_router = Router::new().route("/status", get(api_status));
49
50    // Build microkernel server with custom routers
51    let microkernel: GitHubMicrokernelServer = MicrokernelServer::new()
52        .with_oauth_provider(oauth_provider)
53        .with_custom_router(health_router)
54        .with_custom_router_config(api_router, CustomRouterConfig::with_prefix("/api"));
55
56    // Test that the router can be built
57    let router = microkernel.build_router()?;
58    println!("✅ Router built successfully!");
59
60    // Print available endpoints
61    println!("\n📋 Server would have these endpoints:");
62    println!("  OAuth:");
63    println!("    GET  /oauth/login");
64    println!("    GET  /oauth/callback");
65    println!("    POST /oauth/token");
66    println!("  Custom:");
67    println!("    GET  /health");
68    println!("    GET  /api/status");
69
70    println!("\n🎉 Custom router functionality is working correctly!");
71    println!("   The server can be built and all routers are properly attached.");
72
73    Ok(())
74}
Source

pub fn with_custom_router_config( self, router: Router, config: CustomRouterConfig, ) -> Self

Attach a custom router with configuration to the microkernel server

This method provides more control over how the custom router is attached, allowing for custom configuration such as path prefixes and names.

§Arguments
  • router - The axum Router to attach
  • config - Configuration for the custom router
§Examples
use axum::{Router, routing::get, response::Html};
use remote_mcp_kernel::microkernel::{GitHubMicrokernelServer, CustomRouterConfig};

async fn api_status() -> Html<&'static str> {
    Html("<h1>API Status: OK</h1>")
}

let custom_router = Router::new()
    .route("/status", get(api_status));

let config = CustomRouterConfig {
    name: Some("API Router".to_string()),
    path_prefix: Some("/api".to_string()),
};

let server: GitHubMicrokernelServer = GitHubMicrokernelServer::new()
    .with_custom_router_config(custom_router, config);
Examples found in repository?
examples/simple_custom_router_test.rs (line 54)
30async fn main() -> Result<(), Box<dyn std::error::Error>> {
31    println!("🧪 Testing custom router functionality...");
32
33    // Create OAuth provider
34    let github_config = OAuthProviderConfig::with_oauth_config(
35        "test_client_id".to_string(),
36        "test_client_secret".to_string(),
37        "http://localhost:8080/oauth/callback".to_string(),
38        "read:user".to_string(),
39        "github".to_string(),
40    );
41
42    let github_oauth_provider = GitHubOAuthProvider::new_github(github_config);
43    let oauth_provider = OAuthProvider::new(github_oauth_provider, oauth_provider_rs::http_integration::config::OAuthProviderConfig::default());
44
45    // Create custom routers
46    let health_router = Router::new().route("/health", get(health_check));
47
48    let api_router = Router::new().route("/status", get(api_status));
49
50    // Build microkernel server with custom routers
51    let microkernel: GitHubMicrokernelServer = MicrokernelServer::new()
52        .with_oauth_provider(oauth_provider)
53        .with_custom_router(health_router)
54        .with_custom_router_config(api_router, CustomRouterConfig::with_prefix("/api"));
55
56    // Test that the router can be built
57    let router = microkernel.build_router()?;
58    println!("✅ Router built successfully!");
59
60    // Print available endpoints
61    println!("\n📋 Server would have these endpoints:");
62    println!("  OAuth:");
63    println!("    GET  /oauth/login");
64    println!("    GET  /oauth/callback");
65    println!("    POST /oauth/token");
66    println!("  Custom:");
67    println!("    GET  /health");
68    println!("    GET  /api/status");
69
70    println!("\n🎉 Custom router functionality is working correctly!");
71    println!("   The server can be built and all routers are properly attached.");
72
73    Ok(())
74}
Source

pub fn with_custom_routers( self, routers: Vec<(Router, CustomRouterConfig)>, ) -> Self

Attach multiple custom routers at once

This method allows attaching multiple custom routers efficiently.

§Arguments
  • routers - A vector of tuples containing (Router, CustomRouterConfig)
§Examples
use axum::{Router, routing::get, response::Html};
use remote_mcp_kernel::microkernel::{GitHubMicrokernelServer, CustomRouterConfig};

async fn health() -> Html<&'static str> {
    Html("<h1>Health: OK</h1>")
}

async fn metrics() -> Html<&'static str> {
    Html("<h1>Metrics: OK</h1>")
}

let health_router = Router::new().route("/health", get(health));
let metrics_router = Router::new().route("/metrics", get(metrics));

let routers = vec![
    (health_router, CustomRouterConfig::default()),
    (metrics_router, CustomRouterConfig {
        name: Some("Metrics".to_string()),
        path_prefix: Some("/monitoring".to_string()),
    }),
];

let server: GitHubMicrokernelServer = GitHubMicrokernelServer::new()
    .with_custom_routers(routers);
Examples found in repository?
examples/custom_router_example.rs (line 169)
109async fn main() -> Result<(), Box<dyn std::error::Error>> {
110    // Initialize tracing for logging
111    tracing_subscriber::fmt::init();
112
113    // Create GitHub OAuth provider
114    let github_config = OAuthProviderConfig::with_oauth_config(
115        std::env::var("GITHUB_CLIENT_ID")
116            .unwrap_or_else(|_| "demo_client_id".to_string()),
117        std::env::var("GITHUB_CLIENT_SECRET")
118            .unwrap_or_else(|_| "demo_client_secret".to_string()),
119        "http://localhost:8080/oauth/callback".to_string(),
120        "read:user".to_string(),
121        "github".to_string(),
122    );
123
124    let github_oauth_provider = GitHubOAuthProvider::new_github(github_config);
125    let oauth_provider = OAuthProvider::new(github_oauth_provider, oauth_provider_rs::http_integration::config::OAuthProviderConfig::default());
126
127    // Create custom routers
128
129    // 1. Health and basic endpoints router
130    let health_router = Router::new()
131        .route("/health", get(health_check))
132        .route("/webhooks", post(webhook_handler));
133
134    // 2. Monitoring router with path prefix
135    let monitoring_router = Router::new().route("/metrics", get(metrics));
136
137    // 3. API router with versioned endpoints
138    let api_router = Router::new()
139        .route("/v1/status", get(api_status))
140        .route("/{version}/status", get(api_status));
141
142    // 4. Admin router with HTML interface
143    let admin_router = Router::new().route("/", get(admin_dashboard));
144
145    // Configure custom routers with different configurations
146    let custom_routers = vec![
147        // Health router without prefix (attached to root)
148        (health_router, CustomRouterConfig::default()),
149        // Monitoring router with prefix and name
150        (
151            monitoring_router,
152            CustomRouterConfig::with_name_and_prefix("Monitoring", "/monitoring"),
153        ),
154        // API router with prefix
155        (
156            api_router,
157            CustomRouterConfig::with_name_and_prefix("API", "/api"),
158        ),
159        // Admin router with prefix
160        (
161            admin_router,
162            CustomRouterConfig::with_name_and_prefix("Admin Dashboard", "/admin"),
163        ),
164    ];
165
166    // Build the microkernel server with OAuth provider and custom routers
167    let microkernel: GitHubMicrokernelServer = MicrokernelServer::new()
168        .with_oauth_provider(oauth_provider)
169        .with_custom_routers(custom_routers);
170
171    // Define the bind address
172    let bind_address: SocketAddr = "127.0.0.1:8080".parse()?;
173
174    // Print available endpoints
175    println!("🚀 Starting microkernel server with custom routers...");
176    println!("📍 Server listening on: http://{}", bind_address);
177    println!("\n📋 Available endpoints:");
178    println!("  OAuth:");
179    println!("    GET  /oauth/login");
180    println!("    GET  /oauth/callback");
181    println!("    POST /oauth/token");
182    println!("  Custom Endpoints:");
183    println!("    GET  /health                  - Health check");
184    println!("    POST /webhooks                - Webhook handler");
185    println!("    GET  /monitoring/metrics      - System metrics");
186    println!("    GET  /api/v1/status           - API status");
187    println!("    GET  /api/{{version}}/status   - Versioned API status");
188    println!("    GET  /admin                   - Admin dashboard");
189    println!("\n🔧 Try these commands:");
190    println!("  curl http://localhost:8080/health");
191    println!("  curl http://localhost:8080/monitoring/metrics");
192    println!("  curl http://localhost:8080/api/v1/status");
193    println!("  open http://localhost:8080/admin");
194
195    // Start the server
196    microkernel.serve(bind_address).await?;
197
198    Ok(())
199}
Source

pub fn build_router(self) -> AppResult<Router>

Build the composed router from all registered handlers

This method demonstrates the microkernel composition principle where independent components are combined into a unified service. Now includes support for custom routers with path prefixes and configuration.

Examples found in repository?
examples/simple_custom_router_test.rs (line 57)
30async fn main() -> Result<(), Box<dyn std::error::Error>> {
31    println!("🧪 Testing custom router functionality...");
32
33    // Create OAuth provider
34    let github_config = OAuthProviderConfig::with_oauth_config(
35        "test_client_id".to_string(),
36        "test_client_secret".to_string(),
37        "http://localhost:8080/oauth/callback".to_string(),
38        "read:user".to_string(),
39        "github".to_string(),
40    );
41
42    let github_oauth_provider = GitHubOAuthProvider::new_github(github_config);
43    let oauth_provider = OAuthProvider::new(github_oauth_provider, oauth_provider_rs::http_integration::config::OAuthProviderConfig::default());
44
45    // Create custom routers
46    let health_router = Router::new().route("/health", get(health_check));
47
48    let api_router = Router::new().route("/status", get(api_status));
49
50    // Build microkernel server with custom routers
51    let microkernel: GitHubMicrokernelServer = MicrokernelServer::new()
52        .with_oauth_provider(oauth_provider)
53        .with_custom_router(health_router)
54        .with_custom_router_config(api_router, CustomRouterConfig::with_prefix("/api"));
55
56    // Test that the router can be built
57    let router = microkernel.build_router()?;
58    println!("✅ Router built successfully!");
59
60    // Print available endpoints
61    println!("\n📋 Server would have these endpoints:");
62    println!("  OAuth:");
63    println!("    GET  /oauth/login");
64    println!("    GET  /oauth/callback");
65    println!("    POST /oauth/token");
66    println!("  Custom:");
67    println!("    GET  /health");
68    println!("    GET  /api/status");
69
70    println!("\n🎉 Custom router functionality is working correctly!");
71    println!("   The server can be built and all routers are properly attached.");
72
73    Ok(())
74}
Source

pub async fn serve(self, bind_address: SocketAddr) -> AppResult<()>

Start the microkernel server

Examples found in repository?
examples/oauth_standard_mcp_server.rs (line 31)
10async fn main() -> AppResult<()> {
11    // Load environment variables
12    dotenv::dotenv().ok();
13
14    // Initialize tracing
15    init_tracing()?;
16
17    tracing::info!("Starting MCP OAuth server with microkernel architecture...");
18
19    // Create OAuth provider
20    let github_config = get_github_oauth_provider_config()?;
21    let oauth_provider = GitHubOAuthProvider::new_github(github_config);
22
23    // Log configuration
24    log_startup_info();
25
26    // Create microkernel server with all handlers composed
27    let microkernel = create_full_github_microkernel(oauth_provider);
28
29    // Start the microkernel server
30    let bind_address = get_bind_socket_addr()?;
31    microkernel.serve(bind_address).await?;
32
33    Ok(())
34}
More examples
Hide additional examples
examples/oauth_cognito_mcp_server.rs (line 36)
10async fn main() -> AppResult<()> {
11    // Load environment variables
12    dotenv::dotenv().ok();
13
14    // Initialize tracing
15    init_tracing()?;
16
17    tracing::info!("Starting MCP OAuth server with Cognito and microkernel architecture...");
18
19    // Create Cognito OAuth provider
20    let cognito_config = get_cognito_oauth_provider_config()?;
21    let oauth_provider = CognitoOAuthProvider::new_cognito(
22        cognito_config,
23        get_cognito_domain()?,
24        get_cognito_region()?,
25        get_cognito_user_pool_id()?,
26    );
27
28    // Log configuration
29    log_startup_info();
30
31    // Create microkernel server with all handlers composed
32    let microkernel = create_full_cognito_microkernel(oauth_provider);
33
34    // Start the microkernel server
35    let bind_address = get_bind_socket_addr()?;
36    microkernel.serve(bind_address).await?;
37
38    Ok(())
39}
examples/oauth_cognito_dynamodb_mcp_server.rs (line 99)
60async fn main() -> AppResult<()> {
61    // Load environment variables
62    dotenv::dotenv().ok();
63
64    // Initialize tracing
65    init_tracing()?;
66
67    tracing::info!("Starting MCP OAuth server with Cognito and DynamoDB storage...");
68
69    // Create Cognito OAuth configuration
70    let cognito_config = get_cognito_oauth_provider_config()?;
71
72    // Get DynamoDB configuration
73    let table_name =
74        env::var("DYNAMODB_TABLE_NAME").unwrap_or_else(|_| "oauth-storage".to_string());
75    let create_table = env::var("DYNAMODB_CREATE_TABLE")
76        .unwrap_or_else(|_| "true".to_string())
77        .parse::<bool>()
78        .unwrap_or(true);
79
80    // Log configuration
81    log_startup_info(&table_name, create_table);
82
83    // Create microkernel server with Cognito OAuth and DynamoDB storage
84    let microkernel = create_full_cognito_microkernel_dynamodb(
85        cognito_config,
86        get_cognito_domain()?,
87        get_cognito_region()?,
88        get_cognito_user_pool_id()?,
89        table_name,
90        create_table,
91    )
92    .await
93    .map_err(|e| {
94        remote_mcp_kernel::error::AppError::Internal(format!("Failed to create microkernel: {}", e))
95    })?;
96
97    // Start the microkernel server
98    let bind_address = get_bind_socket_addr()?;
99    microkernel.serve(bind_address).await?;
100
101    Ok(())
102}
examples/custom_mcp_server_example.rs (line 477)
416async fn main() -> AppResult<()> {
417    // Load environment variables
418    dotenv::dotenv().ok();
419
420    // Initialize tracing
421    init_tracing()?;
422
423    tracing::info!("Starting Custom MCP Server example with Cognito and DynamoDB storage...");
424
425    // Create Cognito OAuth configuration
426    let cognito_config = get_cognito_oauth_provider_config()?;
427
428    // Get DynamoDB configuration
429    let table_name =
430        env::var("DYNAMODB_TABLE_NAME").unwrap_or_else(|_| "oauth-storage".to_string());
431    let create_table = env::var("DYNAMODB_CREATE_TABLE")
432        .unwrap_or_else(|_| "true".to_string())
433        .parse::<bool>()
434        .unwrap_or(true);
435
436    // Log configuration
437    log_startup_info(&table_name, create_table);
438
439    // Create DynamoDB storage
440    let (storage, client_manager) = create_dynamodb_storage(
441        table_name.clone(),
442        create_table,
443        Some("expires_at".to_string()),
444    )
445    .await
446    .map_err(|e| {
447        remote_mcp_kernel::error::AppError::Internal(format!(
448            "Failed to create DynamoDB storage: {}",
449            e
450        ))
451    })?;
452
453    // Create Cognito OAuth provider with DynamoDB storage
454    let oauth_handler = oauth_provider_rs::CognitoOAuthHandler::new_simple(
455        storage,
456        client_manager,
457        cognito_config,
458        get_cognito_domain()?,
459        get_cognito_region()?,
460        get_cognito_user_pool_id()?,
461    );
462
463    let oauth_provider = OAuthProvider::new(oauth_handler, oauth_provider_rs::http_integration::config::OAuthProviderConfig::default());
464
465    // Create custom MCP server
466    let custom_mcp_server = CustomMcpServer::new("Custom File & System MCP Server".to_string());
467
468    // Build microkernel with custom MCP server using convenience methods
469    let microkernel = MicrokernelServer::new()
470        .with_oauth_provider(oauth_provider)
471        .with_mcp_streamable_handler(custom_mcp_server.clone())
472        .with_mcp_sse_handler(custom_mcp_server, SseHandlerConfig::default());
473
474    // Start the microkernel server
475    let bind_address = get_bind_socket_addr()?;
476    tracing::info!("🚀 Starting microkernel server on {}", bind_address);
477    microkernel.serve(bind_address).await?;
478
479    Ok(())
480}
examples/custom_router_example.rs (line 196)
109async fn main() -> Result<(), Box<dyn std::error::Error>> {
110    // Initialize tracing for logging
111    tracing_subscriber::fmt::init();
112
113    // Create GitHub OAuth provider
114    let github_config = OAuthProviderConfig::with_oauth_config(
115        std::env::var("GITHUB_CLIENT_ID")
116            .unwrap_or_else(|_| "demo_client_id".to_string()),
117        std::env::var("GITHUB_CLIENT_SECRET")
118            .unwrap_or_else(|_| "demo_client_secret".to_string()),
119        "http://localhost:8080/oauth/callback".to_string(),
120        "read:user".to_string(),
121        "github".to_string(),
122    );
123
124    let github_oauth_provider = GitHubOAuthProvider::new_github(github_config);
125    let oauth_provider = OAuthProvider::new(github_oauth_provider, oauth_provider_rs::http_integration::config::OAuthProviderConfig::default());
126
127    // Create custom routers
128
129    // 1. Health and basic endpoints router
130    let health_router = Router::new()
131        .route("/health", get(health_check))
132        .route("/webhooks", post(webhook_handler));
133
134    // 2. Monitoring router with path prefix
135    let monitoring_router = Router::new().route("/metrics", get(metrics));
136
137    // 3. API router with versioned endpoints
138    let api_router = Router::new()
139        .route("/v1/status", get(api_status))
140        .route("/{version}/status", get(api_status));
141
142    // 4. Admin router with HTML interface
143    let admin_router = Router::new().route("/", get(admin_dashboard));
144
145    // Configure custom routers with different configurations
146    let custom_routers = vec![
147        // Health router without prefix (attached to root)
148        (health_router, CustomRouterConfig::default()),
149        // Monitoring router with prefix and name
150        (
151            monitoring_router,
152            CustomRouterConfig::with_name_and_prefix("Monitoring", "/monitoring"),
153        ),
154        // API router with prefix
155        (
156            api_router,
157            CustomRouterConfig::with_name_and_prefix("API", "/api"),
158        ),
159        // Admin router with prefix
160        (
161            admin_router,
162            CustomRouterConfig::with_name_and_prefix("Admin Dashboard", "/admin"),
163        ),
164    ];
165
166    // Build the microkernel server with OAuth provider and custom routers
167    let microkernel: GitHubMicrokernelServer = MicrokernelServer::new()
168        .with_oauth_provider(oauth_provider)
169        .with_custom_routers(custom_routers);
170
171    // Define the bind address
172    let bind_address: SocketAddr = "127.0.0.1:8080".parse()?;
173
174    // Print available endpoints
175    println!("🚀 Starting microkernel server with custom routers...");
176    println!("📍 Server listening on: http://{}", bind_address);
177    println!("\n📋 Available endpoints:");
178    println!("  OAuth:");
179    println!("    GET  /oauth/login");
180    println!("    GET  /oauth/callback");
181    println!("    POST /oauth/token");
182    println!("  Custom Endpoints:");
183    println!("    GET  /health                  - Health check");
184    println!("    POST /webhooks                - Webhook handler");
185    println!("    GET  /monitoring/metrics      - System metrics");
186    println!("    GET  /api/v1/status           - API status");
187    println!("    GET  /api/{{version}}/status   - Versioned API status");
188    println!("    GET  /admin                   - Admin dashboard");
189    println!("\n🔧 Try these commands:");
190    println!("  curl http://localhost:8080/health");
191    println!("  curl http://localhost:8080/monitoring/metrics");
192    println!("  curl http://localhost:8080/api/v1/status");
193    println!("  open http://localhost:8080/admin");
194
195    // Start the server
196    microkernel.serve(bind_address).await?;
197
198    Ok(())
199}

Trait Implementations§

Source§

impl<P: OAuthProviderTrait<S, DefaultClientManager<S>>, S: OAuthStorage + Clone + 'static, M: McpServerHandler> Default for MicrokernelServer<P, S, M>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<P, S, M> Freeze for MicrokernelServer<P, S, M>
where P: Freeze, S: Freeze, M: Freeze,

§

impl<P, S, M = McpServer> !RefUnwindSafe for MicrokernelServer<P, S, M>

§

impl<P, S, M> Send for MicrokernelServer<P, S, M>

§

impl<P, S, M> Sync for MicrokernelServer<P, S, M>

§

impl<P, S, M> Unpin for MicrokernelServer<P, S, M>
where P: Unpin, S: Unpin, M: Unpin,

§

impl<P, S, M = McpServer> !UnwindSafe for MicrokernelServer<P, S, M>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

Source§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,