|
| 1 | +use std::sync::Arc; |
| 2 | + |
| 3 | +use clap::Parser; |
| 4 | +use color_eyre::Result; |
| 5 | +use tracing::info; |
| 6 | +use ultrafast_mcp::{ |
| 7 | + prelude::*, ListToolsRequest, ListToolsResponse, MCPError, MCPResult, ToolCall, ToolContent, |
| 8 | + ToolsCapability, |
| 9 | +}; |
| 10 | +use x402_rs::{ |
| 11 | + facilitator::Facilitator, |
| 12 | + facilitator_local::FacilitatorLocal, |
| 13 | + network::Network, |
| 14 | + provider_cache::ProviderCache, |
| 15 | + types::{ |
| 16 | + Scheme, SettleRequest, SettleResponse, SupportedPaymentKind, VerifyRequest, VerifyResponse, |
| 17 | + X402Version, |
| 18 | + }, |
| 19 | +}; |
| 20 | + |
| 21 | +#[derive(Parser, Debug)] |
| 22 | +#[command(name = "ledgerflow-mcp")] |
| 23 | +#[command(about = "MCP server exposing x402 verify/settle/supported tools", long_about = None)] |
| 24 | +pub struct Args { |
| 25 | + /// Run over stdio (default) |
| 26 | + #[arg(long)] |
| 27 | + stdio: bool, |
| 28 | + |
| 29 | + /// Run HTTP server instead of stdio |
| 30 | + #[arg(long)] |
| 31 | + http: bool, |
| 32 | + |
| 33 | + /// Host for HTTP server |
| 34 | + #[arg(long, default_value = "127.0.0.1")] |
| 35 | + host: String, |
| 36 | + |
| 37 | + /// Port for HTTP server |
| 38 | + #[arg(long, default_value_t = 8765)] |
| 39 | + port: u16, |
| 40 | +} |
| 41 | + |
| 42 | +#[derive(Clone)] |
| 43 | +struct X402ToolHandler { |
| 44 | + facilitator: FacilitatorLocal, |
| 45 | +} |
| 46 | + |
| 47 | +#[async_trait::async_trait] |
| 48 | +impl ToolHandler for X402ToolHandler { |
| 49 | + async fn handle_tool_call(&self, call: ToolCall) -> MCPResult<ToolResult> { |
| 50 | + match call.name.as_str() { |
| 51 | + "x402_supported" => { |
| 52 | + let kinds: Vec<SupportedPaymentKind> = Network::variants() |
| 53 | + .iter() |
| 54 | + .copied() |
| 55 | + .map(|n| SupportedPaymentKind { |
| 56 | + x402_version: X402Version::V1, |
| 57 | + scheme: Scheme::Exact, |
| 58 | + network: n, |
| 59 | + }) |
| 60 | + .collect(); |
| 61 | + let payload = serde_json::json!({ "supported": kinds }); |
| 62 | + Ok(ToolResult { |
| 63 | + content: vec![ToolContent::text(payload.to_string())], |
| 64 | + is_error: Some(false), |
| 65 | + }) |
| 66 | + } |
| 67 | + "x402_verify" => { |
| 68 | + let req_value = call.arguments.unwrap_or_default(); |
| 69 | + let req: VerifyRequest = serde_json::from_value(req_value) |
| 70 | + .map_err(|e| MCPError::invalid_params(format!("invalid arguments: {e}")))?; |
| 71 | + let res: VerifyResponse = self |
| 72 | + .facilitator |
| 73 | + .verify(&req) |
| 74 | + .await |
| 75 | + .map_err(|e| MCPError::internal_error(e.to_string()))?; |
| 76 | + Ok(ToolResult { |
| 77 | + content: vec![ToolContent::text( |
| 78 | + serde_json::to_string(&res).unwrap_or_else(|_| "{}".into()), |
| 79 | + )], |
| 80 | + is_error: Some(false), |
| 81 | + }) |
| 82 | + } |
| 83 | + "x402_settle" => { |
| 84 | + let req_value = call.arguments.unwrap_or_default(); |
| 85 | + let req: SettleRequest = serde_json::from_value(req_value) |
| 86 | + .map_err(|e| MCPError::invalid_params(format!("invalid arguments: {e}")))?; |
| 87 | + let res: SettleResponse = self |
| 88 | + .facilitator |
| 89 | + .settle(&req) |
| 90 | + .await |
| 91 | + .map_err(|e| MCPError::internal_error(e.to_string()))?; |
| 92 | + Ok(ToolResult { |
| 93 | + content: vec![ToolContent::text( |
| 94 | + serde_json::to_string(&res).unwrap_or_else(|_| "{}".into()), |
| 95 | + )], |
| 96 | + is_error: Some(false), |
| 97 | + }) |
| 98 | + } |
| 99 | + _ => Err(MCPError::method_not_found(format!( |
| 100 | + "tool '{}' not found", |
| 101 | + call.name |
| 102 | + ))), |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + async fn list_tools(&self, _request: ListToolsRequest) -> MCPResult<ListToolsResponse> { |
| 107 | + Ok(ListToolsResponse { |
| 108 | + tools: vec![ |
| 109 | + Tool { |
| 110 | + name: "x402_supported".to_string(), |
| 111 | + description: "List supported payment kinds (networks + schemes)".to_string(), |
| 112 | + input_schema: serde_json::json!({"type":"object","properties":{}}), |
| 113 | + output_schema: None, |
| 114 | + annotations: None, |
| 115 | + }, |
| 116 | + Tool { |
| 117 | + name: "x402_verify".to_string(), |
| 118 | + description: "Verify a payment intent using x402 Exact scheme".to_string(), |
| 119 | + input_schema: serde_json::json!({"type":"object"}), |
| 120 | + output_schema: None, |
| 121 | + annotations: None, |
| 122 | + }, |
| 123 | + Tool { |
| 124 | + name: "x402_settle".to_string(), |
| 125 | + description: "Settle a verified payment intent".to_string(), |
| 126 | + input_schema: serde_json::json!({"type":"object"}), |
| 127 | + output_schema: None, |
| 128 | + annotations: None, |
| 129 | + }, |
| 130 | + ], |
| 131 | + next_cursor: None, |
| 132 | + }) |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +#[tokio::main] |
| 137 | +async fn main() -> Result<()> { |
| 138 | + color_eyre::install()?; |
| 139 | + tracing_subscriber::fmt() |
| 140 | + .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) |
| 141 | + .init(); |
| 142 | + |
| 143 | + let args = Args::parse(); |
| 144 | + |
| 145 | + // Prepare providers/signers from env (shared with facilitator crate) |
| 146 | + dotenvy::dotenv().ok(); |
| 147 | + let providers = ProviderCache::from_env() |
| 148 | + .await |
| 149 | + .map_err(|e| eyre::eyre!(format!("{e}")))?; |
| 150 | + let facilitator = FacilitatorLocal::new(providers); |
| 151 | + |
| 152 | + let handler = X402ToolHandler { facilitator }; |
| 153 | + |
| 154 | + // Server info and capabilities |
| 155 | + let info = ServerInfo { |
| 156 | + name: "ledgerflow-mcp".to_string(), |
| 157 | + version: env!("CARGO_PKG_VERSION").to_string(), |
| 158 | + description: Some("MCP server exposing x402 verify/settle/supported".to_string()), |
| 159 | + authors: None, |
| 160 | + homepage: None, |
| 161 | + license: None, |
| 162 | + repository: None, |
| 163 | + }; |
| 164 | + |
| 165 | + let capabilities = ServerCapabilities { |
| 166 | + tools: Some(ToolsCapability { |
| 167 | + list_changed: Some(true), |
| 168 | + }), |
| 169 | + ..Default::default() |
| 170 | + }; |
| 171 | + let server = UltraFastServer::new(info, capabilities).with_tool_handler(Arc::new(handler)); |
| 172 | + |
| 173 | + if args.http { |
| 174 | + #[cfg(feature = "http")] |
| 175 | + { |
| 176 | + let addr = SocketAddr::from_str(&format!("{}:{}", args.host, args.port))?; |
| 177 | + info!(%addr, "Starting HTTP MCP server"); |
| 178 | + server |
| 179 | + .run_streamable_http(addr.ip().to_string().as_str(), addr.port()) |
| 180 | + .await?; |
| 181 | + } |
| 182 | + #[cfg(not(feature = "http"))] |
| 183 | + { |
| 184 | + info!("HTTP feature not enabled; falling back to stdio"); |
| 185 | + server.run_stdio().await?; |
| 186 | + } |
| 187 | + } else { |
| 188 | + info!("Starting stdio MCP server"); |
| 189 | + server.run_stdio().await?; |
| 190 | + } |
| 191 | + |
| 192 | + Ok(()) |
| 193 | +} |
0 commit comments