API REST
Documentación de la API REST del Agent Backend
API REST
La API REST de MKS DevEnv permite gestionar workspaces programáticamente.
Base URL
https://lab1-helsinki.api.mks2508.systemsPara desarrollo local:
http://localhost:3100Autenticación
La API usa JWT Bearer tokens para autenticación.
curl -H "Authorization: Bearer YOUR_TOKEN" \
https://lab1-helsinki.api.mks2508.systems/api/workspacesObtener Token
Los tokens se generan en la configuración del Agent Backend:
# En el servidor
export DEVENV_API_SECRET=$(openssl rand -hex 32)
# Iniciar backend con el secret
DEVENV_API_SECRET=$DEVENV_API_SECRET bun run agent-backendEndpoints
Workspaces
Listar Workspaces
GET /api/workspacesQuery Parameters:
| Parámetro | Tipo | Default | Descripción |
|---|---|---|---|
status | string | Filtrar por estado (running, stopped) | |
type | string | Filtrar por tipo (persistent, temporary) |
Response:
{
"workspaces": [
{
"id": "myproject",
"name": "myproject",
"status": "running",
"port": 8443,
"template": "bun-typescript",
"type": "persistent",
"containerId": "abc123def456",
"createdAt": "2024-01-15T10:30:00Z",
"urls": {
"codeServer": "http://localhost:8443",
"rdp": "rdp://localhost:3389",
"ssh": "ssh root@localhost -p 2223"
}
}
]
}Crear Workspace
POST /api/workspaces
Content-Type: application/jsonBody:
{
"name": "myproject",
"template": "bun-typescript",
"type": "persistent",
"port": 8443,
"repo": {
"url": "https://github.com/user/repo.git",
"branch": "main"
}
}| Campo | Tipo | Requerido | Descripción |
|---|---|---|---|
name | string | ✓ | Nombre único del workspace |
template | string | Template a usar (default: bun-typescript) | |
type | string | persistent o temporary (default: persistent) | |
port | number | Puerto específico (default: auto) | |
repo | object | Configuración de repo Git |
Response: 201 Created
{
"id": "myproject",
"name": "myproject",
"status": "creating",
"port": 8443,
"template": "bun-typescript",
"type": "persistent",
"createdAt": "2024-01-15T10:30:00Z"
}Obtener Workspace
GET /api/workspaces/{id}Response: 200 OK
{
"id": "myproject",
"name": "myproject",
"status": "running",
"port": 8443,
"template": "bun-typescript",
"type": "persistent",
"containerId": "abc123def456",
"createdAt": "2024-01-15T10:30:00Z",
"urls": {
"codeServer": "http://localhost:8443",
"rdp": "rdp://localhost:3389",
"ssh": "ssh root@localhost -p 2223"
},
"stats": {
"cpu": "15%",
"memory": "2.1GB / 4GB",
"disk": "12.3GB / 50GB"
}
}Iniciar Workspace
POST /api/workspaces/{id}/startResponse: 200 OK
{
"id": "myproject",
"status": "starting"
}Detener Workspace
POST /api/workspaces/{id}/stopQuery Parameters:
| Parámetro | Tipo | Default | Descripción |
|---|---|---|---|
force | boolean | false | Forzar detención (SIGKILL) |
Response: 200 OK
{
"id": "myproject",
"status": "stopping"
}Reiniciar Workspace
POST /api/workspaces/{id}/restartResponse: 200 OK
{
"id": "myproject",
"status": "restarting"
}Eliminar Workspace
DELETE /api/workspaces/{id}Query Parameters:
| Parámetro | Tipo | Default | Descripción |
|---|---|---|---|
volumes | boolean | false | También eliminar volúmenes |
Response: 200 OK
{
"id": "myproject",
"deleted": true
}Logs
Obtener Logs
GET /api/workspaces/{id}/logsQuery Parameters:
| Parámetro | Tipo | Default | Descripción |
|---|---|---|---|
tail | number | 50 | Número de líneas |
follow | boolean | false | Stream logs en tiempo real |
service | string | Servicio específico |
Response: 200 OK
{
"logs": [
{
"timestamp": "2024-01-15T10:30:00Z",
"service": "codeserver",
"level": "info",
"message": "Code-Server started on port 8443"
}
]
}Stream (follow=true):
Server-Sent Events (SSE) stream:
data: {"timestamp":"2024-01-15T10:30:01Z","service":"codeserver","level":"info","message":"User connected"}
data: {"timestamp":"2024-01-15T10:30:02Z","service":"codeserver","level":"info","message":"File edited: /workspace/index.ts"}Exec
Ejecutar Comando
POST /api/workspaces/{id}/exec
Content-Type: application/jsonBody:
{
"command": "bun test",
"workdir": "/workspace",
"timeout": 30000
}Response: 200 OK
{
"exitCode": 0,
"stdout": "✓ All tests passed",
"stderr": "",
"duration": 5234
}Agent Sessions
Crear Sesión de Agent
POST /api/agent/sessions
Content-Type: application/json
Authorization: Bearer YOUR_TOKENBody:
{
"workspaceId": "myproject",
"model": "claude-4",
"context": {
"task": "code-review",
"prNumber": 123
}
}Response: 201 Created
{
"id": "sess_abc123",
"workspaceId": "myproject",
"model": "claude-4",
"status": "active",
"createdAt": "2024-01-15T10:30:00Z",
"messages": []
}Enviar Mensaje
POST /api/agent/sessions/{id}/messages
Content-Type: application/jsonBody:
{
"message": "Analiza el PR #123 y encuentra bugs",
"stream": true
}Response (stream=false): 200 OK
{
"id": "msg_xyz789",
"role": "assistant",
"content": "He analizado el PR y encontrado...",
"finishReason": "stop",
"usage": {
"promptTokens": 1234,
"completionTokens": 567,
"totalTokens": 1801
}
}Response (stream=true): Server-Sent Events
Listar Sesiones
GET /api/agent/sessionsResponse: 200 OK
{
"sessions": [
{
"id": "sess_abc123",
"workspaceId": "myproject",
"model": "claude-4",
"status": "active",
"createdAt": "2024-01-15T10:30:00Z",
"messageCount": 5
}
]
}Obtener Sesión
GET /api/agent/sessions/{id}Response: 200 OK
{
"id": "sess_abc123",
"workspaceId": "myproject",
"model": "claude-4",
"status": "active",
"createdAt": "2024-01-15T10:30:00Z",
"messages": [
{
"id": "msg_xyz789",
"role": "user",
"content": "Analiza el PR #123",
"timestamp": "2024-01-15T10:31:00Z"
},
{
"id": "msg_def456",
"role": "assistant",
"content": "He encontrado 3 bugs potenciales...",
"timestamp": "2024-01-15T10:31:30Z"
}
]
}Eliminar Sesión
DELETE /api/agent/sessions/{id}Response: 200 OK
{
"id": "sess_abc123",
"deleted": true
}Errores
La API usa códigos HTTP estándar. El body de error contiene detalles:
{
"error": {
"code": "WORKSPACE_NOT_FOUND",
"message": "Workspace 'nonexistent' not found",
"details": {}
}
}Códigos de Error
| Código HTTP | Error Code | Descripción |
|---|---|---|
400 | INVALID_REQUEST | Request inválido |
401 | UNAUTHORIZED | Token inválido o expirado |
404 | WORKSPACE_NOT_FOUND | Workspace no encontrado |
409 | WORKSPACE_EXISTS | Ya existe workspace con ese nombre |
409 | PORT_UNAVAILABLE | Puerto no disponible |
500 | INTERNAL_ERROR | Error interno del servidor |
Rate Limiting
La API tiene rate limiting:
| Plan | Límite |
|---|---|
| Default | 100 requests/minuto |
| Authenticated | 1000 requests/minuto |
Headers de rate limit:
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 995
X-RateLimit-Reset: 1705305600Webhooks
La API puede enviar webhooks a eventos específicos.
Configurar Webhook
POST /api/webhooks
Content-Type: application/jsonBody:
{
"url": "https://your-server.com/webhook",
"events": ["workspace.created", "workspace.started", "workspace.stopped"],
"secret": "your-webhook-secret"
}Payload de Webhook
{
"event": "workspace.created",
"timestamp": "2024-01-15T10:30:00Z",
"workspace": {
"id": "myproject",
"status": "running"
}
}Headers:
X-Webhook-Signature: sha256=...
X-Webhook-Event: workspace.createdOpenAPI/Swagger
La especificación OpenAPI 3.0 está disponible en:
GET /openapi.jsonUI interactiva (Scalar):
https://lab1-helsinki.api.mks2508.systems/openapi