leindex 1.9.0

LeIndex MCP and semantic code search engine for AI tools and large codebases
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
use super::{JsonRpcError, JsonRpcRequest};
use serde::Serialize;
use serde_json::Value;

/// List prompts as JSON
pub fn list_prompts_json() -> Value {
    let prompts = get_prompts();
    serde_json::json!({ "prompts": prompts })
}

/// Handle prompts/get request
pub fn handle_prompt_get(req: &JsonRpcRequest) -> Result<Value, JsonRpcError> {
    let params = req
        .params
        .as_ref()
        .ok_or_else(|| JsonRpcError::invalid_params("Missing params for prompts/get"))?;

    let name = params
        .get("name")
        .and_then(|v| v.as_str())
        .ok_or_else(|| JsonRpcError::invalid_params("Missing or invalid 'name' field"))?;

    let arguments = params.get("arguments").cloned();
    let messages = get_prompt(name, arguments)?;

    Ok(serde_json::json!({
        "description": format!("Prompt: {}", name),
        "messages": messages
    }))
}

/// List resources as JSON
pub fn list_resources_json() -> Value {
    let resources = get_resources();
    serde_json::json!({ "resources": resources })
}

/// Handle resources/read request
pub fn handle_resource_read(req: &JsonRpcRequest) -> Result<Value, JsonRpcError> {
    let params = req
        .params
        .as_ref()
        .ok_or_else(|| JsonRpcError::invalid_params("Missing params for resources/read"))?;

    let uri = params
        .get("uri")
        .and_then(|v| v.as_str())
        .ok_or_else(|| JsonRpcError::invalid_params("Missing or invalid 'uri' field"))?;

    let content = get_resource(uri)?;
    Ok(serde_json::json!({ "contents": [content] }))
}

// ============================================================================
// MCP Prompts Implementation
// ============================================================================

/// A prompt definition for the MCP prompts capability
#[derive(Debug, Clone, Serialize)]
pub struct Prompt {
    /// Unique identifier for the prompt
    pub name: String,
    /// Human-readable description
    pub description: String,
    /// Optional arguments the prompt accepts
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments: Option<Vec<PromptArgument>>,
}

/// A prompt argument definition
#[derive(Debug, Clone, Serialize)]
pub struct PromptArgument {
    /// Argument name
    pub name: String,
    /// Argument description
    pub description: String,
    /// Whether the argument is required
    pub required: bool,
}

/// A prompt message (content)
#[derive(Debug, Clone, Serialize)]
pub struct PromptMessage {
    /// Role of the message sender
    pub role: String,
    /// Content of the message
    pub content: PromptContent,
}

/// Content of a prompt message
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
pub enum PromptContent {
    /// Text content
    #[serde(rename = "text")]
    Text {
        /// The text content of the message
        text: String,
    },
}

/// Get the list of available prompts
pub fn get_prompts() -> Vec<Prompt> {
    vec![
        Prompt {
            name: "quickstart".to_string(),
            description: "Quick introduction to using LeIndex effectively".to_string(),
            arguments: None,
        },
        Prompt {
            name: "investigation_workflow".to_string(),
            description: "Step-by-step guide for investigating code with LeIndex".to_string(),
            arguments: Some(vec![PromptArgument {
                name: "query".to_string(),
                description: "What you're trying to find or understand".to_string(),
                required: true,
            }]),
        },
    ]
}

/// Get a specific prompt by name
pub fn get_prompt(
    name: &str,
    arguments: Option<Value>,
) -> Result<Vec<PromptMessage>, JsonRpcError> {
    match name {
        "quickstart" => Ok(vec![
            PromptMessage {
                role: "user".to_string(),
                content: PromptContent::Text {
                    text: "Welcome to LeIndex! Here's how to get started:\n\n1. **Indexing**: First, index your project with `leindex.index`\n2. **Searching**: Use `leindex.search` for semantic code search\n3. **Analysis**: Use `leindex.deep-analyze` for comprehensive code analysis\n4. **Context**: Use `leindex.context` to expand around specific symbols\n\nPro tip: LeIndex auto-indexes on first use, so you can start searching immediately!".to_string(),
                },
            },
        ]),
        "investigation_workflow" => {
            let query = arguments
                .as_ref()
                .and_then(|a| a.get("query"))
                .and_then(|q| q.as_str())
                .filter(|query| !query.trim().is_empty())
                .ok_or_else(|| {
                    JsonRpcError::invalid_params(
                        "investigation_workflow requires a non-empty string 'query' argument",
                    )
                })?;

            Ok(vec![
                PromptMessage {
                    role: "user".to_string(),
                    content: PromptContent::Text {
                        text: format!(
                            "Let me help you investigate: {}\n\nHere's the recommended workflow:\n\n1. **Start broad**: Use `leindex.search` with a natural language query like '{}'\n2. **Find entry points**: Look for the most relevant symbols in the results\n3. **Deep dive**: Use `leindex.deep-analyze` on the most relevant symbol\n4. **Expand context**: Use `leindex.context` to see how the symbol is used\n5. **Navigate**: Follow symbol references with `leindex.read-symbol`\n\nWould you like me to help you with any specific step?",
                            query, query
                        ),
                    },
                },
            ])
        }
        _ => Err(JsonRpcError::method_not_found(format!("Prompt '{}' not found", name))),
    }
}

// ============================================================================
// MCP Resources Implementation
// ============================================================================

/// A resource definition for the MCP resources capability
#[derive(Debug, Clone, Serialize)]
pub struct Resource {
    /// Unique URI for the resource
    pub uri: String,
    /// Human-readable name
    pub name: String,
    /// MIME type of the resource
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "mimeType")]
    pub mime_type: Option<String>,
    /// Resource description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Resource content
#[derive(Debug, Clone, Serialize)]
pub struct ResourceContent {
    /// Resource URI
    pub uri: String,
    /// MIME type
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "mimeType")]
    pub mime_type: Option<String>,
    /// Text content (if text resource)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    /// Binary content (if binary resource)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blob: Option<String>,
}

/// Get the list of available resources
pub fn get_resources() -> Vec<Resource> {
    vec![
        Resource {
            uri: "leindex://docs/quickstart".to_string(),
            name: "LeIndex Quickstart Guide".to_string(),
            mime_type: Some("text/markdown".to_string()),
            description: Some("Quick start guide for using LeIndex".to_string()),
        },
        Resource {
            uri: "leindex://docs/server-config".to_string(),
            name: "Server Configuration".to_string(),
            mime_type: Some("text/markdown".to_string()),
            description: Some("Configuration options for LeIndex server".to_string()),
        },
    ]
}

/// Get a specific resource by URI
pub fn get_resource(uri: &str) -> Result<ResourceContent, JsonRpcError> {
    match uri {
        "leindex://docs/quickstart" => Ok(ResourceContent {
            uri: uri.to_string(),
            mime_type: Some("text/markdown".to_string()),
            text: Some(QUICKSTART_GUIDE.to_string()),
            blob: None,
        }),
        "leindex://docs/server-config" => Ok(ResourceContent {
            uri: uri.to_string(),
            mime_type: Some("text/markdown".to_string()),
            text: Some(SERVER_CONFIG_GUIDE.to_string()),
            blob: None,
        }),
        _ => Err(JsonRpcError::method_not_found(format!(
            "Resource '{}' not found",
            uri
        ))),
    }
}

/// Quickstart guide content
const QUICKSTART_GUIDE: &str = r#"# LeIndex Quickstart Guide

## Installation

```bash
cargo install leindex
```

## Basic Usage

### 1. Index a Project

```bash
leindex index /path/to/project
```

Or use the MCP tool:
```json
{
  "name": "leindex.index",
  "arguments": {
    "project_path": "/path/to/project"
  }
}
```

### 2. Search Code

```bash
leindex search "how is authentication handled"
```

Or use the MCP tool:
```json
{
  "name": "leindex.search",
  "arguments": {
    "query": "how is authentication handled",
    "limit": 10
  }
}
```

### 3. Deep Analysis

```bash
leindex analyze --symbol "User::authenticate"
```

Or use the MCP tool:
```json
{
  "name": "leindex.deep-analyze",
  "arguments": {
    "query": "User::authenticate"
  }
}
```

## Available Tools

- `leindex.search` - Semantic code search
- `leindex.deep-analyze` - Comprehensive code analysis
- `leindex.context` - Expand symbol context
- `leindex.grep-symbols` - Search symbols by name
- `leindex.read-file` - Read file with PDG annotations
- `leindex.file-summary` - Get file structural summary

## Environment Variables

- `LEINDEX_HOME` - Storage directory (default: ~/.leindex)
- `LEINDEX_PORT` - Server port (default: 47500)
"#;

/// Server configuration guide content
const SERVER_CONFIG_GUIDE: &str = r#"# LeIndex Server Configuration

## Configuration Options

The LeIndex server can be configured via:

1. Command-line arguments
2. Environment variables
3. Configuration file (config.yaml)

## Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `LEINDEX_HOME` | Storage/index directory | `~/.leindex` |
| `LEINDEX_PORT` | HTTP server port | `47500` |
| `LEINDEX_HOST` | HTTP server host | `127.0.0.1` |

## MCP Server Mode

Start the MCP server:

```bash
leindex mcp --stdio
```

For HTTP transport:

```bash
leindex serve
```

## Feature Flags

When building from source:

- `full` - All features (default)
- `minimal` - Parse and search only
- `cli` - CLI + MCP server
- `server` - HTTP server only

## Multi-Project Support

The server supports multiple concurrent projects:

```bash
leindex serve --max-projects 10
```

Default maximum: 5 projects.
"#;

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

    #[test]
    fn test_investigation_workflow_requires_non_empty_query() {
        assert!(get_prompt("investigation_workflow", None).is_err());
        assert!(
            get_prompt(
                "investigation_workflow",
                Some(serde_json::json!({"query": "   "}))
            )
            .is_err()
        );
        assert!(
            get_prompt(
                "investigation_workflow",
                Some(serde_json::json!({"query": 42}))
            )
            .is_err()
        );
    }

    #[test]
    fn test_investigation_workflow_generates_for_non_empty_query() {
        let messages = get_prompt(
            "investigation_workflow",
            Some(serde_json::json!({"query": "find authentication"})),
        )
        .unwrap();

        assert_eq!(messages.len(), 1);
        match &messages[0].content {
            PromptContent::Text { text } => assert!(text.contains("find authentication")),
        }
    }
}