# MCP Development Rules & Context for test-claude-md-placement

## Project Overview
- **Generated by**: KEN-MCP v3.6.0  
- **Project Name**: test-claude-md-placement
- **Purpose**: MCP server for: Create a simple test MCP with basic file operations
- **Original Requirements**: Create a simple test MCP with basic file operations
- **Tools**: 3 tools (read_file, write_file, list_directory)
- **Resources**: 3 resources (files://recent, dirs://structure, system://status)

## What is MCP (Model Context Protocol)
MCP is a standardized protocol that allows AI models like Claude to interact with external tools and resources through a JSON-RPC interface. Key concepts:

- **Communication**: Bidirectional JSON-RPC 2.0 over stdio (stdin/stdout)
- **Process Model**: Claude Code launches the MCP server as a subprocess
- **Protocol Flow**: Claude sends JSON-RPC requests → MCP server processes → Returns JSON-RPC responses
- **Critical Constraint**: ONLY valid JSON-RPC messages can go to stdout

## What is FastMCP
FastMCP is a Python framework that dramatically simplifies MCP server development:

- **Protocol Handling**: Automatically manages JSON-RPC 2.0 communication
- **Decorators**: Use @mcp.tool and @mcp.resource for easy function registration  
- **Async Support**: Built-in support for async operations
- **Error Handling**: Proper error responses without breaking the protocol
- **Stdio Management**: Handles stdin/stdout correctly when used properly

## CRITICAL RULES (NEVER VIOLATE)

### 1. Stdout Protocol Rules
- **NEVER** use `print()` statements - they corrupt the JSON-RPC stream
- **NEVER** output anything to stdout except through FastMCP
- **NEVER** allow exceptions to reach stdout unhandled
- **ALWAYS** let FastMCP handle all stdout communication

### 2. Logging Rules  
- **ALWAYS** use `logger.info()`, `logger.error()`, `logger.debug()` for output
- **ALL** logging goes to stderr (FastMCP configures this automatically)
- **NEVER** redirect or modify the logging setup in server.py
- **USE** structured logging for debugging: `logger.info("Action completed", extra={"key": "value"})`

### 3. Error Handling Rules
- **ALWAYS** catch exceptions in tool functions
- **RETURN** error messages as strings, not raise exceptions
- **VALIDATE** all inputs before processing
- **HANDLE** edge cases gracefully with meaningful error messages

### 4. Implementation Rules
- **REPLACE** all TODO comments with actual implementation
- **REMOVE** all placeholder/mock data (verify.py will catch these)
- **IMPLEMENT** real business logic, not just return empty containers
- **TEST** thoroughly with test.py before considering complete

## Understanding This MCP Server

### Generated Tools
- **read_file**: Read operation for file.
- **write_file**: Write operation for file.
- **list_directory**: List operation for directory.

**Note**: Each tool has detailed implementation requirements in server.py. The above are concise summaries.

### Generated Resources  
- **files://recent**: Recently accessed files - TODO: Implement based on requirements
- **dirs://structure**: Directory structure information - TODO: Implement based on requirements
- **system://status**: System status for file_system - TODO: Implement health checks

### Architecture
- **Server Entry**: server.py contains the FastMCP server
- **Protocol**: JSON-RPC 2.0 over stdio
- **Logging**: All logs go to stderr via Python logging
- **Testing**: test.py validates functionality
- **Verification**: verify.py checks for incomplete implementations
- **Diagnostics**: diagnose.py troubleshoots connection issues

## Implementation Workflow

### 1. Understand the Requirements
- Read the original requirements: Create a simple test MCP with basic file operations
- Identify what each tool should actually do
- Understand the expected inputs and outputs

### 2. Replace Placeholders
- Find all "TODO: Claude, implement..." comments
- Replace mock data with real implementations  
- Remove hardcoded IDs like "generated-id"
- Implement actual business logic

### 3. Test Continuously
```bash
python3 test.py     # Run functionality tests
python3 verify.py   # Check for incomplete implementations  
python3 diagnose.py # Debug connection issues
```

### 4. Validation Patterns
- **Strings**: Check for empty/null, validate format, sanitize input
- **Numbers**: Validate range, check for NaN/infinity
- **Objects**: Verify required fields exist and have correct types
- **Arrays**: Check bounds, validate each element

## Common Implementation Patterns

### Tool Functions
```python
@mcp.tool()
async def my_tool(ctx: Context, param: str) -> str:
    # 1. Validate inputs
    if not param or not isinstance(param, str):
        return "Error: param must be a non-empty string"
    
    # 2. Log the operation (goes to stderr)
    await ctx.info(f"Processing tool request with param: {param}")
    
    # 3. Implement business logic
    try:
        result = await some_async_operation(param)
        return result
    except Exception as e:
        # 4. Handle errors gracefully
        await ctx.error(f"Tool failed: {e}")
        return f"Error: {str(e)}"
```

### Resource Functions
```python
@mcp.resource("scheme://resource-name")
async def my_resource(ctx: Context) -> str:
    try:
        # Implement resource logic
        data = await fetch_resource_data()
        return json.dumps(data)
    except Exception as e:
        await ctx.error(f"Resource failed: {e}")
        return json.dumps({"error": str(e)})
```

## Platform Considerations

### Command Differences
- **Windows**: Use `py` instead of `python3`
- **macOS/Linux**: Use `python3` 
- **All Platforms**: The shebang line is auto-generated correctly

### Path Handling
```python
from pathlib import Path
# Cross-platform path handling
data_dir = Path.home() / ".mcp_data" / "my_app"
data_dir.mkdir(parents=True, exist_ok=True)
```

## Debugging Guidelines

### Connection Issues
1. **Run Diagnostics**: `python3 diagnose.py` checks common problems
2. **Check Logs**: Look for stderr output when starting the server
3. **Validate Syntax**: Ensure no Python syntax errors
4. **Test Manually**: Run `python3 server.py` and look for startup errors

### Test Failures
1. **Read Error Messages**: test.py provides detailed failure information
2. **Check Implementation**: Ensure tools return expected data types
3. **Validate Logic**: Verify business logic matches requirements
4. **Fix Incrementally**: Address one test failure at a time

### Verification Issues
1. **Run verify.py**: Identifies TODOs, placeholders, and hardcoded values
2. **Address Each Issue**: Replace placeholders with real implementations
3. **Re-run Verification**: Ensure all issues are resolved
4. **Test Again**: Verify functionality still works after changes

## FastMCP Best Practices

### Async Operations
```python
# Good: Proper async handling
async def process_data(data):
    async with aiohttp.ClientSession() as session:
        response = await session.get(url)
        return await response.json()

# Bad: Blocking operations in async functions
async def bad_process(data):
    time.sleep(5)  # Blocks the event loop
    return data
```

### Error Responses
```python
# Good: Return error strings
@mcp.tool()
async def my_tool(ctx: Context, param: str) -> str:
    if not param:
        return "Error: param is required"
    return f"Processed: {param}"

# Bad: Raise exceptions  
@mcp.tool()
async def bad_tool(ctx: Context, param: str) -> str:
    if not param:
        raise ValueError("param is required")  # Breaks protocol
```

## Claude Code Workflow Commands

### MCP Management
```bash
# Add an MCP to Claude Code
claude mcp add <name> <command>

# Remove an MCP from Claude Code  
claude mcp remove <name>

# List all configured MCPs and their status
claude mcp list

# Continue a conversation after restart
claude --continue
```

### Critical Workflow Rule
**⚠️ IMPORTANT**: Whenever you make changes to ANY MCP server code:
1. Save your changes
2. **ALWAYS** request a restart: "Please restart Claude Code for these changes to take effect"  
3. After restart, use `claude --continue` to continue the conversation
4. Changes will NOT work until Claude Code is restarted!

This applies to:
- Modifying server.py implementations
- Fixing bugs or adding features
- Any code changes in the MCP directory

### Example MCP Management Workflow
```bash
# 1. Add your MCP
claude mcp add my-project "/path/to/project/run_server.py"

# 2. Check it was added
claude mcp list

# 3. Restart Claude Code (changes won't work until restart!)
# Exit and restart Claude Code application

# 4. After restart, verify connection
claude mcp list  # Should show "Active ✓"

# 5. Continue previous conversation if needed
claude --continue
```

## Remember
- You are building a server that Claude communicates with via JSON-RPC
- The protocol is strict - any stdout pollution breaks everything
- FastMCP handles the protocol layer - focus on implementing the business logic
- All generated code has structure but needs real implementation
- Use the verification tools to ensure completeness
- Test thoroughly before considering the implementation complete
- **ALWAYS request restart after MCP changes before expecting them to work!**

## Success Criteria
✅ All tests in test.py pass  
✅ verify.py reports no remaining issues  
✅ diagnose.py shows no connection problems  
✅ MCP connects successfully in Claude Code  
✅ All placeholder code has been replaced with real implementations  
✅ Error cases are handled gracefully  
✅ Logging goes to stderr only
