# {{PROJECT_NAME}}

{{PROJECT_DESCRIPTION}}

A modern Model Context Protocol (MCP) server built with TypeScript, demonstrating advanced MCP capabilities through a comprehensive **Data Analysis Assistant**. Features clean architectural separation and integrated testing with the [MCP Inspector](https://github.com/modelcontextprotocol/inspector).

## 🎯 **Unified Architecture**

Instead of scattered examples, this project showcases **one comprehensive Data Analysis Assistant** that demonstrates ALL MCP capabilities:

### 🔧 **Comprehensive Tools** (2 focused tools)
- **`data-analysis`** - Complete analysis with 5 methodologies, 6 sampling strategies, elicitation integration
- **`server-status`** - Health monitoring and performance tracking

### 📋 **Rich Resources** (2 comprehensive resources) 
- **`data-analysis` resources** - Complete methodology guides, templates, workflows, and best practices
- **`server-info` resources** - Server information, configuration, dynamic welcome messages, and API docs

### 💡 **Flexible Prompts** (1 multi-methodology prompt)
- **`research-analysis`** - 8 research methodologies with flexible contexts and output formats

### ✨ **Advanced Features**
- 🧠 **Interactive Elicitation** - Guided analysis with smart question generation
- 📊 **AI-Enhanced Sampling** - 6 sampling strategies including AI-powered techniques  
- 🏗️ **Modular Architecture** - Clean separation of concerns with dependency injection
- 🛡️ **Production Ready** - Comprehensive error handling and validation
- 🔄 **Multiple Transports** - Stdio and HTTP with session management

## 🚀 Quick Start

### Installation & Setup

```bash
npm install
```

### 🔍 **MCP Inspector Integration**

Test and explore your server using the integrated [MCP Inspector](https://github.com/modelcontextprotocol/inspector):

#### Visual Testing (UI Mode)
```bash
# Launch interactive inspector
npm run inspector

# Test with HTTP transport
npm run inspector:http
```

#### Command Line Testing (CLI Mode) 
```bash
# Test all capabilities via CLI
npm run inspector:cli

# Test specific endpoints
npm run test:tools      # List available tools
npm run test:resources  # List available resources  
npm run test:prompts    # List available prompts

# Test with built version
npm run inspector:built
```

## Quick Start

### Installation

```bash
npm install
```

### Development Commands

#### Basic Development
```bash
# Stdio transport (for CLI tools like Claude Desktop)
npm run dev:stdio

# HTTP transport (for web services and browser clients)
npm run dev:http
```

#### Advanced HTTP Options
```bash
# HTTP with OAuth authentication
npm run dev:http:oauth

# Stateless HTTP mode (simplified deployment)
npm run dev:http:stateless

# Secure configuration
npm run dev:http:secure
```

### Production Deployment

```bash
# Build the project
npm run build

# Standard deployment
npm run start:http

# Production with OAuth
npm run start:http:oauth

# Stateless deployment (for serverless/containers)
npm run start:http:stateless
```

## 🌐 HTTP Transport Features

### Endpoints

- `POST /mcp` - MCP communication and initialization
- `GET /mcp` - Server-Sent Events for real-time notifications
- `DELETE /mcp` - Session termination and cleanup
- `GET /health` - Comprehensive health checks
- `GET /info` - Server capabilities and configuration

### Session Management

The server supports both **stateful** and **stateless** modes:

#### Stateful Mode (Default)
- Persistent sessions with unique session IDs
- Server-Sent Events for real-time notifications
- Session cleanup and resource management
- Resumable connections with `Last-Event-ID`

#### Stateless Mode
- No session persistence
- Simpler deployment and scaling
- Each request is independent
- Ideal for API proxies and serverless environments

### Security Features

- **CORS Configuration** for browser clients
- **DNS Rebinding Protection** with allowed hosts/origins
- **OAuth Authentication** for secure access
- **Request Validation** with comprehensive error handling

## 🛠️ **Data Analysis Assistant**

### Comprehensive Tools

#### 1. **Data Analysis Tool** 
The main feature showcasing all MCP capabilities:

```bash
# Example data analysis with sampling and elicitation
{
  "data": [{"age": 25, "score": 85}, {"age": 30, "score": 92}],
  "analysis_type": "exploratory",
  "sampling_strategy": "ai-representative", 
  "sample_size": 100,
  "enable_elicitation": true,
  "output_format": "detailed"
}
```

**Features:**
- 📊 **5 Analysis Types**: exploratory, descriptive, diagnostic, predictive, prescriptive
- 🎯 **6 Sampling Strategies**: random, systematic, stratified, ai-representative, ai-diverse, none
- 🧠 **Elicitation Integration**: Interactive guidance and smart questions
- 📈 **Statistical Analysis**: Descriptive stats, anomaly detection, pattern recognition
- 🔧 **Multiple Output Formats**: summary, detailed, statistical, insights

#### 2. **Server Status Tool**
Simple monitoring and health checks:

```bash
{
  "include_details": true,
  "format": "json"
}
```

### Interactive Workflows

#### Elicitation-Driven Analysis
1. Start with data analysis (enable_elicitation: true)
2. Receive contextual questions about your data
3. Use elicitation session for guided exploration
4. Get targeted analysis based on your responses

#### Multi-Stage Analysis Pipeline
```bash
# 1. Exploratory → understand data
# 2. Descriptive → statistical summaries  
# 3. Diagnostic → investigate relationships
# 4. Predictive → forecast trends
# 5. Prescriptive → actionable recommendations
```

## 📚 **Comprehensive Resources**

### Data Analysis Resources

#### 1. **Methodology Guide** (`analysis://methodology`)
Complete guide to data analysis approaches and best practices.

#### 2. **Analysis Templates** (`analysis://template/{type}`)
Dynamic templates for each analysis type:
- `analysis://template/exploratory` - Initial data exploration
- `analysis://template/descriptive` - Statistical summaries
- `analysis://template/diagnostic` - Causal investigation
- `analysis://template/predictive` - Forecasting
- `analysis://template/prescriptive` - Recommendations

#### 3. **Sampling Guide** (`analysis://sampling-guide`)  
Comprehensive documentation of sampling strategies and usage.

#### 4. **Elicitation Workflows** (`analysis://elicitation-workflows`)
Interactive workflow templates for guided analysis.

#### 5. **Best Practices** (`analysis://best-practices`)
Industry best practices for effective data analysis.

### Server Information Resources

#### 1. **Server Info** (`server://info`)
Complete server capabilities and real-time status.

#### 2. **Configuration** (`server://config`) 
Current server configuration and runtime settings.

#### 3. **Welcome Message** (`server://welcome/{name}`)
Personalized welcome with capability overview.

#### 4. **API Documentation** (`server://api-docs`)
Complete API documentation and usage examples.

## 💬 **Research Analysis Prompts**

### Multi-Methodology Prompt System

The `research-analysis` prompt supports **8 methodologies**:

#### Core Methodologies
- 📊 **data-analysis** - Statistical and pattern analysis
- 🔍 **code-review** - Software quality assessment  
- 🏗️ **system-design** - Architecture planning
- 📚 **literature-review** - Academic research synthesis

#### Advanced Methodologies  
- ⚖️ **comparative-analysis** - Option evaluation
- 📝 **case-study** - In-depth scenario analysis
- 🧪 **experimental-design** - Research methodology design
- 📋 **survey-research** - Data collection planning

### Flexible Configuration

```bash
{
  "topic": "Customer churn prediction analysis",
  "methodology": "data-analysis", 
  "context": "E-commerce subscription business",
  "depth": "comprehensive",
  "audience": "technical",
  "output_format": "structured"
}
```

**Parameters:**
- **depth**: overview, detailed, comprehensive, expert
- **audience**: general, technical, academic, executive  
- **output_format**: structured, narrative, academic, business
- **include_methodology**: Include methodology explanations
- **include_examples**: Include templates and examples

## ⚙️ Configuration

### Environment Variables

```bash
# Transport mode
MCP_TRANSPORT=http|stdio

# HTTP server port
PORT=3000

# Logging level
LOG_LEVEL=debug|info|warn|error

# Feature flags
ENABLE_OAUTH=true|false
ENABLE_DNS_PROTECTION=true|false
ENABLE_STATELESS=true|false
```

### Command Line Options

```bash
# OAuth authentication
node dist/server.js http --oauth

# Disable DNS protection
node dist/server.js http --no-dns-protection

# Stateless mode
node dist/server.js http --stateless

# Combined options
node dist/server.js http --oauth --stateless
```

## 🏥 Health Monitoring

### Health Checks

The server includes comprehensive health monitoring:

- **Memory Usage** - Heap memory monitoring with warnings
- **Uptime Tracking** - Server uptime and stability metrics
- **Custom Checks** - Extensible health check system

### Health Endpoints

```bash
# Basic health check
curl http://localhost:3000/health

# Detailed server info
curl http://localhost:3000/info
```

### Custom Health Checks

```typescript
healthChecker.registerCheck('database', async () => {
  const isConnected = await checkDatabaseConnection();
  return {
    name: 'database',
    status: isConnected ? 'pass' : 'fail',
    message: isConnected ? 'Connected' : 'Connection failed'
  };
});
```

## 🧪 Testing

### Running Tests

```bash
# Run all tests
npm test

# Watch mode for development
npm run test:watch

# Coverage report
npm test -- --coverage
```

### Test Structure

```typescript
describe('MCP Server', () => {
  test('should handle tool calls', async () => {
    const result = await server.callTool('echo', { message: 'test' });
    expect(result.content[0].text).toBe('Echo [plain]: test');
  });
});
```

## 🔧 Development

### Code Quality

```bash
# Lint code
npm run lint

# Auto-fix issues
npm run lint:fix

# Type checking
npm run build
```

### Project Structure

Our clean, modular architecture:

```
src/
├── server.ts                      # Simplified main entry point (106 lines)
├── core/                          # Core server logic
│   ├── config.ts                  # Configuration management
│   ├── mcp-server.ts              # Core MCP server implementation  
│   └── server-factory.ts          # Server instantiation
├── transports/                    # Transport layer
│   ├── stdio-transport.ts         # Stdio communication
│   ├── http-transport.ts          # HTTP communication
│   └── transport-manager.ts       # Transport coordination
├── tools/                         # Modular tool implementations
│   ├── index.ts                   # Tool registry
│   ├── data-analysis-tool.ts      # Comprehensive analysis tool
│   └── server-status-tool.ts      # Monitoring tool
├── resources/                     # Resource providers
│   ├── index.ts                   # Resource registry
│   ├── data-analysis-resource.ts  # Analysis documentation
│   └── server-info-resource.ts    # Server information
├── prompts/                       # Prompt templates
│   ├── index.ts                   # Prompt registry
│   └── research-analysis-prompt.ts # Multi-methodology prompts
├── services/                      # Business logic
│   ├── elicitation.ts             # Interactive guidance
│   ├── sampling.ts                # Data sampling
│   └── example.ts                 # Example service
└── utils/                         # Utilities
    ├── logger.ts                  # Logging system
    └── health.ts                  # Health monitoring
```

### Architecture Benefits

- 🏗️ **Modular Design** - Each component has single responsibility
- 🔧 **Easy Testing** - Individual modules can be tested in isolation  
- 📈 **Scalable** - Easy to add new tools, resources, and features
- 🧠 **Maintainable** - Clear separation of concerns
- 🎯 **Educational** - Demonstrates MCP best practices

## 🚀 Deployment

### Docker Deployment

```dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["npm", "start"]
```

### Environment-Specific Configs

#### Development
```bash
npm run dev:http
```

#### Staging
```bash
npm run build
NODE_ENV=staging npm run start:http
```

#### Production
```bash
npm run build
NODE_ENV=production npm run start:http:oauth
```

## 📖 MCP Protocol Information

This server implements the Model Context Protocol specification:

- **Protocol Version**: 2025-03-26 (Streamable HTTP)
- **Backwards Compatibility**: SSE fallback for legacy clients
- **Capabilities**: Tools, Resources, Prompts, Sampling, Elicitation
- **Transports**: Stdio, HTTP, Streamable HTTP

### Client Integration

#### Claude Desktop

Add to your Claude Desktop config:

```json
{
  "mcpServers": {
    "{{PROJECT_NAME}}": {
      "command": "node",
      "args": ["path/to/{{PROJECT_NAME}}/dist/server.js"],
      "env": {
        "MCP_TRANSPORT": "stdio"
      }
    }
  }
}
```

#### MCP Inspector Integration

Perfect for testing and development:

```bash
# Visual testing in browser
npm run inspector

# CLI testing for automation
npm run inspector:cli

# Test specific capabilities
npm run test:tools
npm run test:resources
npm run test:prompts
```

#### HTTP Clients

```bash
# Initialize connection
curl -X POST http://localhost:3000/mcp \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0.0"}}}'
```

## 🔍 **MCP Inspector Features**

This project includes full integration with the [MCP Inspector](https://github.com/modelcontextprotocol/inspector) for comprehensive testing:

### Visual Testing (UI Mode)
- 🖥️ Interactive browser interface for exploring capabilities
- 📊 Real-time tool execution with parameter forms
- 📋 Resource browser with JSON visualization  
- 💡 Prompt testing with streaming responses
- 🔍 Request history and error visualization
- ⚙️ Configuration management

### Command Line Testing (CLI Mode)
- 🤖 Programmatic interaction for automation
- 🔄 Perfect for CI/CD pipelines
- 🧪 Scriptable testing and validation
- 📝 Machine-readable JSON output
- 🔧 Integration with coding assistants

### Available Inspector Commands

```bash
# UI Mode - Visual testing
npm run inspector                    # Launch browser interface
npm run inspector:http              # Test HTTP transport

# CLI Mode - Programmatic testing  
npm run inspector:cli               # Test via command line
npm run inspector:built             # Test built version

# Quick Tests - Specific endpoints
npm run test:tools                  # List and test tools
npm run test:resources              # Browse resources
npm run test:prompts                # Test prompts

# Example: Test data analysis tool
npx @modelcontextprotocol/inspector --cli tsx src/server.ts \
  --method tools/call \
  --tool-name data-analysis \
  --tool-arg 'data=[{"score":85},{"score":92}]' \
  --tool-arg analysis_type=exploratory
```

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch: `git checkout -b feature/amazing-feature`
3. Make your changes
4. Add tests for your changes
5. Run the test suite: `npm test`
6. Commit your changes: `git commit -m 'Add amazing feature'`
7. Push to the branch: `git push origin feature/amazing-feature`
8. Open a Pull Request

### Development Guidelines

- Write TypeScript with strict mode
- Add comprehensive tests for new features
- Update documentation for API changes
- Follow the existing code style
- Use conventional commit messages

## 📄 License

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

## 🙏 Acknowledgments

- [Model Context Protocol](https://modelcontextprotocol.io/) - The protocol specification and community
- [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) - The official TypeScript SDK
- [MCP Inspector](https://github.com/modelcontextprotocol/inspector) - Visual testing tool for MCP servers
- Built with [create-mcp](https://github.com/LinuxDevil/Create-MCP) - Modern MCP server generator

## ✨ **Why This Architecture?**

This project demonstrates **production-ready MCP development** with:

- 🎯 **One comprehensive example** instead of confusing scattered demos
- 🏗️ **Clean separation of concerns** for maintainable code
- 📚 **Educational value** showing how all MCP features work together
- 🔧 **Real-world applicability** with practical data analysis use case
- 🧪 **Built-in testing** with MCP Inspector integration
- 📈 **Scalable foundation** for building complex MCP servers

Perfect for learning MCP development, building production servers, or as a foundation for custom implementations.

---

**Generated with [create-mcp](https://github.com/LinuxDevil/Create-MCP)** - The modern CLI for creating Model Context Protocol servers with unified architecture and integrated testing.