optimization-runner 0.6.0

Local runner (optimization-run) and MCP server (optimization-mcp) for versioned optimization jobs on one CPU budget
Documentation
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! Experimental out-of-band uploads over MCP. A transfer endpoint publishes
//! a staged file for a grant. The MCP retry verifies and publishes the input.
use super::{INVALID_PARAMS, MISSING_CAPABILITY, Reply, Server, inputs, tasks, tools};
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use hmac::{Hmac, Mac};
use optimization_job_api::{
    MAX_INPUT_BYTES,
    storage::{lock, write_atomic_json},
};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{Value, json};
use sha2::Sha256;
use std::{
    fs::{self, File},
    io::{self, Read, Write},
    net::{Ipv4Addr, Ipv6Addr},
    os::unix::fs::{DirBuilderExt, PermissionsExt},
    path::{Path, PathBuf},
    time::{SystemTime, UNIX_EPOCH},
};

pub(super) const EXTENSION: &str = "io.modelcontextprotocol/files";
pub(super) const TOOL: &str = "upload_input";
const TARGET_SECONDS: u64 = 300;
const STATE_SECONDS: u64 = 900;

pub(super) struct Uploads {
    /// `scheme://host[:port]`, without a trailing slash.
    origin: String,
    staging: PathBuf,
    key: [u8; 32],
}

#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct Arguments {
    file: Input,
}

#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct Input {
    id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    name: Option<String>,
    mime_type: String,
    #[serde(deserialize_with = "size")]
    size: u64,
    digest: Digest,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    data: Option<String>,
}

#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct Digest {
    algorithm: String,
    value: String,
}

#[derive(Deserialize, Serialize)]
struct Grant {
    size: u64,
    target_expires_at: u64,
    expires_at: u64,
}

fn size<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u64, D::Error> {
    let number = serde_json::Number::deserialize(deserializer)?;
    // JSON Schema regards 12 and 12.0 as equal. Normalizing the forms also
    // lets an equivalent request verify the same requestState.
    number
        .as_u64()
        .or_else(|| {
            number
                .as_f64()
                .filter(|n| *n >= 0.0 && *n <= MAX_INPUT_BYTES as f64 && n.fract() == 0.0)
                .map(|n| n as u64)
        })
        .ok_or_else(|| serde::de::Error::custom("size must be a non-negative integer"))
}

fn now() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

fn bad_config(message: &str) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidInput, message)
}

/// The transfer origin in normal form, or `None` unless `endpoint` is
/// `https://host[:port]`, or `http://` with a loopback host, and nothing
/// else: no user information, path, query or fragment. A host is an ASCII
/// DNS name, an IPv4 address or a bracketed IPv6 address.
fn origin(endpoint: &str) -> Option<String> {
    let (scheme, authority) = endpoint
        .strip_suffix('/')
        .unwrap_or(endpoint)
        .split_once("://")?;
    let (host, port, loopback) = if let Some(rest) = authority.strip_prefix('[') {
        let (address, port) = rest.split_once(']')?;
        let address: Ipv6Addr = address.parse().ok()?;
        let port = match port {
            "" => None,
            port => Some(port.strip_prefix(':')?),
        };
        (format!("[{address}]"), port, address.is_loopback())
    } else {
        let (host, port) = match authority.rsplit_once(':') {
            Some((host, port)) => (host, Some(port)),
            None => (authority, None),
        };
        let label = |label: &str| {
            (1..=63).contains(&label.len())
                && label
                    .bytes()
                    .all(|b| b.is_ascii_alphanumeric() || b == b'-')
                && !label.starts_with('-')
                && !label.ends_with('-')
        };
        if host.len() > 253 || !host.split('.').all(label) {
            return None;
        }
        let host = host.to_ascii_lowercase();
        let loopback = host == "localhost"
            || host
                .parse::<Ipv4Addr>()
                .is_ok_and(|address| address.is_loopback());
        (host, port, loopback)
    };
    if let Some(port) = port {
        let digits = (1..=5).contains(&port.len()) && port.bytes().all(|b| b.is_ascii_digit());
        if !digits || port.parse::<u16>().ok()? == 0 {
            return None;
        }
    }
    if !(scheme == "https" || (scheme == "http" && loopback)) {
        return None;
    }
    Some(match port {
        Some(port) => format!("{scheme}://{host}:{port}"),
        None => format!("{scheme}://{host}"),
    })
}

fn valid_token(token: &str) -> bool {
    token.len() == 32
        && token
            .bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

fn load_key(directory: &Path) -> io::Result<[u8; 32]> {
    let path = directory.join("files.key");
    let mut key = [0u8; 32];
    let _guard = lock(&directory.join("files.lock"))?;
    match fs::symlink_metadata(&path) {
        Ok(meta) => {
            if !meta.is_file() || meta.permissions().mode() & 0o077 != 0 || meta.len() != 32 {
                return Err(bad_config(
                    "the Files key must be a private 32-byte regular file",
                ));
            }
            File::open(&path)?.read_exact(&mut key)?;
        }
        Err(error) if error.kind() == io::ErrorKind::NotFound => {
            File::open("/dev/urandom")?.read_exact(&mut key)?;
            let mut file = tempfile::NamedTempFile::new_in(directory)?;
            file.write_all(&key)?;
            file.as_file().sync_all()?;
            file.persist_noclobber(path).map_err(|e| e.error)?;
            File::open(directory)?.sync_all()?;
        }
        Err(error) => return Err(error),
    }
    Ok(key)
}

impl Uploads {
    pub fn new(root: &Path, endpoint: &str) -> io::Result<Self> {
        let origin = origin(endpoint).ok_or_else(|| {
            bad_config("Files endpoint must be an HTTPS origin or an HTTP loopback origin")
        })?;
        let directory = root.join("mcp");
        fs::create_dir_all(&directory)?;
        let staging = directory.join("uploads");
        match fs::DirBuilder::new().mode(0o700).create(&staging) {
            Ok(()) => (),
            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => (),
            Err(error) => return Err(error),
        }
        let metadata = fs::symlink_metadata(&staging)?;
        if !metadata.is_dir() || metadata.permissions().mode() & 0o077 != 0 {
            return Err(bad_config("the Files staging directory must be private"));
        }
        let uploads = Self {
            origin,
            staging,
            key: load_key(&directory)?,
        };
        uploads.clean();
        Ok(uploads)
    }

    fn mac(&self, token: &str, expires_at: u64, args: &Arguments) -> Hmac<Sha256> {
        let mut mac = Hmac::new_from_slice(&self.key).expect("32-byte HMAC key");
        // Bind the signed state to the complete validated arguments and target.
        let bound = serde_json::to_vec(&(TOOL, &self.origin, token, expires_at, args))
            .expect("serializable upload state");
        mac.update(&bound);
        mac
    }

    fn verified_token<'a>(&self, state: &'a str, args: &Arguments) -> Option<&'a str> {
        let mut parts = state.split('.');
        let token = parts.next()?;
        let expires_at: u64 = parts.next()?.parse().ok()?;
        let signature = parts.next()?;
        if state.len() > 110 || parts.next().is_some() || !valid_token(token) || now() >= expires_at
        {
            return None;
        }
        let signature = URL_SAFE_NO_PAD.decode(signature).ok()?;
        self.mac(token, expires_at, args)
            .verify_slice(&signature)
            .ok()?;
        Some(token)
    }

    fn grant(&self, args: &Arguments) -> io::Result<Value> {
        let now = now();
        let grant = Grant {
            size: args.file.size,
            target_expires_at: now + TARGET_SECONDS,
            expires_at: now + STATE_SECONDS,
        };
        // Staged files of expired grants would otherwise stay until the
        // next server start.
        self.clean();
        let token = tools::task_token()?;
        let target = format!("{}/uploads/{token}", self.origin);
        let signature = URL_SAFE_NO_PAD.encode(
            self.mac(&token, grant.expires_at, args)
                .finalize()
                .into_bytes(),
        );
        write_atomic_json(&self.staging.join(format!("{token}.json")), &grant)?;
        Ok(json!({
            "resultType": "upload_required",
            "uploads": [{
                "fileId": args.file.id, "url": target, "method": "PUT",
                "credentials": "omit", "expiresAt": tasks::iso(grant.target_expires_at as f64),
            }],
            "requestState": format!("{token}.{}.{signature}", grant.expires_at),
        }))
    }

    fn clean(&self) {
        let now = now();
        for entry in fs::read_dir(&self.staging).into_iter().flatten().flatten() {
            let path = entry.path();
            if path.extension().and_then(|ext| ext.to_str()) != Some("json")
                || !path
                    .file_stem()
                    .and_then(|stem| stem.to_str())
                    .is_some_and(valid_token)
                || !entry.file_type().is_ok_and(|kind| kind.is_file())
            {
                continue;
            }
            let grant = fs::read(&path)
                .ok()
                .and_then(|bytes| serde_json::from_slice::<Grant>(&bytes).ok());
            if grant.is_some_and(|grant| grant.expires_at <= now) {
                let _ = fs::remove_file(path.with_extension("upload"));
                let _ = fs::remove_file(path);
            }
        }
    }
}

fn bad_state() -> Reply {
    Reply::Err(
        INVALID_PARAMS,
        "invalid, expired or mismatched upload requestState".into(),
        None,
    )
}

fn completion(result: Result<Value, tools::Fail>) -> Reply {
    match result {
        Ok(value) => Reply::Ok(tools::tool_result(value, false)),
        Err(tools::Fail::Tool(error)) => Reply::Ok(tools::tool_result(error.value(), true)),
        Err(tools::Fail::Cancelled) => Reply::Silent,
    }
}

pub(super) fn call(
    server: &Server,
    uploads: &Uploads,
    arguments: Value,
    state: Option<&Value>,
    supported: bool,
) -> Reply {
    let invalid_arguments = || {
        completion(Err(tools::fail(
            "invalid_arguments",
            "expected valid file metadata, up to 64 MiB, with a SHA-256 digest and no inline data",
        )))
    };
    // A null optional member is invalid on the wire. Reject it before Serde
    // maps null and absent to the same value for Option.
    if arguments["file"].get("name").is_some_and(Value::is_null)
        || arguments["file"].get("data").is_some_and(Value::is_null)
    {
        return if state.is_some() {
            bad_state()
        } else {
            invalid_arguments()
        };
    }
    let Ok(args) = serde_json::from_value::<Arguments>(arguments) else {
        return if state.is_some() {
            bad_state()
        } else {
            invalid_arguments()
        };
    };
    let file = &args.file;
    if !(1..=128).contains(&file.id.chars().count())
        || file.mime_type.is_empty()
        || file.size > MAX_INPUT_BYTES
        || file.digest.algorithm != "sha-256"
        || file
            .data
            .as_ref()
            .is_some_and(|s| file.size != 0 || !s.is_empty())
    {
        return if state.is_some() {
            bad_state()
        } else {
            invalid_arguments()
        };
    }
    let Ok(hash) = URL_SAFE_NO_PAD.decode(&file.digest.value) else {
        return if state.is_some() {
            bad_state()
        } else {
            invalid_arguments()
        };
    };
    if hash.len() != 32 {
        return if state.is_some() {
            bad_state()
        } else {
            invalid_arguments()
        };
    }
    let mut sha256 = String::with_capacity(64);
    for byte in hash {
        use std::fmt::Write as _;
        write!(sha256, "{byte:02x}").expect("writing to a string");
    }
    let token = match state {
        Some(value) => match value
            .as_str()
            .and_then(|state| uploads.verified_token(state, &args))
        {
            Some(token) => Some(token),
            None => return bad_state(),
        },
        None => None,
    };
    if file.size == 0 {
        return completion(inputs::store_empty(server, &sha256));
    }
    if !supported {
        return Reply::Err(
            MISSING_CAPABILITY,
            "Missing required client capability".into(),
            Some(json!({"requiredCapabilities":{"extensions":{EXTENSION:{"upload":{}}}}})),
        );
    }
    if let Some(token) = token {
        let staged = uploads.staging.join(format!("{token}.upload"));
        return completion(inputs::store_upload(server, &staged, &sha256, file.size));
    }
    if let Err(error) = inputs::check_upload(server, &sha256, file.size) {
        return completion(Err(error));
    }
    match uploads.grant(&args) {
        Ok(result) => Reply::Ok(result),
        Err(_) => completion(Err(tools::fail(
            "runner_error",
            "could not issue an upload grant",
        ))),
    }
}

pub(super) fn definition() -> Value {
    json!({
        "name": TOOL,
        "title": "Upload an input file",
        "description": "Store a job input through the experimental Files extension. Pass a SHA-256 digest; use the returned input_dir when you validate and submit the job.",
        "annotations":{"readOnlyHint":false,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false},
        "inputSchema":{
            "type":"object","required":["file"],"additionalProperties":false,
            "properties":{"file":{
                "type":"object","required":["id","mimeType","size","digest"],"additionalProperties":false,
                "x-mcp-file":{"maxSize":MAX_INPUT_BYTES},
                "properties":{
                    "id":{"type":"string","minLength":1,"maxLength":128},
                    "name":{"type":"string"},
                    "mimeType":{"type":"string","minLength":1},
                    "size":{"type":"integer","minimum":0,"maximum":MAX_INPUT_BYTES},
                    "digest":{"type":"object","required":["algorithm","value"],"additionalProperties":false,
                        "properties":{"algorithm":{"const":"sha-256"},"value":{"type":"string","pattern":"^[A-Za-z0-9_-]{43}$"}}},
                    "data":{"const":""},
                },
            }},
        },
        "outputSchema": tools::output_schema(TOOL).expect("upload output schema"),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn only_a_bare_https_or_loopback_http_origin_is_accepted() {
        for (endpoint, normal) in [
            ("https://files.example.org", "https://files.example.org"),
            (
                "https://Files.Example.org:8443/",
                "https://files.example.org:8443",
            ),
            ("https://203.0.113.7", "https://203.0.113.7"),
            ("https://[2001:db8::1]:8443", "https://[2001:db8::1]:8443"),
            ("http://127.0.0.1:8000", "http://127.0.0.1:8000"),
            ("http://localhost:9/", "http://localhost:9"),
            ("http://[::1]:8000", "http://[::1]:8000"),
        ] {
            assert_eq!(origin(endpoint).as_deref(), Some(normal), "{endpoint}");
        }
        for endpoint in [
            "http://files.example.org",
            "http://192.0.2.1:8000",
            "http://[2001:db8::1]",
            "HTTPS://files.example.org",
            "ftp://files.example.org",
            "files.example.org",
            "https://",
            "https:///uploads",
            "https://user@files.example.org",
            "https://user:secret@files.example.org",
            "https://files.example.org/uploads",
            "https://files.example.org//",
            "https://files.example.org?x=1",
            "https://files.example.org#x",
            "https://files.example.org:",
            "https://files.example.org:0",
            "https://files.example.org:65536",
            "https://files.example.org:+80",
            "https://files.example.org:80:80",
            "https://-files.example.org",
            "https://files..example.org",
            "https://files_1.example.org",
            "https://[::1",
            "https://[::1]8443",
            "https://[not-an-address]",
            "https://files.example.org /",
        ] {
            assert_eq!(origin(endpoint), None, "{endpoint}");
        }
    }

    #[test]
    fn a_correctly_signed_state_cannot_be_used_after_expiry() {
        let root = tempfile::tempdir().unwrap();
        let uploads = Uploads::new(root.path(), "http://127.0.0.1:8000").unwrap();
        let arguments: Arguments = serde_json::from_value(json!({
            "file":{"id":"model","mimeType":"application/octet-stream","size":1,
                "digest":{"algorithm":"sha-256","value":"ignored for this signature test"}}
        }))
        .unwrap();
        let token = tools::task_token().unwrap();
        let expiry = now().saturating_sub(1);
        let signed = URL_SAFE_NO_PAD.encode(
            uploads
                .mac(&token, expiry, &arguments)
                .finalize()
                .into_bytes(),
        );
        assert_eq!(
            uploads.verified_token(&format!("{token}.{expiry}.{signed}"), &arguments),
            None
        );
    }
}