clync 0.4.1

Encrypted sync for Claude Code across machines
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
use anyhow::Result;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::io::{self, BufRead, Write};

use crate::cmd::short_uuid;
use crate::config::Config;
use crate::list::list_sessions;
use crate::mcp_help::help_text;
use crate::scanner::ScanFilter;

#[derive(Deserialize)]
struct JsonRpcRequest {
    #[allow(dead_code)]
    jsonrpc: String,
    id: Option<Value>,
    method: String,
    #[serde(default)]
    params: Value,
}

#[derive(Serialize)]
struct JsonRpcResponse {
    jsonrpc: String,
    id: Value,
    #[serde(skip_serializing_if = "Option::is_none")]
    result: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    error: Option<Value>,
}

pub fn run_mcp_server() -> Result<()> {
    let stdin = io::stdin();
    let mut stdout = io::stdout();

    for line in stdin.lock().lines() {
        let line = line?;
        if line.trim().is_empty() {
            continue;
        }

        let request: JsonRpcRequest = match serde_json::from_str(&line) {
            Ok(r) => r,
            Err(e) => {
                let resp = JsonRpcResponse {
                    jsonrpc: "2.0".into(),
                    id: Value::Null,
                    result: None,
                    error: Some(json!({"code": -32700, "message": format!("parse error: {e}")})),
                };
                write_response(&mut stdout, &resp)?;
                continue;
            }
        };

        if request.method.starts_with("notifications/") {
            continue;
        }
        let response = handle_request(&request);
        write_response(&mut stdout, &response)?;
    }

    Ok(())
}

fn write_response(stdout: &mut io::Stdout, resp: &JsonRpcResponse) -> Result<()> {
    let json = serde_json::to_string(resp)?;
    writeln!(stdout, "{json}")?;
    stdout.flush()?;
    Ok(())
}

fn handle_request(req: &JsonRpcRequest) -> JsonRpcResponse {
    let id = req.id.clone().unwrap_or(Value::Null);

    match req.method.as_str() {
        "initialize" => JsonRpcResponse {
            jsonrpc: "2.0".into(),
            id,
            result: Some(json!({
                "protocolVersion": "2024-11-05",
                "capabilities": {
                    "tools": {}
                },
                "serverInfo": {
                    "name": "clync",
                    "version": env!("CARGO_PKG_VERSION")
                }
            })),
            error: None,
        },
        "tools/list" => JsonRpcResponse {
            jsonrpc: "2.0".into(),
            id,
            result: Some(json!({
                "tools": tool_definitions()
            })),
            error: None,
        },
        "tools/call" => {
            let tool_name = req
                .params
                .get("name")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            let args = req.params.get("arguments").cloned().unwrap_or(json!({}));
            match call_tool(tool_name, &args) {
                Ok(result) => JsonRpcResponse {
                    jsonrpc: "2.0".into(),
                    id,
                    result: Some(json!({
                        "content": [{"type": "text", "text": result}]
                    })),
                    error: None,
                },
                Err(e) => JsonRpcResponse {
                    jsonrpc: "2.0".into(),
                    id,
                    result: Some(json!({
                        "content": [{"type": "text", "text": format!("error: {e}")}],
                        "isError": true
                    })),
                    error: None,
                },
            }
        }
        _ => JsonRpcResponse {
            jsonrpc: "2.0".into(),
            id,
            result: None,
            error: Some(
                json!({"code": -32601, "message": format!("unknown method: {}", req.method)}),
            ),
        },
    }
}

fn tool_definitions() -> Value {
    json!([
        {
            "name": "list_sessions",
            "description": "List Claude Code sessions with optional search. Returns UUID, project, message count, first message preview, size, and modification time for each session.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "Search sessions by project name, UUID, or first message content"
                    },
                    "max_age_days": {
                        "type": "integer",
                        "description": "Only show sessions modified within N days"
                    },
                    "limit": {
                        "type": "integer",
                        "description": "Max number of results (default: 20)"
                    }
                }
            }
        },
        {
            "name": "session_detail",
            "description": "Get details for a specific session by UUID (or prefix). Returns message count, participants, timestamps, project, and the last N messages.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "uuid": {
                        "type": "string",
                        "description": "Full or partial UUID of the session"
                    },
                    "tail": {
                        "type": "integer",
                        "description": "Number of recent messages to include (default: 10)"
                    }
                },
                "required": ["uuid"]
            }
        },
        {
            "name": "sync_status",
            "description": "Show what differs between local sessions and the encrypted sync repo. Lists sessions that are local-only, remote-only, diverged, or in sync.",
            "inputSchema": {
                "type": "object",
                "properties": {}
            }
        },
        {
            "name": "sync_push",
            "description": "Encrypt and push changed sessions and extras (memories, settings, etc.) to the sync store.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "sync": {
                        "type": "boolean",
                        "description": "Also sync to remote (git push, S3 upload, etc.). Default: auto_push config value."
                    }
                }
            }
        },
        {
            "name": "sync_pull",
            "description": "Pull and decrypt sessions from sync store, smart-merging any diverged sessions using UUID-based conversation trees.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "sync": {
                        "type": "boolean",
                        "description": "Also sync from remote first (git pull, S3 download, etc.). Default: auto_push config value."
                    }
                }
            }
        },
        {
            "name": "sync_log",
            "description": "Show recent sync operations with machine name, timestamps, and what was synced/merged.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "limit": {
                        "type": "integer",
                        "description": "Number of recent entries to show (default: 10)"
                    }
                }
            }
        },
        {
            "name": "config_show",
            "description": "Show current clync configuration: sync repo path, encryption method, and which targets (sessions, memories, settings, etc.) are enabled.",
            "inputSchema": {
                "type": "object",
                "properties": {}
            }
        },
        {
            "name": "help",
            "description": "Show available clync commands and usage information. Call with a specific topic for detailed help.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "topic": {
                        "type": "string",
                        "description": "Help topic: 'setup', 'sync', 'list', 'mcp', 'config', or 'all'"
                    }
                }
            }
        }
    ])
}

fn call_tool(name: &str, args: &Value) -> Result<String> {
    match name {
        "list_sessions" => {
            let config = Config::load()?;
            let query = args.get("query").and_then(|v| v.as_str());
            let max_age = args.get("max_age_days").and_then(|v| v.as_u64());
            let limit = args.get("limit").and_then(|v| v.as_u64()).unwrap_or(20) as usize;

            let filter = ScanFilter {
                max_age_days: max_age,
                max_file_size: None,
            };

            let sessions = list_sessions(&config.claude_projects_dir(), query, &filter)?;
            let limited: Vec<_> = sessions.into_iter().take(limit).collect();

            Ok(serde_json::to_string_pretty(&limited)?)
        }
        "session_detail" => {
            let config = Config::load()?;
            let uuid_prefix = args
                .get("uuid")
                .and_then(|v| v.as_str())
                .filter(|s| !s.is_empty())
                .ok_or_else(|| anyhow::anyhow!("uuid is required"))?;
            let tail = args.get("tail").and_then(|v| v.as_u64()).unwrap_or(10) as usize;

            let filter = ScanFilter::default();
            let sessions = crate::scanner::scan_sessions(&config.claude_projects_dir(), &filter)?;

            let session = sessions
                .iter()
                .find(|s| s.uuid.starts_with(uuid_prefix))
                .ok_or_else(|| anyhow::anyhow!("no session matching '{uuid_prefix}'"))?;

            let entries = crate::parser::parse_jsonl_file(&session.jsonl_path)?;

            let user_msgs = entries
                .iter()
                .filter(|e| e.entry_type.as_deref() == Some("user"))
                .count();
            let assistant_msgs = entries
                .iter()
                .filter(|e| e.entry_type.as_deref() == Some("assistant"))
                .count();

            let first_ts = entries.first().map(|e| e.timestamp_millis()).unwrap_or(0);
            let last_ts = entries.last().map(|e| e.timestamp_millis()).unwrap_or(0);

            let recent: Vec<Value> = entries
                .iter()
                .filter(|e| matches!(e.entry_type.as_deref(), Some("user") | Some("assistant")))
                .rev()
                .take(tail)
                .collect::<Vec<_>>()
                .into_iter()
                .rev()
                .map(|e| {
                    let role = e.entry_type.as_deref().unwrap_or("unknown");
                    let content = e
                        .extra
                        .get("message")
                        .and_then(|m| m.get("content"))
                        .and_then(|c| {
                            c.as_str().map(|s| s.to_string()).or_else(|| {
                                c.as_array().map(|arr| {
                                    arr.iter()
                                        .filter_map(|item| {
                                            item.get("text").and_then(|t| t.as_str())
                                        })
                                        .collect::<Vec<_>>()
                                        .join("\n")
                                })
                            })
                        })
                        .unwrap_or_default();
                    let truncated = truncate_str(&content, 500);
                    json!({"role": role, "content": truncated})
                })
                .collect();

            let detail = json!({
                "uuid": session.uuid,
                "project": session.entry.project_path,
                "size_bytes": session.entry.size,
                "user_messages": user_msgs,
                "assistant_messages": assistant_msgs,
                "total_entries": entries.len(),
                "first_timestamp": first_ts,
                "last_timestamp": last_ts,
                "recent_messages": recent
            });

            Ok(serde_json::to_string_pretty(&detail)?)
        }
        "sync_status" => {
            let config = Config::load()?;
            let cipher = crate::crypto::Cipher::from_config(&config.encryption)?;
            let store = crate::store::create_store(&config)?;
            let filter = ScanFilter::default();
            let result = crate::sync::status(&config, &cipher, &filter, store.as_ref())?;

            let mut output = String::new();
            if result.local_only.is_empty()
                && result.remote_only.is_empty()
                && result.diverged.is_empty()
            {
                output.push_str(&format!("all {} sessions in sync", result.in_sync));
            } else {
                for s in &result.local_only {
                    output.push_str(&format!(
                        "+ {} [{}] (local only)\n",
                        short_uuid(&s.uuid),
                        s.project
                    ));
                }
                for s in &result.remote_only {
                    output.push_str(&format!(
                        "- {} [{}] (remote only)\n",
                        short_uuid(&s.uuid),
                        s.project
                    ));
                }
                for s in &result.diverged {
                    output.push_str(&format!(
                        "~ {} [{}] (diverged)\n",
                        short_uuid(&s.uuid),
                        s.project
                    ));
                }
                if result.in_sync > 0 {
                    output.push_str(&format!("in sync: {}", result.in_sync));
                }
            }
            Ok(output)
        }
        "sync_push" => {
            let config = Config::load()?;
            let do_sync = args
                .get("sync")
                .and_then(|v| v.as_bool())
                .unwrap_or(config.sync.storage.auto_push());
            let r = crate::cmd::do_push(do_sync)?;
            Ok(format!(
                "pushed {} sessions ({} unchanged), {} extras, {} memories",
                r.sessions, r.skipped, r.extras, r.memories
            ))
        }
        "sync_pull" => {
            let config = Config::load()?;
            let do_sync = args
                .get("sync")
                .and_then(|v| v.as_bool())
                .unwrap_or(config.sync.storage.auto_push());
            let r = crate::cmd::do_pull(do_sync)?;
            let mut msg = format!(
                "pulled {} new, {} merged, {} unchanged",
                r.pulled, r.merged, r.skipped
            );
            if r.archived > 0 {
                msg.push_str(&format!(", {} archived", r.archived));
            }
            msg.push_str(&format!(", {} extras, {} memories", r.extras, r.memories));
            Ok(msg)
        }
        "sync_log" => {
            let config = Config::load()?;
            let limit = args.get("limit").and_then(|v| v.as_u64()).unwrap_or(10) as usize;
            let store_path = config.storage_path().ok_or_else(|| {
                anyhow::anyhow!("log requires local storage (not available with S3 backend)")
            })?;
            let entries = crate::synclog::read_recent(store_path, limit)?;
            Ok(serde_json::to_string_pretty(&entries)?)
        }
        "config_show" => tool_config_show(),
        "help" => {
            let topic = args.get("topic").and_then(|v| v.as_str()).unwrap_or("all");
            Ok(help_text(topic))
        }
        _ => anyhow::bail!("unknown tool: {name}"),
    }
}

fn tool_config_show() -> Result<String> {
    let config = Config::load()?;
    let enc_method = match &config.encryption {
        crate::config::EncryptionConfig::KeyFile { path } => {
            format!("key_file ({})", path.display())
        }
        crate::config::EncryptionConfig::Passphrase { env_var } => {
            format!("passphrase (${env_var})")
        }
        crate::config::EncryptionConfig::OnePassword { reference } => {
            format!("1password ({reference})")
        }
        crate::config::EncryptionConfig::Bitwarden { item_id, .. } => {
            format!("bitwarden ({item_id})")
        }
        crate::config::EncryptionConfig::Pass { entry } => {
            format!("pass ({entry})")
        }
        crate::config::EncryptionConfig::None => "none (plain text)".into(),
    };
    let storage_desc = match &config.sync.storage {
        crate::config::StorageConfig::Git {
            path, auto_push, ..
        } => format!("git ({}), auto_push: {auto_push}", path.display()),
        crate::config::StorageConfig::Folder { path } => {
            format!("folder ({})", path.display())
        }
        #[cfg(feature = "s3")]
        crate::config::StorageConfig::S3 { bucket, region, .. } => {
            format!("s3 ({bucket}, {region})")
        }
    };
    let t = &config.targets;
    Ok(format!(
        "storage: {storage_desc}\nclaude dir: {}\nencryption: {}\ncompanion dirs: {}\n\ntargets:\n  sessions: {}\n  memories: {}\n  settings: {}\n  commands: {}\n  skills: {}\n  global CLAUDE.md: {}",
        config.sync.claude_dir.display(),
        enc_method,
        config.sync.include_companion_dirs,
        t.sessions,
        t.memories,
        t.settings,
        t.commands,
        t.skills,
        t.global_claude_md
    ))
}

fn truncate_str(s: &str, max: usize) -> String {
    if s.len() <= max {
        return s.to_string();
    }
    let mut end = max.saturating_sub(3);
    while end > 0 && !s.is_char_boundary(end) {
        end -= 1;
    }
    format!("{}...", &s[..end])
}

#[cfg(test)]
#[path = "mcp_tests.rs"]
mod tests;