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

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,