API.mdā¢9.37 kB
# MCP Self-Learning Server API Documentation
## š REST API Reference
Base URL: `http://localhost:8765`
### Authentication
Currently supports optional token-based authentication. Configure in server settings.
```bash
curl -H "Authorization: Bearer YOUR_TOKEN" http://localhost:8765/endpoint
```
## š” Core Endpoints
### Health & Status
#### `GET /health`
Get server health status.
**Response:**
```json
{
"status": "healthy",
"uptime": 123456,
"requests": 42,
"memory": {
"rss": 86380544,
"heapTotal": 22167552,
"heapUsed": 15762544
},
"mcpServer": "running"
}
```
#### `GET /status`
Get detailed server status.
**Response:**
```json
{
"running": true,
"uptime": 123456,
"requests": 42,
"websocketConnections": 2,
"memory": { "rss": 86827008, "heapTotal": 22691840 },
"learning": {
"active": true,
"patterns": 15,
"knowledge": 8,
"cycles": 3,
"memoryBuffer": 250
},
"persistence": {
"enabled": true,
"lastSave": "2024-08-29T18:40:54.123Z"
}
}
```
### Learning Operations
#### `POST /analyze`
Analyze an interaction pattern for learning.
**Request Body:**
```json
{
"interaction": {
"type": "tool_usage",
"input": "User query or command",
"output": "Agent response or result",
"success": true,
"context": {
"sourceAgent": "claudio-agent-1",
"workflowId": "workflow-123",
"metadata": {}
}
}
}
```
**Response:**
```json
{
"success": true,
"patternId": "uuid-pattern-id",
"features": {
"toolSequence": ["analyze", "respond"],
"contextualCues": {
"domain": "general",
"intent": "query",
"entities": [],
"sentiment": "neutral"
},
"performanceMetrics": {
"responseTime": 150,
"accuracy": 0.95,
"efficiency": 0.87
},
"semanticEmbedding": [0.1, 0.2, 0.3, ...],
"temporalPatterns": {
"timeOfDay": "morning",
"dayOfWeek": 1,
"isWeekend": false
}
},
"recommendations": ["suggestion1", "suggestion2"]
}
```
#### `GET /insights`
Get learning insights and analytics.
**Response:**
```json
{
"success": true,
"insights": {
"metrics": {
"totalInteractions": 150,
"successRate": 0.92,
"averageResponseTime": 200,
"toolUsageFrequency": {
"analyze": 45,
"generate": 32,
"search": 28
},
"errorPatterns": {
"timeout": 3,
"validation": 5
},
"learningCycles": 8
},
"topPatterns": [
{
"key": "query:analysis:successful",
"confidence": 0.95,
"count": 25
}
],
"topTools": [
{"tool": "analyze", "count": 45}
],
"knowledgeItems": 12,
"recommendations": [
"Consider optimizing response time for analyze tool",
"Pattern 'query:analysis' shows high success rate"
]
},
"uptime": 123456,
"memoryUsage": {
"rss": 88834048,
"heapTotal": 24526848
}
}
```
#### `POST /learn`
Trigger a manual learning cycle.
**Response:**
```json
{
"success": true,
"cycleId": "cycle-uuid",
"patternsProcessed": 15,
"optimizationsFound": 3,
"duration": 450
}
```
### Optimization & Prediction
#### `GET /optimize?tool_name=TOOL_NAME`
Get optimization suggestions.
**Query Parameters:**
- `tool_name` (optional): Specific tool to optimize
**Response:**
```json
{
"success": true,
"suggestions": [
{
"type": "performance",
"tool": "analyze",
"description": "Consider caching frequent queries",
"estimatedImpact": 0.25,
"implementation": {
"difficulty": "medium",
"estimatedEffort": "2-4 hours"
}
}
],
"confidence": 0.87
}
```
#### `POST /predict`
Predict next actions based on context.
**Request Body:**
```json
{
"context": {
"currentTool": "analyze",
"workflowState": "processing",
"userIntent": "data_analysis",
"history": ["search", "analyze"]
}
}
```
**Response:**
```json
{
"success": true,
"predictions": [
{
"action": "generate_report",
"confidence": 0.85,
"reasoning": "Pattern indicates report generation follows analysis",
"suggestedTool": "report_generator"
}
],
"confidence": 0.82
}
```
### Data Management
#### `GET /export?format=json`
Export learned knowledge.
**Query Parameters:**
- `format`: Export format (`json`, `csv`)
**Response:**
```json
{
"success": true,
"data": {
"patterns": [...],
"knowledge": [...],
"metadata": {
"exportTime": "2024-08-29T18:40:54.123Z",
"version": "1.0.0"
}
}
}
```
#### `POST /import`
Import knowledge from external source.
**Request Body:**
```json
{
"data": {
"patterns": [...],
"knowledge": [...],
"metadata": {}
}
}
```
#### `GET /metrics?tool_name=TOOL_NAME`
Get performance metrics.
**Response:**
```json
{
"success": true,
"metrics": {
"responseTime": {
"average": 200,
"min": 50,
"max": 800,
"p95": 400
},
"successRate": {
"overall": 0.92,
"byTool": {
"analyze": 0.95,
"generate": 0.88
}
},
"resourceUsage": {
"memory": 85.3,
"cpu": 12.5
},
"errorPatterns": {
"timeout": 2,
"validation": 3
}
}
}
```
## š WebSocket API
Connect to `ws://localhost:8765/ws` for real-time updates.
### Events Received
#### `welcome`
Connection established.
```json
{
"type": "welcome",
"message": "Connected to MCP Self-Learning Server",
"serverId": "server-uuid"
}
```
#### `pattern_analyzed`
New pattern analyzed.
```json
{
"type": "pattern_analyzed",
"data": {
"patternId": "uuid",
"type": "tool_usage",
"success": true,
"timestamp": "2024-08-29T18:40:54.123Z"
}
}
```
#### `learning_cycle_completed`
Learning cycle finished.
```json
{
"type": "learning_cycle_completed",
"data": {
"cycleId": "cycle-uuid",
"patternsProcessed": 15,
"optimizations": 3,
"duration": 450
}
}
```
#### `insights_updated`
Learning insights updated.
```json
{
"type": "insights_updated",
"data": {
"totalPatterns": 156,
"newRecommendations": 2
}
}
```
## š Client Libraries
### Node.js Client
```javascript
import SelfLearningClient from './lib/self-learning-client.js';
const client = new SelfLearningClient({
port: 8765,
timeout: 30000,
retryAttempts: 3
});
// Connect and analyze
await client.connect();
const result = await client.analyzePattern({
type: 'interaction',
input: 'user query',
output: 'response',
success: true
});
// Real-time updates
await client.connectWebSocket();
client.on('pattern_analyzed', (data) => {
console.log('New pattern:', data);
});
// Batch operations
const results = await client.analyzeMultiplePatterns(interactions);
// Learning sessions
const session = client.createLearningSession('session-id');
session.addInteraction(interaction);
const summary = await session.analyzeSession();
```
### Python Client
```python
from lib.self_learning_client import SelfLearningClient
client = SelfLearningClient(base_url="http://localhost:8765")
# Connect and analyze
await client.connect()
result = await client.analyze_voice_interaction(
"What's the weather?",
"It's sunny, 75°F",
{"intent": "weather", "confidence": 0.95},
True
)
# Get insights
insights = await client.get_insights()
# Performance metrics
metrics = await client.get_performance_metrics()
```
## š§ MCP Tools (for Claudio Integration)
### Available Tools
1. **learn_from_interaction**
- Learn from agent interactions
- Improves future performance
2. **get_learning_insights**
- Get learning analytics
- Provides recommendations
3. **optimize_workflow**
- Optimize agent workflows
- Suggests improvements
4. **predict_next_action**
- Predict workflow next steps
- Guides agent decisions
5. **learn_from_workflow_outcome**
- Learn from complete workflows
- Improves workflow patterns
6. **get_agent_performance_metrics**
- Get agent performance data
- Monitors efficiency
### Tool Registration (Claudio)
```javascript
import { ClaudioMCPLearningTools } from './integrations/claudio-mcp-tools.js';
const learningTools = new ClaudioMCPLearningTools();
await learningTools.initialize();
// Get tool definitions for MCP server registration
const tools = learningTools.getToolDefinitions();
// Handle tool calls
const result = await learningTools.handleToolCall('learn_from_interaction', {
agent_id: 'my-agent',
input: 'user request',
output: 'agent response',
success: true
});
```
## ā ļø Error Responses
All endpoints return consistent error formats:
```json
{
"success": false,
"error": "Error message",
"code": "ERROR_CODE",
"details": {
"field": "Additional error details"
}
}
```
### Common Error Codes
- `INVALID_REQUEST`: Malformed request body
- `MISSING_PARAMETER`: Required parameter missing
- `LEARNING_ERROR`: Error in learning process
- `SERVER_ERROR`: Internal server error
- `AUTH_ERROR`: Authentication failed
## š Rate Limits
Default limits (configurable):
- **API Requests**: 100 requests/minute
- **WebSocket Messages**: 1000 messages/minute
- **Analysis Requests**: 50 requests/minute
Rate limit headers included in responses:
```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1632150000
```