# Zrald2 - Function Logic Analysis MCP Server

Advanced Function Logic Analysis MCP Server that identifies and analyzes function logic patterns related to user files and requests. Integrates with zrald1 MCP server for comprehensive code analysis.

## 🎯 Purpose

Zrald2 is designed to:
- **Identify Functions**: Detect and analyze functions in user code files
- **Logic Pattern Analysis**: Identify complex logic patterns (conditionals, loops, recursion, etc.)
- **Context-Aware Analysis**: Analyze functions in the context of user requests
- **Integration with Zrald1**: Requires and integrates with zrald1 MCP server for file data
- **Comprehensive Summaries**: Generate detailed summaries of function logic and patterns

## 🚀 Features

### Core Capabilities
- **Function Detection**: Parse and identify functions across multiple programming languages
- **Logic Pattern Recognition**: Detect conditional logic, loops, recursion, callbacks, promises, error handling
- **Complexity Analysis**: Calculate cyclomatic and cognitive complexity metrics
- **Relationship Mapping**: Identify relationships between functions (calls, dependencies, similarities)
- **Context Analysis**: Analyze user requests to focus on relevant functions
- **Summary Generation**: Create comprehensive, technical-level-appropriate summaries

### Integration Features
- **Zrald1 Dependency**: Automatically fetches file data from zrald1 MCP server
- **Graph Data Integration**: Uses zrald1's graph processing capabilities
- **Content Search Integration**: Leverages zrald1's vector search for relevant content
- **Relationship Analysis**: Combines with zrald1's file relationship data

## 📦 Installation

```bash
npm install zrald2
```

## 🔧 Usage

### As a standalone MCP server

```bash
npx zrald2
```

### As a library

```typescript
import { FunctionLogicMCPServer } from 'zrald2';

const server = new FunctionLogicMCPServer();
await server.start();
```

## 🛠 Available Tools

### 1. `analyze_functions`
Analyze functions in user files and identify logic patterns

**Parameters:**
- `user_request` (required): Description of what to analyze
- `focus_areas` (optional): Specific function names or areas to focus on
- `technical_level` (optional): 'beginner', 'intermediate', or 'advanced'
- `include_code_examples` (optional): Whether to include code examples

**Example:**
```json
{
  "user_request": "Analyze the authentication functions for security issues",
  "focus_areas": ["login", "authenticate", "validateToken"],
  "technical_level": "advanced",
  "include_code_examples": true
}
```

### 2. `detect_logic_patterns`
Detect specific logic patterns in previously analyzed functions

**Parameters:**
- `pattern_types` (optional): Array of pattern types to detect
- `complexity_threshold` (optional): Minimum complexity threshold

**Example:**
```json
{
  "pattern_types": ["conditional", "loop", "error-handling"],
  "complexity_threshold": 2
}
```

### 3. `generate_function_summary`
Generate a comprehensive summary of function analysis

**Parameters:**
- `summary_type` (optional): 'brief', 'detailed', or 'technical'
- `include_recommendations` (optional): Whether to include recommendations

### 4. `analyze_request_context`
Analyze user request in context of available functions

**Parameters:**
- `user_request` (required): User request to analyze
- `context_keywords` (optional): Additional context keywords

### 5. `validate_zrald1_integration`
Validate connection and integration with zrald1 MCP server

## 📊 Analysis Capabilities

### Function Analysis
- **Function Detection**: Identifies functions, methods, arrow functions, async functions
- **Parameter Analysis**: Analyzes function parameters, types, default values
- **Complexity Metrics**: Calculates cyclomatic and cognitive complexity
- **Dependency Tracking**: Identifies function dependencies and calls

### Logic Pattern Detection
- **Conditional Logic**: if/else, switch, ternary operators
- **Loops**: for, while, forEach, map, filter operations
- **Recursion**: Self-calling functions and recursive patterns
- **Callbacks**: Callback functions and event handlers
- **Promises**: Promise chains, async/await patterns
- **Error Handling**: try/catch blocks, error throwing

### Relationship Analysis
- **Function Calls**: Maps which functions call which other functions
- **Dependencies**: Identifies variable and module dependencies
- **Similarities**: Finds functions with similar structure or complexity
- **Call Graphs**: Builds call relationship graphs

## 🔗 Zrald1 Integration

Zrald2 **requires** zrald1 MCP server to be running and accessible. It integrates by:

1. **File Data Retrieval**: Gets file information and content from zrald1
2. **Graph Data Access**: Uses zrald1's processed graph data
3. **Content Search**: Leverages zrald1's vector search capabilities
4. **Relationship Data**: Incorporates zrald1's file relationship analysis

### Integration Validation
Use the `validate_zrald1_integration` tool to ensure proper connection:

```bash
# This will test the connection and basic functionality
{
  "tool": "validate_zrald1_integration"
}
```

## 📈 Output Examples

### Function Analysis Output
```json
{
  "success": true,
  "analysis": {
    "functions": [
      {
        "function": {
          "name": "authenticateUser",
          "type": "async",
          "parameters": [{"name": "username", "type": "string"}],
          "complexity": 8,
          "location": {"filePath": "auth.js", "startLine": 15}
        },
        "logicPatterns": [
          {
            "type": "conditional",
            "description": "User validation logic",
            "complexity": 2
          },
          {
            "type": "error-handling",
            "description": "Authentication error handling",
            "complexity": 1
          }
        ],
        "complexity": {
          "cyclomaticComplexity": 8,
          "cognitiveComplexity": 6,
          "linesOfCode": 25
        },
        "summary": "authenticateUser is an async function that takes 1 parameter with moderate complexity containing conditional, error-handling logic patterns and makes 3 function calls."
      }
    ],
    "overallSummary": "Found 1 relevant function with an average complexity of 8.0.",
    "recommendations": [
      "Consider refactoring 1 high-complexity function to improve maintainability"
    ]
  }
}
```

### Summary Output
```markdown
# 🔍 Function Logic Analysis

**Request:** Analyze authentication functions for security issues

## 📊 Overview
Found 3 authentication-related functions with moderate to high complexity...

## 🔧 Function Details
### 1. authenticateUser
**Type:** async function
**Parameters:** 2
**Summary:** Complex authentication function with error handling...

## 💡 Recommendations
1. Consider refactoring high-complexity functions
2. Add more comprehensive error handling
3. Review recursive functions for potential issues
```

## 🏗 Architecture

```
zrald2/
├── src/
│   ├── core/
│   │   ├── function-analyzer.ts    # Main function analysis logic
│   │   ├── logic-detector.ts       # Logic pattern detection
│   │   ├── zrald1-client.ts       # Integration with zrald1
│   │   └── summary-generator.ts    # Summary generation
│   ├── types/
│   │   ├── function-analysis.ts    # Type definitions
│   │   └── logic-flow.ts          # Logic flow types
│   ├── utils/
│   │   └── ast-parser.ts          # AST parsing utilities
│   ├── mcp-server.ts              # Main MCP server
│   └── index.ts                   # Entry point
```

## 🔧 Development

### Prerequisites
- Node.js 18+
- TypeScript 5+
- zrald1 MCP server running

### Setup
```bash
git clone <repository>
cd zrald2
npm install
npm run build
```

### Testing
```bash
npm test
```

### Development Mode
```bash
npm run dev
```

## 📝 License

MIT License - see LICENSE file for details.

## 🤝 Contributing

Contributions welcome! Please read the contributing guidelines and submit pull requests.

## 🆘 Support

For issues and questions:
1. Check that zrald1 MCP server is running
2. Validate integration using `validate_zrald1_integration`
3. Review logs for connection issues
4. Submit issues on GitHub

---

**Zrald2 - Advanced Function Logic Analysis for AI Agents** 🚀
