1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
// Copyright 2025 Kindly Software Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! `KindlyGuard` MCP Security Server
//!
//! A focused security server for the Model Context Protocol that protects
//! against unicode attacks, injection attempts, and other threats.
use anyhow::Result;
use clap::Parser;
use std::sync::Arc;
use tracing::{error, info};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
// Use the library crate instead of re-declaring modules
use kindly_guard_server::{cli, config, daemon, server};
use cli::commands::Commands;
use config::Config;
use server::McpServer;
/// Start telemetry flush task if enabled
fn start_telemetry_flush(
enabled: bool,
interval_seconds: u64,
server: Arc<McpServer>,
) -> Option<tokio::task::JoinHandle<()>> {
if enabled {
Some(tokio::spawn(async move {
let mut interval =
tokio::time::interval(tokio::time::Duration::from_secs(interval_seconds));
loop {
interval.tick().await;
let telemetry = server.component_manager.telemetry_provider();
if let Err(e) = telemetry.flush().await {
error!("Failed to flush telemetry: {}", e);
}
}
}))
} else {
None
}
}
/// Command line arguments
#[derive(Parser, Debug)]
#[command(name = "kindly-guard")]
#[command(about = "Security-focused MCP server", long_about = None)]
struct Args {
/// Path to configuration file
#[arg(short, long)]
config: Option<String>,
/// Run in stdio mode (default)
#[arg(long, conflicts_with_all = ["http", "proxy", "daemon"])]
stdio: bool,
/// Run HTTP API server
#[arg(long, conflicts_with_all = ["stdio", "proxy", "daemon"])]
http: bool,
/// Run as HTTPS proxy
#[arg(long, conflicts_with_all = ["stdio", "http", "daemon"])]
proxy: bool,
/// Bind address for HTTP/proxy mode
#[arg(long, default_value = "127.0.0.1:8080")]
bind: String,
/// Run as daemon
#[arg(long, conflicts_with_all = ["stdio", "http", "proxy"])]
daemon: bool,
/// PID file path (for daemon mode)
#[arg(long, requires = "daemon")]
pid_file: Option<String>,
/// Enable shield display
#[arg(long)]
shield: bool,
/// Run as command interface (e.g., /kindlyguard status)
#[command(subcommand)]
command: Option<Commands>,
/// Output format for commands
#[arg(short = 'f', long, global = true)]
format: Option<String>,
/// Disable color output
#[arg(long, global = true)]
no_color: bool,
}
#[tokio::main]
async fn main() -> Result<()> {
// Parse command line arguments
let args = Args::parse();
// Check if running in command mode with JSON output
let is_json_command =
args.command.is_some() && args.format.as_ref().map(|f| f == "json").unwrap_or(false);
// Initialize logging - suppress for JSON command output
if is_json_command {
// For JSON output, disable all logging or set to error level only
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "kindly_guard=error".into()),
)
.with(tracing_subscriber::fmt::layer().with_writer(std::io::stderr))
.init();
} else {
// Normal logging initialization
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "kindly_guard=info".into()),
)
.with(tracing_subscriber::fmt::layer())
.init();
}
// Check if running in command mode
if args.command.is_some() {
// Command mode - don't show server startup message
let cmd = cli::commands::KindlyCommand {
command: args.command,
format: args.format.unwrap_or_else(|| "text".to_string()),
no_color: args.no_color,
};
return cli::commands::run_command(cmd).await;
}
info!("🛡️ KindlyGuard MCP Security Server starting...");
// Load configuration
let config = if let Some(path) = args.config {
Config::load_from_file(&path)?
} else {
Config::load()?
};
// Store telemetry configuration before moving config
let telemetry_enabled = config.telemetry.export_endpoint.is_some();
let telemetry_interval = config.telemetry.export_interval_seconds;
// Create the MCP server
let server = Arc::new(McpServer::new(config)?);
// Optionally start shield display
let shield_handle = if args.shield {
let shield = server.shield.clone();
Some(tokio::spawn(async move {
if let Err(e) = shield.start_display().await {
error!("Shield display error: {}", e);
}
}))
} else {
None
};
// Run the server
if args.daemon {
// Daemon mode
info!("Running in daemon mode");
let daemon_config = daemon::DaemonConfig {
pid_file: args.pid_file,
..Default::default()
};
daemon::run_with_daemon(daemon_config, |mut shutdown_rx| async move {
// Start HTTP server in daemon mode
let server_clone = server.clone();
let server_handle = tokio::spawn(async move {
if let Err(e) = server_clone.run_http("127.0.0.1:8080").await {
error!("HTTP server error: {}", e);
}
});
// Wait for shutdown signal
let _ = shutdown_rx.recv().await;
info!("Received shutdown signal");
// Gracefully shutdown server
server_handle.abort();
Ok(())
})
.await?;
} else if args.http {
info!("Running HTTP API server on {}", args.bind);
// Start periodic telemetry flush if configured
let telemetry_flush_handle =
start_telemetry_flush(telemetry_enabled, telemetry_interval, server.clone());
match server.run_http(&args.bind).await {
Ok(()) => {
info!("HTTP server shutting down gracefully");
},
Err(e) => {
error!("HTTP server error: {}", e);
return Err(e);
},
}
// Stop telemetry flush task
if let Some(handle) = telemetry_flush_handle {
handle.abort();
}
} else if args.proxy {
info!("Running as HTTPS proxy on {}", args.bind);
// Start periodic telemetry flush if configured
let telemetry_flush_handle =
start_telemetry_flush(telemetry_enabled, telemetry_interval, server.clone());
match server.run_proxy(&args.bind).await {
Ok(()) => {
info!("Proxy server shutting down gracefully");
},
Err(e) => {
error!("Proxy server error: {}", e);
return Err(e);
},
}
// Stop telemetry flush task
if let Some(handle) = telemetry_flush_handle {
handle.abort();
}
} else {
// Default to stdio mode if no mode specified
info!("Running in stdio mode (default)");
// Start periodic telemetry flush if configured
let telemetry_flush_handle =
start_telemetry_flush(telemetry_enabled, telemetry_interval, server.clone());
match server.run_stdio().await {
Ok(()) => {
info!("KindlyGuard server shutting down gracefully");
},
Err(e) => {
error!("Server error: {}", e);
return Err(e);
},
}
// Stop telemetry flush task
if let Some(handle) = telemetry_flush_handle {
handle.abort();
}
}
// Stop the shield display if running
if let Some(handle) = shield_handle {
handle.abort();
}
Ok(())
}
#[cfg(test)]
mod tests {
#[test]
fn test_main_compiles() {
// Simple compilation test
// This test ensures the main module compiles properly
}
}