mcp-compressor-core 0.23.0

Internal Rust core for mcp-compressor. Prefer the public mcp-compressor crate.
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
//! `PythonGenerator` — generates an importable Python module.
//!
//! Each upstream tool becomes a typed async function that calls `POST /exec`
//! on the local tool proxy.  The generated module:
//!
//! - Is named `<cli_name>.py`.
//! - Imports `httpx` for HTTP calls.
//! - Contains `_BRIDGE` and `_TOKEN` module-level constants.
//! - Has one `def <tool_name>(...)` function per upstream tool with:
//!   - Required params as positional; optional as keyword-only with `None` default.
//!   - A docstring taken from the tool's description.
//!   - Return type annotation of `str`.
//! - Contains a `# generated by mcp-compressor — do not edit manually` header.

use crate::client_gen::generator::{ClientGenerator, GeneratedArtifact, GeneratorConfig};
use crate::Error;

pub struct PythonGenerator;

impl ClientGenerator for PythonGenerator {
    fn render(&self, config: &GeneratorConfig) -> Result<Vec<GeneratedArtifact>, Error> {
        Ok(vec![GeneratedArtifact::new(
            format!("{}.py", config.cli_name),
            render_python_module(config),
        )])
    }
}

fn render_python_module(config: &GeneratorConfig) -> String {
    let mut module = format!(
        r#"# generated by mcp-compressor — do not edit manually
import json
import urllib.error
import urllib.request

_BRIDGE = {bridge:?}
_TOKEN = {token:?}
_SESSION_PID = {pid}
_HEADERS = {{"Content-Type": "application/json", "Authorization": f"Bearer {{_TOKEN}}"}}


def _exec(tool: str, tool_input: dict) -> str:
    payload = json.dumps({{"tool": tool, "input": tool_input}}).encode()
    request = urllib.request.Request(_BRIDGE + "/exec", data=payload, headers=_HEADERS, method="POST")
    try:
        with urllib.request.urlopen(request) as response:
            return response.read().decode()
    except urllib.error.HTTPError as exc:
        message = exc.read().decode(errors="replace") or exc.reason
        raise RuntimeError(f"mcp-compressor proxy returned HTTP {{exc.code}}: {{message}}") from None
    except urllib.error.URLError as exc:
        raise RuntimeError(
            "mcp-compressor proxy is not running; restart the mcp-compressor process and try again. "
            f"details: {{exc.reason}}"
        ) from None
"#,
        bridge = config.bridge_url,
        token = config.token,
        pid = config.session_pid,
    );

    for tool in &config.tools {
        let params = python_params(tool);
        let input = python_input_dict(tool);
        let docstring = tool.description.as_deref().unwrap_or("");
        let function_name = to_snake_case(&tool.name);
        module.push_str(&format!(
            r#"

def {name}({params}) -> str:
    """{docstring}"""
    return _exec({tool_name:?}, {input})
"#,
            name = function_name,
            params = params,
            docstring = docstring.replace("\"\"\"", "\\\"\\\"\\\""),
            tool_name = tool.name,
            input = input,
        ));
    }

    module
}

fn python_params(tool: &crate::compression::engine::Tool) -> String {
    ordered_param_names(tool)
        .into_iter()
        .map(|(name, required)| {
            let param_name = to_snake_case(&name);
            if required {
                param_name
            } else {
                format!("{param_name}=None")
            }
        })
        .collect::<Vec<_>>()
        .join(", ")
}

fn python_input_dict(tool: &crate::compression::engine::Tool) -> String {
    let pairs = tool
        .param_names()
        .into_iter()
        .map(|name| format!("{name:?}: {}", to_snake_case(&name)))
        .collect::<Vec<_>>()
        .join(", ");
    format!("{{{pairs}}}")
}

fn to_snake_case(name: &str) -> String {
    let mut output = String::new();
    let mut previous_was_separator = false;
    for (index, ch) in name.chars().enumerate() {
        if ch == '-' || ch == ' ' {
            if !output.is_empty() && !previous_was_separator {
                output.push('_');
            }
            previous_was_separator = true;
        } else if ch.is_ascii_uppercase() {
            if index > 0 && !previous_was_separator {
                output.push('_');
            }
            output.push(ch.to_ascii_lowercase());
            previous_was_separator = false;
        } else {
            output.push(ch);
            previous_was_separator = ch == '_';
        }
    }
    output
}

fn ordered_param_names(tool: &crate::compression::engine::Tool) -> Vec<(String, bool)> {
    let required = required_params(tool);
    let mut params = tool
        .param_names()
        .into_iter()
        .map(|name| {
            let is_required = required.contains(&name);
            (name, is_required)
        })
        .collect::<Vec<_>>();
    params.sort_by_key(|(_name, is_required)| !*is_required);
    params
}

fn required_params(tool: &crate::compression::engine::Tool) -> Vec<String> {
    tool.input_schema
        .get("required")
        .and_then(serde_json::Value::as_array)
        .map(|values| values.iter().filter_map(serde_json::Value::as_str).map(ToString::to_string).collect())
        .unwrap_or_default()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::client_gen::generator::test_helpers::{make_config, make_config_multiword_tool};
    use crate::client_gen::{ClientGenerator, GeneratorConfig};
    use crate::compression::engine::Tool;
    use std::ffi::OsStr;
    use std::fs;

    // ------------------------------------------------------------------
    // File creation
    // ------------------------------------------------------------------

    /// generate() returns exactly one path (the .py module).
    #[test]
    fn generate_returns_one_file() {
        let dir = tempfile::tempdir().unwrap();
        let config = make_config(dir.path());
        let paths = PythonGenerator.generate(&config).unwrap();
        assert_eq!(paths.len(), 1, "expected exactly one generated file");
    }

    /// The generated file has a `.py` extension.
    #[test]
    fn generated_file_has_py_extension() {
        let dir = tempfile::tempdir().unwrap();
        let config = make_config(dir.path());
        let paths = PythonGenerator.generate(&config).unwrap();
        assert_eq!(
            paths[0].extension(),
            Some(OsStr::new("py")),
            "expected .py extension",
        );
    }

    /// The generated file is named `<cli_name>.py`.
    #[test]
    fn generated_file_named_after_cli_name() {
        let dir = tempfile::tempdir().unwrap();
        let config = make_config(dir.path());
        let paths = PythonGenerator.generate(&config).unwrap();
        assert_eq!(paths[0].file_name(), Some(OsStr::new("my-server.py")));
    }

    /// The generated file exists on disk.
    #[test]
    fn generated_file_exists() {
        let dir = tempfile::tempdir().unwrap();
        let config = make_config(dir.path());
        let paths = PythonGenerator.generate(&config).unwrap();
        assert!(paths[0].exists());
    }

    // ------------------------------------------------------------------
    // File content — header
    // ------------------------------------------------------------------

    /// The file starts with the "do not edit manually" comment.
    #[test]
    fn file_has_do_not_edit_header() {
        let dir = tempfile::tempdir().unwrap();
        let config = make_config(dir.path());
        let paths = PythonGenerator.generate(&config).unwrap();
        let content = fs::read_to_string(&paths[0]).unwrap();
        assert!(
            content.contains("do not edit"),
            "expected 'do not edit' header, got: {content:?}",
        );
    }

    // ------------------------------------------------------------------
    // File content — constants
    // ------------------------------------------------------------------

    /// The file contains `_TOKEN` with the session token value.
    #[test]
    fn file_contains_token_constant() {
        let dir = tempfile::tempdir().unwrap();
        let config = make_config(dir.path());
        let paths = PythonGenerator.generate(&config).unwrap();
        let content = fs::read_to_string(&paths[0]).unwrap();
        assert!(content.contains(&config.token), "token not found in file");
        assert!(content.contains("_TOKEN"), "_TOKEN constant not found");
    }

    /// The file contains `_BRIDGE` with the proxy URL.
    #[test]
    fn file_contains_bridge_constant() {
        let dir = tempfile::tempdir().unwrap();
        let config = make_config(dir.path());
        let paths = PythonGenerator.generate(&config).unwrap();
        let content = fs::read_to_string(&paths[0]).unwrap();
        assert!(content.contains(&config.bridge_url), "bridge URL not found in file");
        assert!(content.contains("_BRIDGE"), "_BRIDGE constant not found");
    }

    // ------------------------------------------------------------------
    // File content — function definitions
    // ------------------------------------------------------------------

    /// Each upstream tool produces a `def <name>(...)` function.
    #[test]
    fn file_contains_function_per_tool() {
        let dir = tempfile::tempdir().unwrap();
        let config = make_config(dir.path());
        let paths = PythonGenerator.generate(&config).unwrap();
        let content = fs::read_to_string(&paths[0]).unwrap();
        assert!(content.contains("def fetch("), "'def fetch(' not found");
        assert!(content.contains("def search("), "'def search(' not found");
    }

    /// Each function contains a docstring derived from the tool's description.
    #[test]
    fn function_has_docstring_from_description() {
        let dir = tempfile::tempdir().unwrap();
        let config = make_config(dir.path());
        let paths = PythonGenerator.generate(&config).unwrap();
        let content = fs::read_to_string(&paths[0]).unwrap();
        assert!(content.contains("Fetch a URL"), "tool description not found in docstring");
        assert!(content.contains("Search the web"), "tool description not found in docstring");
    }

    /// Function parameters match the tool's schema properties.
    #[test]
    fn function_params_match_schema() {
        let dir = tempfile::tempdir().unwrap();
        let config = make_config(dir.path());
        let paths = PythonGenerator.generate(&config).unwrap();
        let content = fs::read_to_string(&paths[0]).unwrap();
        // fetch() has "url" param; search() has "query" param
        assert!(content.contains("url"), "'url' param not found");
        assert!(content.contains("query"), "'query' param not found");
    }

    /// Functions have a `-> str` return type annotation.
    #[test]
    fn function_has_str_return_annotation() {
        let dir = tempfile::tempdir().unwrap();
        let config = make_config(dir.path());
        let paths = PythonGenerator.generate(&config).unwrap();
        let content = fs::read_to_string(&paths[0]).unwrap();
        assert!(content.contains("-> str"), "-> str return annotation not found");
    }

    /// Required params appear without a default value; optional params use `None`.
    #[test]
    fn required_params_have_no_default_optional_have_none() {
        let dir = tempfile::tempdir().unwrap();
        // make_config has "url" as required for fetch, no optional
        let config = make_config(dir.path());
        let paths = PythonGenerator.generate(&config).unwrap();
        let content = fs::read_to_string(&paths[0]).unwrap();
        // "url" is required → no "= None" for url
        // (this test verifies the function signature handles optionality)
        assert!(content.contains("url"), "'url' param not found in generated file");
    }

    #[test]
    fn required_params_are_ordered_before_optional_params() {
        let dir = tempfile::tempdir().unwrap();
        let config = GeneratorConfig {
            cli_name: "real".to_string(),
            bridge_url: "http://127.0.0.1:1".to_string(),
            token: "token".to_string(),
            tools: vec![Tool::new(
                "real_tool",
                Some("Real schema".to_string()),
                serde_json::json!({
                    "type": "object",
                    "properties": {
                        "optional_first": {"type": "string"},
                        "required_second": {"type": "string"},
                        "optional_third": {"type": "string"}
                    },
                    "required": ["required_second"]
                }),
            )],
            session_pid: 1,
            output_dir: dir.path().to_path_buf(),
            extra_cli_bridges: Vec::new(),
        };
        let paths = PythonGenerator.generate(&config).unwrap();
        let content = fs::read_to_string(&paths[0]).unwrap();
        assert!(content.contains("def real_tool(required_second, optional_first=None, optional_third=None) -> str:"));
        assert!(content.contains("{\"optional_first\": optional_first, \"required_second\": required_second, \"optional_third\": optional_third}"));
        std::process::Command::new("python3")
            .arg("-m")
            .arg("py_compile")
            .arg(&paths[0])
            .status()
            .expect("python3 should run")
            .success()
            .then_some(())
            .expect("generated Python should compile");
    }


    #[test]
    fn camel_case_tool_and_params_are_pythonic_snake_case_but_payload_keeps_original_keys() {
        let dir = tempfile::tempdir().unwrap();
        let config = GeneratorConfig {
            cli_name: "atlassian".to_string(),
            bridge_url: "http://127.0.0.1:1".to_string(),
            token: "token".to_string(),
            tools: vec![Tool::new(
                "searchJiraIssuesUsingJql",
                Some("Search issues with JQL".to_string()),
                serde_json::json!({
                    "type": "object",
                    "properties": {
                        "cloudId": {"type": "string"},
                        "maxResults": {"type": "number"},
                        "nextPageToken": {"type": "string"}
                    },
                    "required": ["cloudId"]
                }),
            )],
            session_pid: 1,
            output_dir: dir.path().to_path_buf(),
            extra_cli_bridges: Vec::new(),
        };
        let paths = PythonGenerator.generate(&config).unwrap();
        let content = fs::read_to_string(&paths[0]).unwrap();
        assert!(content.contains("def search_jira_issues_using_jql(cloud_id, max_results=None, next_page_token=None) -> str:"));
        assert!(content.contains(r#"{"cloudId": cloud_id, "maxResults": max_results, "nextPageToken": next_page_token}"#));
        std::process::Command::new("python3")
            .arg("-m")
            .arg("py_compile")
            .arg(&paths[0])
            .status()
            .expect("python3 should run")
            .success()
            .then_some(())
            .expect("generated Python should compile");
    }

    // ------------------------------------------------------------------
    // Multi-word tool names
    // ------------------------------------------------------------------

    /// A multi-word tool uses its original snake_case name as the function name.
    #[test]
    fn multiword_tool_function_name_is_snake_case() {
        let dir = tempfile::tempdir().unwrap();
        let config = make_config_multiword_tool(dir.path());
        let paths = PythonGenerator.generate(&config).unwrap();
        let content = fs::read_to_string(&paths[0]).unwrap();
        // Python keeps snake_case for function names
        assert!(
            content.contains("def get_confluence_page("),
            "expected snake_case function name, got: {content:?}",
        );
    }
}