# MCP Direct HTTP Endpoint Documentation

## Overview

The Direct endpoint (`/OpenForum/AddOn/ClaudeMCP/Direct`) provides a standard HTTP POST interface for interacting with the OpenForum MCP server using the Model Context Protocol (MCP).

**Version**: 2.0
**Protocol**: MCP 2024-11-05 (Legacy JSON-RPC over HTTP)
**Last Updated**: 2025-10-18

---

## Endpoint Details

### Base Information
- **URL**: `/OpenForum/AddOn/ClaudeMCP/Direct`
- **Method**: POST only
- **Protocol**: HTTP/1.1
- **Encoding**: UTF-8
- **Format**: JSON-RPC 2.0

### Request Requirements

#### Required Headers
```http
POST /OpenForum/AddOn/ClaudeMCP/Direct HTTP/1.1
Content-Type: application/json
Accept: application/json
```

#### Optional Headers
```http
Accept: text/event-stream  # For future SSE support
Accept: */*                # Wildcard also accepted
```

---

## Request Format

### JSON-RPC 2.0 Structure

All requests must follow the JSON-RPC 2.0 specification:

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "method_name",
  "params": {
    "param1": "value1",
    "param2": "value2"
  }
}
```

### Supported Methods

#### 1. initialize
Initialize the MCP connection.

**Request**:
```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "initialize",
  "params": {
    "protocolVersion": "2024-11-05",
    "capabilities": {},
    "clientInfo": {
      "name": "my-client",
      "version": "1.0.0"
    }
  }
}
```

**Response**:
```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
      "tools": {"listChanged": true},
      "prompts": {"listChanged": true},
      "resources": {"listChanged": true}
    },
    "serverInfo": {
      "name": "open-forum",
      "version": "1.0.0"
    }
  }
}
```

#### 2. tools/list
List all available MCP tools.

**Request**:
```json
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/list",
  "params": {}
}
```

**Response**:
```json
{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "tools": [
      {
        "name": "pageBuilder",
        "description": "Create OpenForum pages...",
        "inputSchema": {
          "type": "object",
          "properties": {...},
          "required": [...]
        }
      }
    ]
  }
}
```

#### 3. tools/call
Execute a specific tool.

**Request**:
```json
{
  "jsonrpc": "2.0",
  "id": 3,
  "method": "tools/call",
  "params": {
    "name": "pageBuilder",
    "arguments": {
      "action": "read",
      "page_name": "OpenForum/AddOn/ClaudeMCP"
    }
  }
}
```

**Response**:
```json
{
  "jsonrpc": "2.0",
  "id": 3,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "SUCCESS: Page content retrieved..."
      }
    ]
  }
}
```

#### 4. prompts/list
List all available prompts.

**Request**:
```json
{
  "jsonrpc": "2.0",
  "id": 4,
  "method": "prompts/list",
  "params": {}
}
```

#### 5. prompts/get
Get a specific prompt.

**Request**:
```json
{
  "jsonrpc": "2.0",
  "id": 5,
  "method": "prompts/get",
  "params": {
    "name": "prompt_name",
    "arguments": {}
  }
}
```

#### 6. resources/list
List all available resources.

**Request**:
```json
{
  "jsonrpc": "2.0",
  "id": 6,
  "method": "resources/list",
  "params": {}
}
```

#### 7. resources/read
Read a specific resource.

**Request**:
```json
{
  "jsonrpc": "2.0",
  "id": 7,
  "method": "resources/read",
  "params": {
    "uri": "resource://example"
  }
}
```

---

## Response Format

### Successful Response
```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    // Method-specific result data
  }
}
```

### Error Response
```json
{
  "error": "Error message",
  "details": "Additional error details (optional)"
}
```

---

## HTTP Status Codes

| Code | Meaning | When Used |
|------|---------|-----------|
| 200 OK | Success | Request processed successfully |
| 400 Bad Request | Client Error | Invalid headers, empty body, invalid JSON |
| 405 Method Not Allowed | Method Error | Non-POST request |
| 500 Internal Server Error | Server Error | Processing error, MCP handler failure |

---

## Validation Steps

The endpoint performs the following validation in order:

1. **HTTP Method Check** - Must be POST
2. **Content-Type Validation** - Must include `application/json`
3. **Accept Header Check** - Should include `application/json` or `text/event-stream`
4. **Request Body Read** - UTF-8 encoded
5. **Empty Body Check** - Body must not be empty
6. **JSON Syntax Validation** - Must be valid JSON
7. **MCP Processing** - Handled by Claude.sjs
8. **Response Validation** - Ensures valid response

---

## Error Examples

### Missing Content-Type Header
```http
POST /OpenForum/AddOn/ClaudeMCP/Direct HTTP/1.1

{...}
```

**Response** (400 Bad Request):
```json
{
  "error": "Bad Request",
  "details": "Content-Type header is required"
}
```

### Invalid Content-Type
```http
POST /OpenForum/AddOn/ClaudeMCP/Direct HTTP/1.1
Content-Type: text/plain

{...}
```

**Response** (400 Bad Request):
```json
{
  "error": "Bad Request",
  "details": "Content-Type must be application/json, got: text/plain"
}
```

### Empty Request Body
```http
POST /OpenForum/AddOn/ClaudeMCP/Direct HTTP/1.1
Content-Type: application/json

```

**Response** (400 Bad Request):
```json
{
  "error": "Bad Request",
  "details": "Request body is empty"
}
```

### Invalid JSON
```http
POST /OpenForum/AddOn/ClaudeMCP/Direct HTTP/1.1
Content-Type: application/json

{invalid json}
```

**Response** (400 Bad Request):
```json
{
  "error": "Bad Request",
  "details": "Invalid JSON: ..."
}
```

---

## Example Usage

### Using cURL

```bash
# Initialize MCP connection
curl -X POST http://localhost/OpenForum/AddOn/ClaudeMCP/Direct \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
      "protocolVersion": "2024-11-05",
      "capabilities": {},
      "clientInfo": {"name": "curl-client", "version": "1.0"}
    }
  }'

# List available tools
curl -X POST http://localhost/OpenForum/AddOn/ClaudeMCP/Direct \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/list",
    "params": {}
  }'

# Call a tool
curl -X POST http://localhost/OpenForum/AddOn/ClaudeMCP/Direct \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 3,
    "method": "tools/call",
    "params": {
      "name": "pageBuilder",
      "arguments": {
        "action": "read",
        "page_name": "OpenForum/AddOn/ClaudeMCP"
      }
    }
  }'
```

### Using JavaScript (Fetch API)

```javascript
// Initialize MCP
async function initializeMCP() {
  const response = await fetch('/OpenForum/AddOn/ClaudeMCP/Direct', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    body: JSON.stringify({
      jsonrpc: '2.0',
      id: 1,
      method: 'initialize',
      params: {
        protocolVersion: '2024-11-05',
        capabilities: {},
        clientInfo: {
          name: 'web-client',
          version: '1.0.0'
        }
      }
    })
  });

  return await response.json();
}

// List tools
async function listTools() {
  const response = await fetch('/OpenForum/AddOn/ClaudeMCP/Direct', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    body: JSON.stringify({
      jsonrpc: '2.0',
      id: 2,
      method: 'tools/list',
      params: {}
    })
  });

  return await response.json();
}

// Call a tool
async function callTool(toolName, args) {
  const response = await fetch('/OpenForum/AddOn/ClaudeMCP/Direct', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    body: JSON.stringify({
      jsonrpc: '2.0',
      id: 3,
      method: 'tools/call',
      params: {
        name: toolName,
        arguments: args
      }
    })
  });

  return await response.json();
}
```

### Using Python (requests)

```python
import requests
import json

BASE_URL = 'http://localhost/OpenForum/AddOn/ClaudeMCP/Direct'

def mcp_request(method, params, request_id=1):
    """Send MCP request to Direct endpoint"""
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    payload = {
        'jsonrpc': '2.0',
        'id': request_id,
        'method': method,
        'params': params
    }

    response = requests.post(BASE_URL, headers=headers, json=payload)
    return response.json()

# Initialize
init_response = mcp_request('initialize', {
    'protocolVersion': '2024-11-05',
    'capabilities': {},
    'clientInfo': {'name': 'python-client', 'version': '1.0'}
})

# List tools
tools_response = mcp_request('tools/list', {})

# Call tool
call_response = mcp_request('tools/call', {
    'name': 'pageBuilder',
    'arguments': {
        'action': 'read',
        'page_name': 'OpenForum/AddOn/ClaudeMCP'
    }
})
```

---

## Improvements in Version 2.0

### What's New

1. **✓ Comprehensive Header Validation**
   - Content-Type header validation
   - Accept header validation (lenient mode)
   - Proper HTTP method checking

2. **✓ Robust Error Handling**
   - Try/catch blocks at every step
   - Detailed error messages
   - Proper HTTP status codes

3. **✓ Input Validation**
   - Empty body detection
   - JSON syntax validation
   - Response validation

4. **✓ Resource Management**
   - Proper stream closing (try/finally)
   - No resource leaks

5. **✓ Clear Error Messages**
   - Structured error responses
   - Detailed error context
   - Helpful for debugging

6. **✓ Proper HTTP Status Codes**
   - 200 for success
   - 400 for bad requests
   - 405 for wrong method
   - 500 for server errors

7. **✓ Documentation**
   - Inline code comments
   - Step-by-step processing
   - Clear validation flow

---

## Troubleshooting

### "Content-Type header is required"
**Solution**: Add `Content-Type: application/json` header to your request

### "Request body is empty"
**Solution**: Ensure you're sending a valid JSON body in the POST request

### "Invalid JSON"
**Solution**: Validate your JSON syntax using a JSON validator

### "MCP handler error"
**Solution**: Check the MCP request format - ensure it follows JSON-RPC 2.0 spec

### "Method Not Allowed"
**Solution**: Use POST method only, not GET

---

## Security Considerations

1. **Input Validation**: All inputs are validated before processing
2. **Error Handling**: Errors don't expose internal system details
3. **UTF-8 Encoding**: Prevents encoding-based attacks
4. **JSON Validation**: Prevents malformed JSON attacks
5. **Resource Cleanup**: Prevents resource exhaustion

---

## Future Enhancements

Potential improvements for future versions:

1. **Rate Limiting**: Prevent abuse
2. **Authentication**: API key or OAuth support
3. **Request Logging**: Audit trail
4. **CORS Support**: Cross-origin requests
5. **SSE Streaming**: Server-sent events for long-running operations
6. **Batch Requests**: Support JSON-RPC batch arrays
7. **Protocol Upgrade**: Support MCP 2025-03-26 Streamable HTTP

---

## References

- [Model Context Protocol Specification](https://modelcontextprotocol.io)
- [JSON-RPC 2.0 Specification](https://www.jsonrpc.org/specification)
- OpenForum MCP Documentation: `/OpenForum/AddOn/ClaudeMCP`

---

## Version History

**v2.0** (2025-10-18)
- Complete rewrite with proper validation
- Added comprehensive error handling
- Improved HTTP status codes
- Added header validation
- Resource management improvements
- Full documentation

**v1.0** (Initial)
- Basic POST handler
- Minimal error handling
- No validation

---

**Last Updated**: 2025-10-18
**Author**: Claude AI Assistant
**Location**: `/OpenForum/AddOn/ClaudeMCP/Direct/DIRECT-ENDPOINT-DOCS.md`
