MKS DevEnv

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.systems

Para desarrollo local:

http://localhost:3100

Autenticación

La API usa JWT Bearer tokens para autenticación.

curl -H "Authorization: Bearer YOUR_TOKEN" \
  https://lab1-helsinki.api.mks2508.systems/api/workspaces

Obtener 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-backend

Endpoints

Workspaces

Listar Workspaces

GET /api/workspaces

Query Parameters:

ParámetroTipoDefaultDescripción
statusstringFiltrar por estado (running, stopped)
typestringFiltrar 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/json

Body:

{
  "name": "myproject",
  "template": "bun-typescript",
  "type": "persistent",
  "port": 8443,
  "repo": {
    "url": "https://github.com/user/repo.git",
    "branch": "main"
  }
}
CampoTipoRequeridoDescripción
namestringNombre único del workspace
templatestringTemplate a usar (default: bun-typescript)
typestringpersistent o temporary (default: persistent)
portnumberPuerto específico (default: auto)
repoobjectConfiguració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}/start

Response: 200 OK

{
  "id": "myproject",
  "status": "starting"
}

Detener Workspace

POST /api/workspaces/{id}/stop

Query Parameters:

ParámetroTipoDefaultDescripción
forcebooleanfalseForzar detención (SIGKILL)

Response: 200 OK

{
  "id": "myproject",
  "status": "stopping"
}

Reiniciar Workspace

POST /api/workspaces/{id}/restart

Response: 200 OK

{
  "id": "myproject",
  "status": "restarting"
}

Eliminar Workspace

DELETE /api/workspaces/{id}

Query Parameters:

ParámetroTipoDefaultDescripción
volumesbooleanfalseTambién eliminar volúmenes

Response: 200 OK

{
  "id": "myproject",
  "deleted": true
}

Logs

Obtener Logs

GET /api/workspaces/{id}/logs

Query Parameters:

ParámetroTipoDefaultDescripción
tailnumber50Número de líneas
followbooleanfalseStream logs en tiempo real
servicestringServicio 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/json

Body:

{
  "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_TOKEN

Body:

{
  "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/json

Body:

{
  "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/sessions

Response: 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 HTTPError CodeDescripción
400INVALID_REQUESTRequest inválido
401UNAUTHORIZEDToken inválido o expirado
404WORKSPACE_NOT_FOUNDWorkspace no encontrado
409WORKSPACE_EXISTSYa existe workspace con ese nombre
409PORT_UNAVAILABLEPuerto no disponible
500INTERNAL_ERRORError interno del servidor

Rate Limiting

La API tiene rate limiting:

PlanLímite
Default100 requests/minuto
Authenticated1000 requests/minuto

Headers de rate limit:

X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 995
X-RateLimit-Reset: 1705305600

Webhooks

La API puede enviar webhooks a eventos específicos.

Configurar Webhook

POST /api/webhooks
Content-Type: application/json

Body:

{
  "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.created

OpenAPI/Swagger

La especificación OpenAPI 3.0 está disponible en:

GET /openapi.json

UI interactiva (Scalar):

https://lab1-helsinki.api.mks2508.systems/openapi

Actions

On this page