# @logspace/mcp-server

[![npm version](https://img.shields.io/npm/v/@logspace/mcp-server.svg)](https://www.npmjs.com/package/@logspace/mcp-server)

Model Context Protocol (MCP) server for Logspace - AI-powered session recording analysis and debugging with GitHub Copilot.

## Installation

### For VS Code / Cursor

The MCP server is automatically configured when you install the Logspace extension. You can also configure it manually:

```bash
npx @logspace/mcp-server@latest
```

Add to your `~/Library/Application Support/Code/User/mcp.json`:

```json
{
	"servers": {
		"logspace": {
			"command": "npx",
			"args": ["-y", "@logspace/mcp-server@latest"],
			"env": {
				"API_BASE_URL": "https://api.logspace.io",
				"API_TOKEN_FILE": "/path/to/.logspace/token.txt"
			}
		}
	}
}
```

### For Development

```bash
npm install @logspace/mcp-server
```

## Features

### 🎯 Smart Analysis

AI-powered intelligent analysis that detects patterns, hidden issues, and provides actionable recommendations.

- **Multi-level depth**: quick (1-3s) / standard (3-8s) / comprehensive (8-15s)
- **Pattern detection**: Suspicious sequences, correlations, anomalies
- **User behavior analysis**: Frustration indicators, interaction patterns
- **Performance insights**: Bottleneck detection, slow requests
- **Masked error detection**: 200 OK responses with error payloads
- **Prioritized recommendations**: Critical, high, medium, low severity

[→ See detailed Smart Analysis documentation](./SMART_ANALYSIS.md)

### 📊 Available Tools

1. **smart_analysis** - AI-powered intelligent session analysis
   - Detects patterns and correlations
   - Finds masked errors (200 OK with error data)
   - Identifies user frustration indicators
   - Provides actionable recommendations
   - Three depth levels: quick, standard, comprehensive

2. **analyze_session** - Basic session analysis
   - Error detection and stack traces
   - Failed network requests
   - User actions timeline
   - Session summary

3. **fetch_bug_logs** - Raw log data retrieval
   - Complete session data
   - All recorded events
   - Unprocessed format

4. **get_error_context** - Error context analysis
   - Events 5 seconds before error
   - Related console logs
   - Network activity
   - User actions

5. **list_network_requests** - Network request filtering
   - Filter by method, status, URL pattern
   - Request/response bodies
   - Performance metrics

6. **get_console_logs** - Console output filtering
   - Filter by log level (error, warn, info, debug)
   - Text search across logs
   - Timestamp filtering

7. **get_storage_logs** - Storage operations
   - localStorage, sessionStorage, cookies, indexedDB
   - Filter by storage type, operation, key pattern
   - Track what data was stored/retrieved

8. **get_interactions** - User interactions
   - Clicks, inputs, scrolls, navigation events
   - Element selectors and coordinates
   - Input values and timestamps

9. **get_annotations** - Session annotations
   - User-added notes and issue flags
   - Highlights and markers
   - Search annotation content

10. **get_sse_websocket_logs** - Real-time communication
    - Server-Sent Events (SSE) messages
    - WebSocket connections and messages
    - Filter by URL, message content

11. **get_rrweb_events** - DOM recording events
    - Access rrweb (DOM mutation recording) events
    - Visual replay event data
    - Filter by event type, time range
    - DOM snapshots and incremental changes

### 🌐 Browser Automation Tools (Optional)

These tools require **Playwright** to be installed separately. If not installed, they will return installation instructions.

12. **replay_session** - Replay user interactions in a real browser
    - Automatically performs clicks, inputs, navigation from recorded session
    - Configurable replay speed (slow/normal/fast)
    - Takes screenshot after replay
    - Useful for reproducing bugs

13. **verify_page** - Verify page state and capture errors
    - Navigate to URL and capture page state
    - Check for console errors and warnings
    - Detect failed network requests
    - Capture screenshot for verification

14. **close_browser** - Close browser session
    - Clean up browser resources
    - Use when done with browser automation

#### Installing Playwright (Optional)

To enable browser automation tools, install Playwright globally:

```bash
npm install -g playwright
npx playwright install chromium
```

Then restart the MCP server.

## Tool Comparison

Choose the right tool for your debugging needs:

| Feature                | smart_analysis       | analyze_session | fetch_bug_logs  | get_error_context   | list_network_requests | get_console_logs  |
| ---------------------- | -------------------- | --------------- | --------------- | ------------------- | --------------------- | ----------------- |
| **Speed**              | 1-15s (configurable) | 1-2s            | <1s             | <1s                 | <1s                   | <1s               |
| **Use Case**           | Deep investigation   | Quick overview  | Raw data export | Error debugging     | API debugging         | Console debugging |
| **Pattern Detection**  | ✅ Advanced          | ❌              | ❌              | ❌                  | ❌                    | ❌                |
| **Hidden Issues**      | ✅                   | ❌              | ❌              | ❌                  | ❌                    | ❌                |
| **Recommendations**    | ✅ Actionable        | ❌              | ❌              | ❌                  | ❌                    | ❌                |
| **Severity Levels**    | ✅ 4 levels          | ❌              | ❌              | ❌                  | ❌                    | ❌                |
| **User Behavior**      | ✅ Advanced          | ⚠️ Basic        | ❌              | ❌                  | ❌                    | ❌                |
| **Error Stack Traces** | ✅                   | ✅              | ✅              | ✅                  | ❌                    | ❌                |
| **Network Analysis**   | ✅                   | ✅              | ✅              | ✅                  | ✅ Advanced           | ❌                |
| **Console Logs**       | ✅                   | ✅              | ✅              | ✅                  | ❌                    | ✅ Advanced       |
| **Filtering**          | ❌                   | ❌              | ❌              | ❌                  | ✅ Advanced           | ✅ Advanced       |
| **Best For**           | Complex bugs         | Quick triage    | Data export     | Single error        | API issues            | Console errors    |
| **Recommended When**   | Need insights        | First look      | Integration     | Investigating crash | 401/500 errors        | Warning floods    |

### When to Use Each Tool

**🎯 smart_analysis** - Start here for unknown issues

- "Why is this session failing?"
- "What patterns do I see across errors?"
- "Is the user frustrated?"
- Recommended depth: `standard` for most cases

**📋 analyze_session** - Quick health check

- "Give me a 10-second summary"
- "What are the obvious errors?"
- "How many requests failed?"

**📦 fetch_bug_logs** - Raw data needed

- Exporting to external tools
- Custom analysis pipelines
- Compliance/audit requirements

**🔍 get_error_context** - Investigating specific error

- "What happened right before this crash?"
- "Which user actions triggered this?"
- Focus on 5-second window

**🌐 list_network_requests** - API debugging

- "Show me all 401 errors"
- "Which POST requests failed?"
- "Find requests to /api/auth/\*"

**📝 get_console_logs** - Console noise

- "Show me only errors"
- "Find logs containing 'timeout'"
- "Filter out debug logs"

## Usage Examples

### With GitHub Copilot Chat

Once configured, use natural language in Copilot Chat:

```
@workspace #logspace analyze session 25
```

```
@workspace #logspace show me all failed API requests in session 42
```

```
@workspace #logspace what errors occurred around timestamp 2024-11-18T10:30:00Z in session 15
```

### Direct Tool Invocation

#### Smart Analysis (Recommended)

```json
{
	"tool": "smart_analysis",
	"arguments": {
		"bugId": 25,
		"depth": "standard"
	}
}
```

**Output includes:**

- Pattern detection results
- Masked error findings
- User frustration indicators
- Prioritized recommendations
- Execution time metrics

#### Quick Session Overview

```json
{
	"tool": "analyze_session",
	"arguments": {
		"bugId": 25
	}
}
```

#### Find Authentication Failures

```json
{
	"tool": "list_network_requests",
	"arguments": {
		"bugId": 25,
		"statusCode": 401,
		"urlPattern": "/api/auth",
		"limit": 10
	}
}
```

#### Investigate Error Context

```json
{
	"tool": "get_error_context",
	"arguments": {
		"bugId": 25,
		"errorId": "err_abc123"
	}
}
```

#### Filter Console Logs

```json
{
	"tool": "get_console_logs",
	"arguments": {
		"bugId": 25,
		"level": "error",
		"searchText": "timeout",
		"limit": 20
	}
}
```

## Configuration

### Environment Variables

| Variable          | Description                           | Default                 | Required |
| ----------------- | ------------------------------------- | ----------------------- | -------- |
| `API_BASE_URL`    | Logspace API endpoint                 | `http://localhost:5002` | No       |
| `API_TOKEN_FILE`  | Path to token JSON file               | -                       | Yes\*    |
| `API_TOKEN`       | Direct token (less secure)            | -                       | Yes\*    |
| `LOG_LEVEL`       | Logging level (debug/info/warn/error) | `info`                  | No       |
| `REQUEST_TIMEOUT` | API request timeout (seconds)         | 3600                    | No       |

\*One of `API_TOKEN_FILE` or `API_TOKEN` is required

### Token File Format

The `API_TOKEN_FILE` should contain JSON with access and refresh tokens:

```json
{
	"access_token": "your-jwt-token",
	"refresh_token": "your-refresh-token",
	"updated_at": "2024-11-18T10:00:00Z"
}
```

## Development

### Local Setup

```bash
git clone https://github.com/logspace-io/logspace-mcp.git
cd logspace-mcp/mcp-server
npm install
npm run build
```

### Watch Mode

```bash
npm run dev
```

### Testing

```bash
# Test smart analysis with different depth levels
node test-smart-analysis.js 25 quick
node test-smart-analysis.js 25 standard
node test-smart-analysis.js 25 comprehensive
```

### Project Structure

```
mcp-server/
├── src/
│   ├── index.ts              # MCP server entry point
│   ├── tools/
│   │   ├── smartAnalysis.ts  # AI-powered analysis (NEW!)
│   │   ├── analyzeSession.ts # Basic analysis
│   │   ├── fetchBugLogs.ts
│   │   ├── getErrorContext.ts
│   │   ├── getConsoleLogs.ts
│   │   └── listNetworkRequests.ts
│   ├── services/
│   │   ├── apiClient.ts      # API integration
│   │   └── logParser.ts      # Log parsing logic
│   ├── types/                # TypeScript types
│   └── utils/                # Helper functions
├── dist/                     # Compiled JavaScript
├── SMART_ANALYSIS.md         # Smart analysis docs
└── test-smart-analysis.js    # Test script
```

## Architecture

### Smart Analysis Pipeline

```
┌─────────────────────────────────────────────────────────────┐
│ 1. Fetch Session Data                                       │
│    • API call to Logspace backend                          │
│    • Request-level caching (5min TTL)                      │
└─────────────────────────────────────────────────────────────┘
                            ↓
┌─────────────────────────────────────────────────────────────┐
│ 2. Parse & Structure Logs                                   │
│    • Errors, console logs, network requests                │
│    • User actions, performance metrics                     │
└─────────────────────────────────────────────────────────────┘
                            ↓
┌─────────────────────────────────────────────────────────────┐
│ 3. Run Analysis (depth-dependent)                          │
│    Quick: Critical issues only (~1-3s)                     │
│    Standard: + Pattern detection (~3-8s)                   │
│    Comprehensive: + Hidden issues (~8-15s)                 │
└─────────────────────────────────────────────────────────────┘
                            ↓
┌─────────────────────────────────────────────────────────────┐
│ 4. Pattern Detection                                        │
│    • Suspicious sequences (error → user reaction)          │
│    • User frustration (rapid clicks, repeated actions)     │
│    • Performance issues (slow requests, bottlenecks)       │
│    • Missing actions (expected API calls not made)         │
└─────────────────────────────────────────────────────────────┘
                            ↓
┌─────────────────────────────────────────────────────────────┐
│ 5. Generate Recommendations                                 │
│    • Prioritized by severity (critical/high/medium/low)    │
│    • Actionable steps with file paths                      │
│    • Related code context                                  │
└─────────────────────────────────────────────────────────────┘
                            ↓
┌─────────────────────────────────────────────────────────────┐
│ 6. Return Structured Results                                │
│    • JSON response with findings                           │
│    • Execution metrics                                     │
└─────────────────────────────────────────────────────────────┘
```

### Key Components

- **API Client** (`services/apiClient.ts`): Authenticated requests with caching
- **Log Parser** (`services/logParser.ts`): Structures raw session data
- **Smart Analysis** (`tools/smartAnalysis.ts`): AI-powered pattern detection
- **Error Handler** (`utils/errorHandler.ts`): Consistent error responses

## Error Handling

All tools return structured error responses:

```json
{
	"success": false,
	"error": "Error message",
	"executionTime": 1234
}
```

## Performance & Optimization

### Response Times

| Tool                           | Typical Response | Max Response |
| ------------------------------ | ---------------- | ------------ |
| smart_analysis (quick)         | 1-3s             | 5s           |
| smart_analysis (standard)      | 3-8s             | 12s          |
| smart_analysis (comprehensive) | 8-15s            | 20s          |
| analyze_session                | 1-2s             | 3s           |
| Other tools                    | <500ms           | 1s           |

### Caching Strategy

- **Request-level caching**: 300s TTL (5 minutes)
- **Shared cache**: Tools in same request cycle reuse data
- **Auto-cleanup**: Cache cleared after request completes
- **Benefits**: Reduces API calls, faster repeated queries

### Optimization Tips

1. **Use `quick` depth first**: Fastest results for initial triage
2. **Filter strategically**: Use `limit` and specific filters to reduce data
3. **Leverage caching**: Multiple tool calls in same session are faster
4. **Batch requests**: Use smart_analysis instead of multiple individual tools

## API Response Format

All tools return consistent JSON responses:

### Success Response

```json
{
	"success": true,
	"data": {
		// Tool-specific data
	},
	"executionTime": 1234,
	"metadata": {
		"bugId": 25,
		"timestamp": "2024-11-18T10:30:00Z"
	}
}
```

### Error Response

```json
{
	"success": false,
	"error": "Descriptive error message",
	"errorCode": "ERROR_TYPE",
	"executionTime": 123
}
```

### Common Error Codes

- `AUTHENTICATION_FAILED`: Invalid or expired token
- `SESSION_NOT_FOUND`: Bug ID doesn't exist
- `RATE_LIMIT_EXCEEDED`: Too many requests
- `NETWORK_ERROR`: API connectivity issues
- `VALIDATION_ERROR`: Invalid parameters

## Troubleshooting

### "Authentication failed" error

1. Check `API_TOKEN_FILE` path exists
2. Verify token file has valid JSON format
3. Ensure token hasn't expired
4. Try refreshing token via Logspace extension

### "Session not found" error

1. Verify bug ID exists in your Logspace account
2. Check you have permission to access the session
3. Confirm session recording completed successfully

### Slow response times

1. Use `quick` depth for faster results
2. Add `limit` parameters to reduce data volume
3. Check network connectivity to API
4. Verify API endpoint is responsive

### MCP connection issues

1. Restart VS Code / Cursor
2. Check `mcp.json` configuration is correct
3. Verify `npx` is available: `which npx`
4. Check Node.js version: `node --version` (requires ≥18)

### Development Guidelines

- Follow existing code style (TypeScript + ESM)
- Add tests for new features
- Update documentation
- Keep response times under limits
- Use semantic commit messages

## License

MIT License - see [LICENSE](LICENSE) file for details

## Links

- **npm Package**: https://www.npmjs.com/package/@logspace/mcp-server
- **GitHub**: https://github.com/logspace-io/logspace-mcp
- **Documentation**: [SMART_ANALYSIS.md](./SMART_ANALYSIS.md)
- **Website**: https://logspace.io
- **Support**: support@logspace.io

## Related Projects

- **VS Code Extension**: Logspace integration for Visual Studio Code
- **JetBrains Plugin**: Logspace integration for IntelliJ IDEA and WebStorm
- **Web Dashboard**: https://app.logspace.io

## Changelog

### v1.0.0

- ✨ Smart analysis tool with AI-powered pattern detection
- ✨ Multi-level analysis depth (quick/standard/comprehensive)
- ✨ Masked error detection
- ✨ User frustration indicators
- ✨ Actionable recommendations with severity levels
- 📋 Basic session analysis
- 🌐 Network request filtering
- 📝 Console log filtering
- 🔍 Error context analysis
- 📦 Raw log data export
- 📚 Comprehensive documentation
