1mod database;
7mod error;
8mod handler;
9mod server;
10mod value;
11
12use std::collections::HashSet;
13use std::fmt;
14use std::fs;
15use std::net::SocketAddr;
16use std::path::{Path, PathBuf};
17use std::time::Duration;
18
19use sha2::{Digest, Sha256};
20use subtle::{Choice, ConstantTimeEq};
21
22pub use error::{McpServerError, Result};
23pub use server::McpServer;
24pub use tokio_util::sync::CancellationToken;
25
26#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct McpLimits {
29 pub max_concurrent_requests: usize,
30 pub max_request_bytes: usize,
31 pub max_argument_depth: usize,
32 pub max_argument_items: usize,
33 pub max_result_rows: usize,
34 pub max_result_bytes: usize,
35 pub transaction_timeout: Duration,
36 pub max_transaction_workspace_bytes: usize,
37 pub max_transaction_records: usize,
38 pub max_transaction_journal_bytes: u64,
39 pub max_query_memory_bytes: usize,
40 pub tls_handshake_timeout: Duration,
41 pub shutdown_grace_period: Duration,
42}
43
44impl Default for McpLimits {
45 fn default() -> Self {
46 Self {
47 max_concurrent_requests: 64,
48 max_request_bytes: 4 * 1024 * 1024,
49 max_argument_depth: 64,
50 max_argument_items: 100_000,
51 max_result_rows: 100_000,
52 max_result_bytes: 64 * 1024 * 1024,
53 transaction_timeout: Duration::from_secs(30),
54 max_transaction_workspace_bytes: 64 * 1024 * 1024,
55 max_transaction_records: 1_000_000,
56 max_transaction_journal_bytes: 256 * 1024 * 1024,
57 max_query_memory_bytes: 64 * 1024 * 1024,
58 tls_handshake_timeout: Duration::from_secs(5),
59 shutdown_grace_period: Duration::from_secs(5),
60 }
61 }
62}
63
64impl McpLimits {
65 pub(crate) fn validate(&self) -> Result<()> {
66 if self.max_concurrent_requests == 0
67 || self.max_request_bytes == 0
68 || self.max_argument_depth == 0
69 || self.max_argument_items == 0
70 || self.max_result_rows == 0
71 || self.max_result_bytes == 0
72 || self.transaction_timeout.is_zero()
73 || self.max_transaction_workspace_bytes == 0
74 || self.max_transaction_records == 0
75 || self.max_transaction_journal_bytes == 0
76 || self.max_query_memory_bytes == 0
77 || self.tls_handshake_timeout.is_zero()
78 || self.shutdown_grace_period.is_zero()
79 {
80 return Err(McpServerError::InvalidConfiguration(
81 "MCP resource limits must be positive".into(),
82 ));
83 }
84 Ok(())
85 }
86}
87
88#[derive(Clone, Debug, PartialEq, Eq)]
90pub struct McpTlsConfig {
91 pub certificate_file: PathBuf,
92 pub ca_file: Option<PathBuf>,
93}
94
95#[derive(Clone, PartialEq, Eq)]
97pub struct McpAuth(std::sync::Arc<McpAuthData>);
98
99#[derive(PartialEq, Eq)]
100struct McpAuthData {
101 credentials: Vec<McpCredential>,
102}
103
104#[derive(PartialEq, Eq)]
105struct McpCredential {
106 read_only: bool,
107 username_digest: [u8; 32],
108 password_digest: [u8; 32],
109}
110
111#[derive(Clone, Copy, Debug, PartialEq, Eq)]
112pub(crate) struct AuthContext {
113 pub(crate) read_only: bool,
114}
115
116impl McpAuth {
117 pub fn from_file(path: impl AsRef<Path>) -> Result<Self> {
119 let path = path.as_ref();
120 let contents = fs::read_to_string(path).map_err(|error| {
121 McpServerError::InvalidConfiguration(format!(
122 "failed to read MCP auth file {}: {error}",
123 path.display()
124 ))
125 })?;
126 Self::from_lines(
127 contents
128 .lines()
129 .enumerate()
130 .map(|(index, line)| (index + 1, line)),
131 )
132 }
133
134 fn from_lines<'a>(lines: impl IntoIterator<Item = (usize, &'a str)>) -> Result<Self> {
135 let mut credentials = Vec::new();
136 let mut usernames = HashSet::new();
137 for (line_number, line) in lines {
138 let mut fields = line.splitn(3, ':');
139 let access = fields.next().expect("split returns at least one field");
140 let Some(username) = fields.next() else {
141 return Err(invalid_auth_file_line(
142 line_number,
143 "must use the format <rw|ro>:<user>:<password>",
144 ));
145 };
146 let Some(password) = fields.next() else {
147 return Err(invalid_auth_file_line(
148 line_number,
149 "must use the format <rw|ro>:<user>:<password>",
150 ));
151 };
152 let read_only = match access {
153 "rw" => false,
154 "ro" => true,
155 _ => {
156 return Err(invalid_auth_file_line(
157 line_number,
158 "access must be `rw` or `ro`",
159 ));
160 }
161 };
162 if password.is_empty() {
163 return Err(invalid_auth_file_line(
164 line_number,
165 "password must not be empty",
166 ));
167 }
168 let username_digest: [u8; 32] = Sha256::digest(username.as_bytes()).into();
169 if !usernames.insert(username_digest) {
170 return Err(invalid_auth_file_line(
171 line_number,
172 "username is duplicated",
173 ));
174 }
175 credentials.push(McpCredential {
176 read_only,
177 username_digest,
178 password_digest: Sha256::digest(password.as_bytes()).into(),
179 });
180 }
181 if credentials.is_empty() {
182 return Err(McpServerError::InvalidConfiguration(
183 "MCP auth file must contain at least one credential".into(),
184 ));
185 }
186 Ok(Self(std::sync::Arc::new(McpAuthData { credentials })))
187 }
188
189 pub(crate) fn authenticate(&self, username: &str, password: &str) -> Option<AuthContext> {
190 let username_digest: [u8; 32] = Sha256::digest(username.as_bytes()).into();
191 let password_digest: [u8; 32] = Sha256::digest(password.as_bytes()).into();
192 let mut read_only_match = Choice::from(0);
193 let mut read_write_match = Choice::from(0);
194 for credential in &self.0.credentials {
195 let matched = credential.username_digest.ct_eq(&username_digest)
196 & credential.password_digest.ct_eq(&password_digest);
197 if credential.read_only {
198 read_only_match |= matched;
199 } else {
200 read_write_match |= matched;
201 }
202 }
203 if bool::from(read_only_match) {
204 Some(AuthContext { read_only: true })
205 } else if bool::from(read_write_match) {
206 Some(AuthContext { read_only: false })
207 } else {
208 None
209 }
210 }
211}
212
213fn invalid_auth_file_line(line_number: usize, reason: &str) -> McpServerError {
214 McpServerError::InvalidConfiguration(format!("MCP auth file line {line_number} {reason}"))
215}
216
217impl fmt::Debug for McpAuth {
218 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
219 formatter.write_str("McpAuth([REDACTED])")
220 }
221}
222
223#[derive(Clone, Debug, PartialEq, Eq)]
225pub struct McpServerConfig {
226 pub listen_addr: SocketAddr,
227 pub allowed_hosts: Vec<String>,
229 pub database_path: PathBuf,
230 pub auth: Option<McpAuth>,
231 pub tls: Option<McpTlsConfig>,
232 pub limits: McpLimits,
233}
234
235impl McpServerConfig {
236 pub(crate) fn validate(&self) -> Result<()> {
237 if self.database_path.as_os_str().is_empty() {
238 return Err(McpServerError::InvalidConfiguration(
239 "database_path must not be empty".into(),
240 ));
241 }
242 if self.allowed_hosts.iter().any(|host| host.trim().is_empty()) {
243 return Err(McpServerError::InvalidConfiguration(
244 "MCP allowed hosts must not contain empty entries".into(),
245 ));
246 }
247 if let Some(tls) = &self.tls {
248 if tls.certificate_file.as_os_str().is_empty() {
249 return Err(McpServerError::InvalidConfiguration(
250 "TLS certificate file must not be empty".into(),
251 ));
252 }
253 if tls
254 .ca_file
255 .as_ref()
256 .is_some_and(|path| path.as_os_str().is_empty())
257 {
258 return Err(McpServerError::InvalidConfiguration(
259 "TLS CA file must not be empty".into(),
260 ));
261 }
262 }
263 self.limits.validate()
264 }
265}
266
267#[cfg(test)]
268mod tests {
269 use super::*;
270
271 #[test]
272 fn auth_file_supports_empty_user_password_colons_and_permissions() {
273 let auth = McpAuth::from_lines([(1, "rw:alice:secret:part"), (2, "ro::token")]).unwrap();
274 assert_eq!(
275 auth.authenticate("alice", "secret:part"),
276 Some(AuthContext { read_only: false })
277 );
278 assert_eq!(
279 auth.authenticate("", "token"),
280 Some(AuthContext { read_only: true })
281 );
282 assert_eq!(auth.authenticate("alice", "wrong"), None);
283 assert_eq!(format!("{auth:?}"), "McpAuth([REDACTED])");
284 }
285
286 #[test]
287 fn auth_file_rejects_invalid_lines_and_duplicate_users() {
288 assert!(McpAuth::from_lines([]).is_err());
289 assert!(McpAuth::from_lines([(1, "rw:alice:")]).is_err());
290 assert!(McpAuth::from_lines([(1, "admin:alice:secret")]).is_err());
291 assert!(McpAuth::from_lines([(1, "rw:alice:a"), (2, "ro:alice:b")]).is_err());
292 }
293}