mcp-execution-server 0.7.0

MCP server for progressive loading TypeScript code generation
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
//! Integration tests for skill generation.

use mcp_execution_skill::{
    ParsedToolFile, build_skill_context, parse_tool_file, scan_tools_directory,
};
use std::fmt::Write;
use tempfile::TempDir;
use tokio::fs;

/// Create a test TypeScript tool file.
async fn create_test_tool_file(dir: &std::path::Path, name: &str, category: &str) {
    let content = format!(
        r"/**
 * @tool {name}
 * @server test
 * @category {category}
 * @keywords test,{name}
 * @description Test tool: {name}
 */

interface {pascal_name}Params {{
  required_param: string;
  optional_param?: number;
}}

export async function {pascal_name}(params: {pascal_name}Params): Promise<void> {{
  // Implementation
}}
",
        name = name,
        category = category,
        pascal_name = to_pascal_case(name),
    );

    let filename = format!("{}.ts", to_pascal_case(name));
    fs::write(dir.join(&filename), content).await.unwrap();
}

fn to_pascal_case(s: &str) -> String {
    s.split('_')
        .map(|word| {
            let mut chars = word.chars();
            chars.next().map_or_else(String::new, |first| {
                first.to_uppercase().chain(chars).collect()
            })
        })
        .collect()
}

#[tokio::test]
async fn test_parse_tool_file_integration() {
    let content = r"
/**
 * @tool create_issue
 * @server github
 * @category issues
 * @keywords create,issue,new,bug
 * @description Create a new issue in a repository
 */

interface CreateIssueParams {
  owner: string;
  repo: string;
  title: string;
  body?: string;
  labels?: string[];
}

export async function createIssue(params: CreateIssueParams): Promise<Issue> {
  // Implementation
}
";

    let result = parse_tool_file(content, "createIssue.ts").unwrap();

    assert_eq!(result.name, "create_issue");
    assert_eq!(result.typescript_name, "createIssue");
    assert_eq!(result.server_id, "github");
    assert_eq!(result.category, Some("issues".to_string()));
    assert_eq!(result.keywords.len(), 4);
    assert!(result.description.is_some());
    assert_eq!(result.parameters.len(), 5);

    // Check required vs optional
    let required_count = result.parameters.iter().filter(|p| p.required).count();
    let optional_count = result.parameters.iter().filter(|p| !p.required).count();

    assert_eq!(required_count, 3); // owner, repo, title
    assert_eq!(optional_count, 2); // body, labels
}

#[tokio::test]
async fn test_scan_tools_directory_integration() {
    let temp_dir = TempDir::new().unwrap();
    let dir = temp_dir.path();

    // Create test tool files
    create_test_tool_file(dir, "create_issue", "issues").await;
    create_test_tool_file(dir, "list_repos", "repos").await;
    create_test_tool_file(dir, "get_user", "users").await;

    // Create files that should be skipped
    fs::write(dir.join("index.ts"), "export * from './createIssue';")
        .await
        .unwrap();
    fs::create_dir(dir.join("_runtime")).await.unwrap();
    fs::write(dir.join("_runtime/mcp-bridge.ts"), "// Bridge")
        .await
        .unwrap();

    let tools = scan_tools_directory(dir).await.unwrap();

    assert_eq!(tools.len(), 3);
    assert!(tools.iter().any(|t| t.name == "create_issue"));
    assert!(tools.iter().any(|t| t.name == "list_repos"));
    assert!(tools.iter().any(|t| t.name == "get_user"));
}

#[tokio::test]
async fn test_build_skill_context_integration() {
    let tools = vec![
        ParsedToolFile {
            name: "create_issue".to_string(),
            typescript_name: "createIssue".to_string(),
            server_id: "github".to_string(),
            category: Some("issues".to_string()),
            keywords: vec!["create".to_string(), "issue".to_string()],
            description: Some("Create a new issue".to_string()),
            parameters: vec![],
        },
        ParsedToolFile {
            name: "list_repos".to_string(),
            typescript_name: "listRepos".to_string(),
            server_id: "github".to_string(),
            category: Some("repos".to_string()),
            keywords: vec!["list".to_string(), "repos".to_string()],
            description: Some("List repositories".to_string()),
            parameters: vec![],
        },
    ];

    let use_case_hints = vec!["CI/CD".to_string()];
    let context = build_skill_context("github", &tools, Some(&use_case_hints));

    assert_eq!(context.server_id, "github");
    assert_eq!(context.skill_name, "github-progressive");
    assert_eq!(context.tool_count, 2);
    assert_eq!(context.categories.len(), 2);
    assert!(!context.generation_prompt.is_empty());
    assert!(context.generation_prompt.contains("CI/CD"));
}

#[tokio::test]
async fn test_scan_nonexistent_directory() {
    let result = scan_tools_directory(std::path::Path::new("/nonexistent/path")).await;

    assert!(result.is_err());
}

#[tokio::test]
async fn test_parse_tool_file_missing_required_tags() {
    // Missing @tool tag
    let content = r"
/**
 * @server github
 */
";

    let result = parse_tool_file(content, "test.ts");
    assert!(result.is_err());

    // Missing @server tag
    let content = r"
/**
 * @tool test
 */
";

    let result = parse_tool_file(content, "test.ts");
    assert!(result.is_err());
}

#[tokio::test]
async fn test_skill_metadata_extraction() {
    let content = r"---
name: github-progressive
description: GitHub operations via MCP tools
---

# GitHub Progressive

Introduction paragraph.

## Quick Start

Steps here.

## Common Tasks

Tasks here.

## Troubleshooting

Troubleshooting here.
";

    // This tests the metadata extraction logic
    assert!(content.starts_with("---"));
    assert!(content.contains("name:"));
    assert!(content.contains("description:"));

    // Count sections
    let section_count = content.lines().filter(|l| l.starts_with("## ")).count();
    assert_eq!(section_count, 3);
}

// ============================================================================
// Large File Handling Tests
// ============================================================================

#[tokio::test]
async fn test_scan_directory_with_many_files() {
    let temp_dir = TempDir::new().unwrap();
    let dir = temp_dir.path();

    // Create 50 tool files
    for i in 0..50 {
        let tool_name = format!("tool_{i}");
        create_test_tool_file(dir, &tool_name, "test-category").await;
    }

    let tools = scan_tools_directory(dir).await.unwrap();

    assert_eq!(tools.len(), 50);
    // Verify they're sorted
    for i in 1..tools.len() {
        assert!(tools[i - 1].name <= tools[i].name);
    }
}

#[tokio::test]
async fn test_scan_directory_with_invalid_files() {
    let temp_dir = TempDir::new().unwrap();
    let dir = temp_dir.path();

    // Create valid tool file
    create_test_tool_file(dir, "valid_tool", "category").await;

    // Create invalid TypeScript file (missing @tool tag)
    let invalid_content = r"
/**
 * @server github
 */
export function invalid() {}
";
    fs::write(dir.join("invalid.ts"), invalid_content)
        .await
        .unwrap();

    // Create non-TypeScript file
    fs::write(dir.join("readme.txt"), "Not a TypeScript file")
        .await
        .unwrap();

    let tools = scan_tools_directory(dir).await.unwrap();

    // Should only parse the valid tool (invalid files are logged but skipped)
    assert_eq!(tools.len(), 1);
    assert_eq!(tools[0].name, "valid_tool");
}

#[tokio::test]
async fn test_scan_directory_skips_index_and_runtime() {
    let temp_dir = TempDir::new().unwrap();
    let dir = temp_dir.path();

    // Create valid tool
    create_test_tool_file(dir, "valid_tool", "category").await;

    // Create index.ts (should be skipped)
    fs::write(dir.join("index.ts"), "export * from './validTool';")
        .await
        .unwrap();

    // Create _runtime directory with file (should be skipped)
    fs::create_dir(dir.join("_runtime")).await.unwrap();
    fs::write(dir.join("_runtime/bridge.ts"), "// Runtime bridge")
        .await
        .unwrap();

    // Create file starting with _ (should be skipped)
    create_test_tool_file(dir, "_internal", "category").await;
    let internal_file = dir.join(format!("{}.ts", to_pascal_case("_internal")));
    if internal_file.exists() {
        fs::remove_file(&internal_file).await.ok();
    }
    fs::write(dir.join("_internal.ts"), "// Internal")
        .await
        .unwrap();

    let tools = scan_tools_directory(dir).await.unwrap();

    assert_eq!(tools.len(), 1);
    assert_eq!(tools[0].name, "valid_tool");
}

#[tokio::test]
async fn test_parse_tool_file_large_description() {
    let long_description = "a".repeat(1000);
    let content = format!(
        r"/**
 * @tool test_tool
 * @server github
 * @description {long_description}
 */
"
    );

    let result = parse_tool_file(&content, "test.ts").unwrap();
    assert_eq!(result.description, Some(long_description));
}

#[tokio::test]
async fn test_parse_tool_file_many_keywords() {
    let keywords: Vec<String> = (0..100).map(|i| format!("keyword{i}")).collect();
    let keywords_str = keywords.join(",");

    let content = format!(
        r"/**
 * @tool test_tool
 * @server github
 * @keywords {keywords_str}
 */
"
    );

    let result = parse_tool_file(&content, "test.ts").unwrap();
    assert_eq!(result.keywords.len(), 100);
}

#[tokio::test]
async fn test_parse_tool_file_many_parameters() {
    let mut params = String::new();
    for i in 0..50 {
        writeln!(params, "  param{i}: string;").unwrap();
    }

    let content = format!(
        r"/**
 * @tool test_tool
 * @server github
 */

interface TestToolParams {{
{params}}}
"
    );

    let result = parse_tool_file(&content, "test.ts").unwrap();
    assert_eq!(result.parameters.len(), 50);
}

#[tokio::test]
async fn test_build_skill_context_many_categories() {
    let tools: Vec<ParsedToolFile> = (0..20)
        .map(|i| ParsedToolFile {
            name: format!("tool_{i}"),
            typescript_name: format!("tool{i}"),
            server_id: "test".to_string(),
            category: Some(format!("category-{}", i % 5)), // 5 different categories
            keywords: vec![format!("keyword{i}")],
            description: Some(format!("Tool {i}")),
            parameters: vec![],
        })
        .collect();

    let context = build_skill_context("test", &tools, None);

    assert_eq!(context.tool_count, 20);
    assert_eq!(context.categories.len(), 5);

    // Verify each category has the right number of tools
    for category in &context.categories {
        assert_eq!(category.tools.len(), 4); // 20 tools / 5 categories = 4 per category
    }
}

#[tokio::test]
async fn test_build_skill_context_empty_tools() {
    let tools: Vec<ParsedToolFile> = vec![];

    let context = build_skill_context("test", &tools, None);

    assert_eq!(context.tool_count, 0);
    assert_eq!(context.categories.len(), 0);
    assert_eq!(context.example_tools.len(), 0);
    assert!(context.generation_prompt.contains('0')); // Total tools: 0
}

#[tokio::test]
async fn test_scan_directory_concurrent_access() {
    let temp_dir = TempDir::new().unwrap();
    let dir = temp_dir.path();

    // Create several tool files
    for i in 0..10 {
        create_test_tool_file(dir, &format!("tool_{i}"), "category").await;
    }

    // Scan the same directory concurrently
    let dir_path = dir.to_path_buf();
    let handles: Vec<_> = (0..5)
        .map(|_| {
            let dir = dir_path.clone();
            tokio::spawn(async move { scan_tools_directory(&dir).await })
        })
        .collect();

    // All should succeed
    for handle in handles {
        let result = handle.await.unwrap();
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), 10);
    }
}

// ============================================================================
// Error Handling Tests
// ============================================================================

#[tokio::test]
async fn test_scan_directory_permission_denied() {
    // This test is platform-specific and might not work on all systems
    // We'll skip it on Windows
    if cfg!(windows) {
        return;
    }

    let temp_dir = TempDir::new().unwrap();
    let restricted_dir = temp_dir.path().join("restricted");
    fs::create_dir(&restricted_dir).await.unwrap();

    // Remove read permissions (Unix only)
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = tokio::fs::metadata(&restricted_dir)
            .await
            .unwrap()
            .permissions();
        perms.set_mode(0o000);
        tokio::fs::set_permissions(&restricted_dir, perms)
            .await
            .unwrap();

        let result = scan_tools_directory(&restricted_dir).await;
        assert!(result.is_err());

        // Restore permissions for cleanup
        let mut perms = tokio::fs::metadata(&restricted_dir)
            .await
            .unwrap()
            .permissions();
        perms.set_mode(0o755);
        tokio::fs::set_permissions(&restricted_dir, perms)
            .await
            .unwrap();
    }
}

#[tokio::test]
async fn test_parse_tool_file_binary_content() {
    // Try to parse binary content (should fail gracefully)
    let binary_content = vec![0xFF, 0xFE, 0xFD, 0xFC];
    let content_str = String::from_utf8_lossy(&binary_content);

    let result = parse_tool_file(&content_str, "binary.ts");
    assert!(result.is_err());
}

#[tokio::test]
async fn test_scan_directory_too_many_files() {
    use mcp_execution_skill::{MAX_TOOL_FILES, ScanError};

    let temp_dir = TempDir::new().unwrap();
    let dir = temp_dir.path();

    // Create MAX_TOOL_FILES + 1 files (501 files)
    for i in 0..=MAX_TOOL_FILES {
        create_test_tool_file(dir, &format!("tool_{i}"), "test").await;
    }

    let result = scan_tools_directory(dir).await;

    assert!(result.is_err());
    match result.unwrap_err() {
        ScanError::TooManyFiles { count, limit } => {
            assert_eq!(count, MAX_TOOL_FILES + 1);
            assert_eq!(limit, MAX_TOOL_FILES);
        }
        other => panic!("Expected TooManyFiles error, got: {other:?}"),
    }
}

#[tokio::test]
async fn test_scan_directory_file_too_large() {
    use mcp_execution_skill::{MAX_FILE_SIZE, ScanError};

    let temp_dir = TempDir::new().unwrap();
    let dir = temp_dir.path();

    // Create a file larger than MAX_FILE_SIZE (1MB)
    #[allow(clippy::cast_possible_truncation)]
    let large_content = "a".repeat((MAX_FILE_SIZE as usize) + 1);

    // Add minimal valid JSDoc to make it a tool file
    let content = format!(
        r"/**
 * @tool large_tool
 * @server test
 * @keywords large
 * @description Large tool for testing
 */

interface LargeToolParams {{
  param: string;
}}

{large_content}
"
    );

    let large_file = dir.join("LargeTool.ts");
    fs::write(&large_file, content).await.unwrap();

    let result = scan_tools_directory(dir).await;

    assert!(result.is_err());
    match result.unwrap_err() {
        ScanError::FileTooLarge { path, size, limit } => {
            assert!(path.contains("LargeTool.ts"));
            assert!(size > MAX_FILE_SIZE);
            assert_eq!(limit, MAX_FILE_SIZE);
        }
        other => panic!("Expected FileTooLarge error, got: {other:?}"),
    }
}