mcp-execution-server 0.8.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
//! Type definitions for MCP server tools.
//!
//! This module defines all parameter and result types for the three main tools:
//! - `introspect_server`: Connect to and introspect an MCP server
//! - `save_categorized_tools`: Generate TypeScript files with categorization
//! - `list_generated_servers`: List all servers with generated files

use crate::clock::Clock;
use chrono::{DateTime, Utc};
use mcp_execution_core::{ServerConfig, ServerId};
use mcp_execution_introspector::ServerInfo;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use uuid::Uuid;

// ============================================================================
// introspect_server types
// ============================================================================

/// Parameters for introspecting an MCP server.
///
/// # Examples
///
/// ```
/// use mcp_execution_server::types::IntrospectServerParams;
/// use std::collections::HashMap;
///
/// let params = IntrospectServerParams {
///     server_id: "github".to_string(),
///     command: "npx".to_string(),
///     args: vec!["-y".to_string(), "@anthropic/mcp-server-github".to_string()],
///     env: HashMap::new(),
///     output_dir: None,
///     connect_timeout_secs: None,
///     discover_timeout_secs: None,
/// };
/// ```
#[derive(Debug, Clone, Deserialize, JsonSchema)]
pub struct IntrospectServerParams {
    /// Unique identifier for the server (e.g., "github", "filesystem")
    pub server_id: String,

    /// Command to start the server (e.g., "npx", "docker")
    pub command: String,

    /// Arguments to pass to the command
    #[serde(default)]
    pub args: Vec<String>,

    /// Environment variables for the server process
    #[serde(default)]
    pub env: HashMap<String, String>,

    /// Custom output directory (default: `~/.claude/servers/{server_id}`)
    pub output_dir: Option<PathBuf>,

    /// Connection (handshake) timeout in seconds, overriding the 30-second
    /// default when set.
    #[serde(default)]
    pub connect_timeout_secs: Option<u64>,

    /// Tool discovery timeout in seconds, overriding the 30-second default
    /// when set.
    #[serde(default)]
    pub discover_timeout_secs: Option<u64>,
}

/// Result from introspecting an MCP server.
///
/// Contains tool metadata for Claude to categorize and a session ID
/// for use with `save_categorized_tools`.
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct IntrospectServerResult {
    /// Server identifier
    pub server_id: String,

    /// Human-readable server name
    pub server_name: String,

    /// Number of tools discovered
    pub tools_found: usize,

    /// List of tools for categorization
    pub tools: Vec<IntrospectedToolSummary>,

    /// Session ID for `save_categorized_tools` call
    pub session_id: Uuid,

    /// Session expiration time (ISO 8601)
    pub expires_at: DateTime<Utc>,
}

/// Summary of an introspected tool, returned to Claude for categorization.
///
/// Includes the tool name, description, and parameter names to help
/// Claude understand the tool's purpose and assign appropriate categories.
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct IntrospectedToolSummary {
    /// Original tool name
    pub name: String,

    /// Tool description from server
    pub description: String,

    /// Parameter names for context
    pub parameters: Vec<String>,
}

// ============================================================================
// save_categorized_tools types
// ============================================================================

/// Parameters for saving categorized tools.
///
/// # Examples
///
/// ```
/// use mcp_execution_server::types::{SaveCategorizedToolsParams, CategorizedTool};
/// use uuid::Uuid;
///
/// let params = SaveCategorizedToolsParams {
///     session_id: Uuid::new_v4(),
///     categorized_tools: vec![
///         CategorizedTool {
///             name: "create_issue".to_string(),
///             category: "issues".to_string(),
///             keywords: "create,issue,new,bug,feature".to_string(),
///             short_description: "Create a new issue in a repository".to_string(),
///         },
///     ],
/// };
/// ```
#[derive(Debug, Clone, Deserialize, JsonSchema)]
pub struct SaveCategorizedToolsParams {
    /// Session ID from `introspect_server` call
    pub session_id: Uuid,

    /// Tools with Claude's categorization
    pub categorized_tools: Vec<CategorizedTool>,
}

/// A tool with categorization metadata from Claude.
///
/// Claude analyzes the tool's purpose and provides:
/// - A category for grouping related tools
/// - Keywords for discovery via grep/search
/// - A concise description for file headers
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CategorizedTool {
    /// Original tool name (must match introspected tool)
    pub name: String,

    /// Category assigned by Claude (e.g., "issues", "repos", "users")
    pub category: String,

    /// Comma-separated keywords for discovery
    pub keywords: String,

    /// Concise description (max 80 chars) for header comment
    pub short_description: String,
}

/// Result from saving categorized tools.
///
/// Reports success status, number of files generated, and any errors
/// that occurred during generation.
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct SaveCategorizedToolsResult {
    /// Whether generation succeeded
    pub success: bool,

    /// Number of TypeScript files created
    pub files_generated: usize,

    /// Directory where files were written
    pub output_dir: String,

    /// Count of tools per category
    pub categories: HashMap<String, usize>,

    /// Any tools that failed to generate
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub errors: Vec<ToolGenerationError>,
}

/// Error that occurred while generating a specific tool.
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct ToolGenerationError {
    /// Name of the tool that failed
    pub tool_name: String,

    /// Error message
    pub error: String,
}

// ============================================================================
// list_generated_servers types
// ============================================================================

/// Parameters for listing generated servers.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
pub struct ListGeneratedServersParams {
    /// Base directory to scan (default: `~/.claude/servers`)
    pub base_dir: Option<String>,
}

/// Result from listing generated servers.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ListGeneratedServersResult {
    /// List of servers with generated files
    pub servers: Vec<GeneratedServerInfo>,

    /// Total number of servers found
    pub total_servers: usize,
}

/// Information about a server with generated progressive loading files.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct GeneratedServerInfo {
    /// Server identifier
    pub id: String,

    /// Number of tool files (excluding runtime)
    pub tool_count: usize,

    /// Last generation timestamp
    pub generated_at: Option<DateTime<Utc>>,

    /// Directory path
    pub output_dir: String,
}

// ============================================================================
// State management types
// ============================================================================

/// Pending generation session.
///
/// Stores introspection data between `introspect_server` and
/// `save_categorized_tools` calls.
#[derive(Debug, Clone)]
pub struct PendingGeneration {
    /// Server identifier
    pub server_id: ServerId,

    /// Full server introspection data
    pub server_info: ServerInfo,

    /// Server configuration for regeneration if needed
    pub config: ServerConfig,

    /// Output directory
    pub output_dir: PathBuf,

    /// Session creation time
    pub created_at: DateTime<Utc>,

    /// Session expiration time (30 minutes default)
    pub expires_at: DateTime<Utc>,
}

impl PendingGeneration {
    /// Default session timeout: 30 minutes.
    pub const DEFAULT_TIMEOUT_MINUTES: i64 = 30;

    /// Creates a new pending generation session.
    ///
    /// The session's `created_at`/`expires_at` are derived from `clock.now()`,
    /// so tests can inject a fake clock instead of rewinding `expires_at`
    /// after construction. Production callers should pass [`SystemClock`](crate::clock::SystemClock).
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_server::types::PendingGeneration;
    /// use mcp_execution_server::clock::SystemClock;
    /// use mcp_execution_core::{ServerId, ServerConfig};
    /// use mcp_execution_introspector::ServerInfo;
    /// use std::path::PathBuf;
    ///
    /// # fn example(server_info: ServerInfo) {
    /// let server_id = ServerId::new("github");
    /// let config = ServerConfig::builder()
    ///     .command("npx".to_string())
    ///     .arg("-y".to_string())
    ///     .arg("@anthropic/mcp-server-github".to_string())
    ///     .build();
    /// let output_dir = PathBuf::from("/tmp/output");
    ///
    /// let pending = PendingGeneration::new(
    ///     server_id,
    ///     server_info,
    ///     config,
    ///     output_dir,
    ///     &SystemClock,
    /// );
    /// # }
    /// ```
    #[must_use]
    pub fn new(
        server_id: ServerId,
        server_info: ServerInfo,
        config: ServerConfig,
        output_dir: PathBuf,
        clock: &dyn Clock,
    ) -> Self {
        let now = clock.now();
        Self {
            server_id,
            server_info,
            config,
            output_dir,
            created_at: now,
            expires_at: now + chrono::Duration::minutes(Self::DEFAULT_TIMEOUT_MINUTES),
        }
    }

    /// Checks if this session has expired, using `clock.now()` as the current time.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_server::types::PendingGeneration;
    /// use mcp_execution_server::clock::SystemClock;
    /// # use mcp_execution_core::{ServerId, ServerConfig};
    /// # use mcp_execution_introspector::ServerInfo;
    /// # use std::path::PathBuf;
    ///
    /// # fn example(server_info: ServerInfo) {
    /// let pending = PendingGeneration::new(
    ///     ServerId::new("test"),
    ///     server_info,
    ///     ServerConfig::builder().command("echo".to_string()).build(),
    ///     PathBuf::from("/tmp"),
    ///     &SystemClock,
    /// );
    ///
    /// assert!(!pending.is_expired(&SystemClock));
    /// # }
    /// ```
    #[must_use]
    pub fn is_expired(&self, clock: &dyn Clock) -> bool {
        clock.now() > self.expires_at
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::clock::{SystemClock, TestClock};

    #[test]
    fn test_pending_generation_not_expired() {
        let pending = create_test_pending();
        assert!(!pending.is_expired(&SystemClock));
    }

    #[test]
    fn test_pending_generation_not_expired_at_exact_boundary() {
        let clock = TestClock::new(Utc::now());
        let pending = create_test_pending_with_clock(&clock);

        // `is_expired` uses strict `>`, so the exact expiry instant is not expired.
        clock.advance(chrono::Duration::minutes(
            PendingGeneration::DEFAULT_TIMEOUT_MINUTES,
        ));
        assert!(!pending.is_expired(&clock));
    }

    #[test]
    fn test_pending_generation_not_expired_one_second_before_boundary() {
        let clock = TestClock::new(Utc::now());
        let pending = create_test_pending_with_clock(&clock);

        clock.advance(
            chrono::Duration::minutes(PendingGeneration::DEFAULT_TIMEOUT_MINUTES)
                - chrono::Duration::seconds(1),
        );
        assert!(!pending.is_expired(&clock));
    }

    #[test]
    fn test_pending_generation_expired_one_second_after_boundary() {
        let clock = TestClock::new(Utc::now());
        let pending = create_test_pending_with_clock(&clock);

        clock.advance(
            chrono::Duration::minutes(PendingGeneration::DEFAULT_TIMEOUT_MINUTES)
                + chrono::Duration::seconds(1),
        );
        assert!(pending.is_expired(&clock));
    }

    #[test]
    fn test_categorized_tool_serialization() {
        let tool = CategorizedTool {
            name: "create_issue".to_string(),
            category: "issues".to_string(),
            keywords: "create,issue,new".to_string(),
            short_description: "Create a new issue".to_string(),
        };

        let json = serde_json::to_string(&tool).unwrap();
        let _deserialized: CategorizedTool = serde_json::from_str(&json).unwrap();
    }

    // Test helpers
    fn create_test_pending() -> PendingGeneration {
        create_test_pending_with_clock(&SystemClock)
    }

    fn create_test_pending_with_clock(clock: &dyn Clock) -> PendingGeneration {
        use mcp_execution_core::ToolName;
        use mcp_execution_introspector::{ServerCapabilities, ToolInfo};

        let server_id = ServerId::new("test");
        let server_info = ServerInfo {
            id: server_id.clone(),
            name: "Test Server".to_string(),
            version: "1.0.0".to_string(),
            capabilities: ServerCapabilities {
                supports_tools: true,
                supports_resources: false,
                supports_prompts: false,
            },
            tools: vec![ToolInfo {
                name: ToolName::new("test_tool"),
                description: "Test tool description".to_string(),
                input_schema: serde_json::json!({}),
                output_schema: None,
            }],
        };
        let config = ServerConfig::builder().command("echo".to_string()).build();
        let output_dir = PathBuf::from("/tmp/test");

        PendingGeneration::new(server_id, server_info, config, output_dir, clock)
    }
}