# Authentication
Source: https://docs.cloudshipai.com/api-reference/authentication
API authentication methods
## Local Mode
When Station runs in local mode (`local_mode: true`), no authentication is required:
```bash theme={null}
curl http://localhost:8585/api/v1/agents
```
## CloudShip Mode
When connected to CloudShip (`local_mode: false`), use one of these methods:
### Bearer Token
```bash theme={null}
curl -H "Authorization: Bearer your-token" \
http://localhost:8585/api/v1/agents
```
### API Key
Generate an API key in Station settings:
```bash theme={null}
curl -H "X-API-Key: stn_xxx" \
http://localhost:8585/api/v1/agents
```
## MCP Authentication
The MCP server (port 8586) uses OAuth when in CloudShip mode.
### OAuth Flow
```mermaid theme={null}
sequenceDiagram
participant Client
participant Station
participant CloudShip
Client->>Station: MCP Request
Station->>Client: 401 + OAuth Config
Client->>CloudShip: Authorization Request
CloudShip->>Client: Access Token
Client->>Station: MCP Request + Token
Station->>Client: MCP Response
```
### OAuth Configuration
Station advertises OAuth configuration:
```json theme={null}
{
"oauth": {
"authorization_url": "https://app.cloudshipai.com/oauth/authorize",
"token_url": "https://app.cloudshipai.com/oauth/token",
"client_id": "station-mcp",
"scopes": ["mcp:read", "mcp:execute"]
}
}
```
## Token Scopes
| Scope | Permissions |
| --------- | ------------------------ |
| `read` | List agents, tools, runs |
| `write` | Create/update agents |
| `execute` | Run agents |
| `admin` | Full access |
## Creating API Keys
### Via CLI
```bash theme={null}
stn auth create-key --name "CI Pipeline" --scopes "read,execute"
```
### Via API
```bash theme={null}
curl -X POST http://localhost:8585/api/v1/auth/keys \
-H "Authorization: Bearer admin-token" \
-d '{"name": "CI Pipeline", "scopes": ["read", "execute"]}'
```
## Revoking Keys
```bash theme={null}
stn auth revoke-key stn_xxx
```
Or via API:
```bash theme={null}
curl -X DELETE http://localhost:8585/api/v1/auth/keys/stn_xxx \
-H "Authorization: Bearer admin-token"
```
# API Introduction
Source: https://docs.cloudshipai.com/api-reference/introduction
Station REST API reference
## Overview
Station provides a REST API for programmatic access to all features.
**Base URL**: `http://localhost:8585/api/v1`
## Authentication
### Local Mode
No authentication required when `local_mode: true`.
### CloudShip Mode
Use bearer token authentication:
```bash theme={null}
curl -H "Authorization: Bearer your-token" \
http://localhost:8585/api/v1/agents
```
## Endpoints
### Health
```http theme={null}
GET /api/v1/health
```
Returns server health status.
### Agents
| Method | Endpoint | Description |
| ------ | ------------------------ | ----------------- |
| GET | `/api/v1/agents` | List all agents |
| GET | `/api/v1/agents/:id` | Get agent details |
| POST | `/api/v1/agents` | Create agent |
| PUT | `/api/v1/agents/:id` | Update agent |
| DELETE | `/api/v1/agents/:id` | Delete agent |
| POST | `/api/v1/agents/:id/run` | Execute agent |
### Environments
| Method | Endpoint | Description |
| ------ | --------------------------------- | ----------------- |
| GET | `/api/v1/environments` | List environments |
| GET | `/api/v1/environments/:name` | Get environment |
| POST | `/api/v1/environments/:name/sync` | Sync environment |
### MCP Servers
| Method | Endpoint | Description |
| ------ | --------------------- | -------------------- |
| GET | `/api/v1/mcp-servers` | List MCP servers |
| GET | `/api/v1/tools` | List available tools |
### Runs
| Method | Endpoint | Description |
| ------ | ------------------ | --------------- |
| GET | `/api/v1/runs` | List agent runs |
| GET | `/api/v1/runs/:id` | Get run details |
## Response Format
All responses follow this format:
```json theme={null}
{
"success": true,
"data": { ... },
"error": null
}
```
Error response:
```json theme={null}
{
"success": false,
"data": null,
"error": {
"code": "AGENT_NOT_FOUND",
"message": "Agent with ID 123 not found"
}
}
```
## Pagination
List endpoints support pagination:
```http theme={null}
GET /api/v1/agents?page=1&limit=20
```
Response includes pagination metadata:
```json theme={null}
{
"data": [...],
"pagination": {
"page": 1,
"limit": 20,
"total": 45,
"pages": 3
}
}
```
## Rate Limiting
| Mode | Limit |
| --------- | ----------- |
| Local | None |
| CloudShip | 100 req/min |
## SDKs
Official SDKs coming soon:
* Python
* TypeScript
* Go
## OpenAPI Spec
Download the OpenAPI specification:
```bash theme={null}
curl http://localhost:8585/api/v1/openapi.json -o openapi.json
```
# Workflows API
Source: https://docs.cloudshipai.com/api-reference/workflows
Manage and execute durable multi-step workflows
## Workflow Definitions
Endpoints for managing workflow definitions.
| Method | Endpoint | Description |
| -------- | ----------------------------------- | ------------------------------------- |
| `POST` | `/api/v1/workflows` | Create a new workflow |
| `GET` | `/api/v1/workflows` | List all workflows |
| `GET` | `/api/v1/workflows/:id` | Get workflow by ID |
| `PUT` | `/api/v1/workflows/:id` | Update workflow (creates new version) |
| `DELETE` | `/api/v1/workflows/:id` | Disable workflow |
| `POST` | `/api/v1/workflows/validate` | Validate definition without saving |
| `GET` | `/api/v1/workflows/:id/versions` | List all versions |
| `GET` | `/api/v1/workflows/:id/versions/:v` | Get specific version |
### Create Workflow
**Request Body**
```json theme={null}
{
"workflowId": "incident-rca",
"name": "Incident Root Cause Analysis",
"description": "Parallel investigation with synthesis",
"definition": {
"id": "incident-rca",
"start": "investigate",
"states": [...]
}
}
```
## Workflow Runs
Endpoints for executing workflows and tracking their progress.
| Method | Endpoint | Description |
| ------ | ---------------------------------- | --------------------------------------------- |
| `POST` | `/api/v1/workflow-runs` | Start a new run |
| `GET` | `/api/v1/workflow-runs` | List runs (filter by `workflow_id`, `status`) |
| `GET` | `/api/v1/workflow-runs/:id` | Get run status and output |
| `GET` | `/api/v1/workflow-runs/:id/stream` | SSE stream of run updates |
| `GET` | `/api/v1/workflow-runs/:id/steps` | List completed steps |
| `POST` | `/api/v1/workflow-runs/:id/pause` | Pause execution |
| `POST` | `/api/v1/workflow-runs/:id/resume` | Resume paused run |
| `POST` | `/api/v1/workflow-runs/:id/cancel` | Cancel run |
### Start Run
**Request Body**
```json theme={null}
{
"workflowId": "incident-rca",
"input": {
"service_name": "payment-service",
"namespace": "production"
}
}
```
### Streaming Updates (SSE)
The `/api/v1/workflow-runs/:id/stream` endpoint provides a server-sent events (SSE) stream of run updates.
**Events:**
* `run_started`: Emitted when the run begins
* `step_started`: Emitted when a step begins execution
* `step_completed`: Emitted when a step finishes
* `run_completed`: Emitted when the entire workflow finishes
* `run_failed`: Emitted if an error occurs
## Human Approvals
Endpoints for managing `human_approval` steps in workflows.
| Method | Endpoint | Description |
| ------ | ---------------------------------------- | ----------------------------- |
| `GET` | `/api/v1/workflow-approvals` | List pending approvals |
| `GET` | `/api/v1/workflow-approvals/:id` | Get approval details |
| `POST` | `/api/v1/workflow-approvals/:id/approve` | Approve with optional comment |
| `POST` | `/api/v1/workflow-approvals/:id/reject` | Reject with reason |
### Approve Request
**Request Body**
```json theme={null}
{
"comment": "Reviewed and approved for production rollout"
}
```
Set `X-Approver-ID` header to identify the approver. Defaults to `api-user` if not provided.
# Architecture Deep Dive
Source: https://docs.cloudshipai.com/contributing/architecture
Detailed architecture diagrams and component analysis
# Architecture Deep Dive
This document provides detailed architecture diagrams showing how Station's services, APIs, and components interact.
## High-Level System Architecture
```
┌─────────────────────────────────────────────────────────────────────────┐
│ STATION PLATFORM │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐ │
│ │ CLI Layer │ │ API Server │ │ MCP Server │ │
│ │ (cmd/main) │ │ (:8585) │ │ (stdio) │ │
│ │ │ │ │ │ │ │
│ │ • agent │ │ • /api/v1/agents │ │ • Tool handlers │ │
│ │ • bundle │ │ • /api/v1/envs │ │ • Agent handlers │ │
│ │ • env │ │ • /api/v1/runs │ │ • Resources │ │
│ │ • sync │ │ • /api/v1/mcp │ │ • Tool Discovery │ │
│ │ • runs │ │ • /api/v1/tools │ │ • Prompts │ │
│ └────────┬─────────┘ └────────┬─────────┘ └────────┬─────────┘ │
│ │ │ │ │
│ └───────────────────────┼────────────────────────┘ │
│ │ │
│ ┌──────────▼──────────┐ │
│ │ Service Layer │ │
│ │ (internal/services)│ │
│ └──────────┬──────────┘ │
│ │ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ Environment System │ │
│ │ ~/.config/station/environments// │ │
│ │ ├── template.json (MCP Server definitions) │ │
│ │ ├── variables.yml (Template variables) │ │
│ │ └── agents/ (Agent .prompt files) │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ External Integration Layer │ │
│ │ • GenKit AI Models (OpenAI, Gemini, Ollama) │ │
│ │ • MCP Server Processes (filesystem, custom tools) │ │
│ │ • Lighthouse (CloudShip data ingestion & telemetry) │ │
│ │ • OpenTelemetry (Tracing & metrics) │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────┘
```
## Agent Execution Flow
All entry points converge at the **AgentExecutionEngine**:
```
┌──────────────────────────────────────────────────────────────────────┐
│ AGENT EXECUTION PATHS │
└──────────────────────────────────────────────────────────────────────┘
CLI PATH: stn agent run
═══════════════════════════════════════════════════════════════════════
cmd/main/handlers/agent/execution.go
└─ RunAgentLocal()
│
├─ Load config
├─ Open database connection
└─ Call: agentExecutionEngine.ExecuteWithOptions()
API PATH: POST /api/v1/agents/:id/execute
═══════════════════════════════════════════════════════════════════════
internal/api/v1/agents.go
└─ executeAgent() handler
│
├─ Validate authentication
├─ Parse task from request body
└─ Call: agentService.ExecuteAgent()
MCP SERVER PATH: call_agent tool
═══════════════════════════════════════════════════════════════════════
internal/mcp/execution_handlers.go
└─ handleMCPAgentRun()
│
├─ Parse MCP tool call arguments
├─ Create AgentRun database entry
└─ Call: agentService.ExecuteAgentWithRunID()
SCHEDULER PATH: Cron-triggered execution
═══════════════════════════════════════════════════════════════════════
internal/services/scheduler.go
└─ SchedulerService.Start()
│
├─ Load scheduled agents from database
└─ At cron trigger:
└─ Call: agentService.ExecuteAgent()
```
## AgentExecutionEngine Internals
The core execution engine orchestrates the full agent lifecycle:
```
┌─ AgentExecutionEngine Key Responsibilities ─────────────────────────┐
│ │
│ File: /internal/services/agent_execution_engine.go │
│ │
│ 1. Agent Validation & Loading │
│ • Fetch agent from database │
│ • Validate agent exists and is configured │
│ • Get environment and tool assignments │
│ │
│ 2. Environment Setup │
│ • Load environment configuration │
│ • Load variables.yml for template processing │
│ • Validate environment exists │
│ │
│ 3. AI Model Configuration │
│ • Initialize GenKit with configured provider │
│ • Set up model-specific parameters │
│ • Handle model fallbacks if needed │
│ │
│ 4. MCP Server Connection │
│ • Create MCPConnectionManager instance │
│ • Connect to each MCP server in environment │
│ • Discover available tools per server │
│ • Cache tools for performance │
│ │
│ 5. Tool Preparation │
│ • Build complete tool list from all servers │
│ • Apply agent-specific tool assignments │
│ • Filter tools based on permissions │
│ │
│ 6. Execution │
│ • Render dotprompt template with variables │
│ • Pass task + tools to GenKit │
│ • Process iterative tool calls │
│ • Enforce max steps limit │
│ │
│ 7. Metadata Capture │
│ • Record all tool calls with parameters │
│ • Capture execution steps │
│ • Track token usage (input/output) │
│ • Measure execution duration │
│ │
│ 8. Lighthouse Integration (Optional) │
│ • Send run data to Lighthouse │
│ • Include app/app_type classification │
│ • Enable CloudShip data ingestion │
│ │
│ 9. Cleanup │
│ • Close all MCP connections │
│ • Release resources │
│ • Stop any running processes │
│ │
└──────────────────────────────────────────────────────────────────────┘
```
## Service Layer Architecture
Station's service layer contains 43+ focused modules:
```
┌─────────────────────────────────────────────────────────────────────┐
│ CORE SERVICES LAYER │
│ /internal/services/ - 43 focused modules │
└─────────────────────────────────────────────────────────────────────┘
AGENT EXECUTION SERVICES
═════════════════════════════════════════════════════════════════════
AgentService (agent_service_impl.go)
├─ Creates/manages AgentExecutionEngine
├─ Wraps execution with telemetry
├─ Interface: AgentServiceInterface
└─ Methods:
├─ ExecuteAgent(agentID, task, variables) → Message
├─ ExecuteAgentWithRunID(agentID, task, runID, variables)
├─ CreateAgent(config) → Agent
├─ UpdateAgent(agentID, config) → Agent
└─ DeleteAgent(agentID)
AgentExecutionEngine (agent_execution_engine.go)
├─ Main execution orchestrator
├─ Manages GenKit + MCP lifecycle
└─ Methods:
├─ Execute(agent, task, runID, userVars)
└─ ExecuteWithOptions(agent, task, runID, userVars, opts)
GenKitProvider (genkit_provider.go)
├─ AI model provider initialization
├─ Supports: OpenAI, Gemini, Ollama
└─ Methods:
└─ InitializeGenKit() → *genkit.Genkit
MCP MANAGEMENT SERVICES
═════════════════════════════════════════════════════════════════════
MCPConnectionManager (mcp_connection_manager.go)
├─ Lifecycle management for MCP connections
├─ Tool discovery and caching
└─ Methods:
├─ DiscoverTools(envID, genkitApp)
├─ GetCachedTools(envID)
└─ CleanupConnections(clients)
MCPToolDiscovery (mcp_tool_discovery.go)
├─ Discovers tools from MCP servers
├─ Maps tools to servers
└─ Methods:
├─ DiscoverToolsPerServer(fileConfig)
└─ SaveToolsForServer(envID, serverName, tools)
ToolDiscoveryService (tool_discovery_service.go)
├─ High-level tool discovery orchestration
└─ Methods:
├─ DiscoverTools(envID) → []Tool
└─ RefreshTools(envID)
ENVIRONMENT & CONFIGURATION SERVICES
═════════════════════════════════════════════════════════════════════
EnvironmentManagementService (environment_management_service.go)
├─ Environment CRUD operations
├─ File-based configuration management
└─ Methods:
├─ CreateEnvironment(name, description)
├─ DeleteEnvironment(name)
└─ GetEnvironmentFileConfig(name)
DeclarativeSync (declarative_sync.go)
├─ Synchronizes file-based configs to database
├─ Bidirectional sync (files ↔ database)
├─ Template variable processing
└─ Methods:
├─ SyncEnvironment(ctx, envName, options)
├─ SyncAgents(ctx, envID)
└─ SyncMCPServers(ctx, envID)
SCHEDULING & AUTOMATION
═════════════════════════════════════════════════════════════════════
SchedulerService (scheduler.go)
├─ Cron-based agent scheduling (6-field cron)
├─ Persistent schedule storage
└─ Methods:
├─ Start() - loads and activates schedules
├─ Stop() - graceful shutdown
└─ ScheduleAgent(agentID, cronExpression)
TELEMETRY & MONITORING
═════════════════════════════════════════════════════════════════════
TelemetryService (telemetry_service.go)
├─ OpenTelemetry integration
├─ Span creation and tracking
└─ Methods:
├─ Initialize(ctx)
└─ CreateSpan(ctx, name, attributes)
```
## MCP Server Architecture
```
┌──────────────────────────────────────────────────────────────────────┐
│ MCP SERVER SUBSYSTEM │
│ /internal/mcp/ - Model Context Protocol │
└──────────────────────────────────────────────────────────────────────┘
CORE MCP SERVER
═══════════════════════════════════════════════════════════════════════
MCP Server (mcp/server.go)
└─ Main MCP server instance
│
├─ Capabilities:
│ ├─ Tools (tool discovery & execution)
│ ├─ Resources (read-only data access)
│ ├─ Prompts (system prompts)
│ └─ Tool suggestions
│
└─ Core Components:
├─ mcpServer: *server.MCPServer (mark3labs/mcp-go)
├─ httpServer: *server.StreamableHTTPServer
├─ toolDiscoverySvc: *ToolDiscoveryService
├─ agentService: AgentServiceInterface
├─ authService: *auth.AuthService
└─ repos: *repositories.Repositories
HANDLER ORGANIZATION
═══════════════════════════════════════════════════════════════════════
/internal/mcp/
│
├─ server.go # Main server setup
│
├─ agent_handlers.go # Agent CRUD tools
│ ├─ call_agent # Execute an agent
│ ├─ list_agents # List all agents
│ ├─ get_agent_details # Get agent info
│ └─ create_agent # Create new agent
│
├─ environment_handlers.go # Environment tools
│ ├─ list_environments # List environments
│ ├─ create_environment # Create environment
│ └─ sync_environment # Sync from files
│
├─ mcp_handlers.go # MCP server management
│ ├─ add_mcp_server # Add MCP server
│ └─ list_mcp_servers # List servers
│
├─ tool_handlers.go # Tool management
│ ├─ list_tools # List all tools
│ ├─ discover_tools # Trigger discovery
│ └─ add_tool # Add tool to agent
│
└─ workflow_handlers.go # Workflow tools
├─ create_workflow # Create workflow
├─ start_workflow_run # Start execution
└─ get_workflow_run # Get run status
```
## Database Layer
```
┌──────────────────────────────────────────────────────────────────────┐
│ DATABASE LAYER │
│ /internal/db/ - SQLite with Repositories │
└──────────────────────────────────────────────────────────────────────┘
REPOSITORY PATTERN
═══════════════════════════════════════════════════════════════════════
/internal/db/repositories/
│
├─ agent_repository.go # Agent CRUD
│ ├─ Create(agent) → id
│ ├─ GetByID(id) → Agent
│ ├─ GetByName(name) → Agent
│ ├─ Update(agent)
│ └─ Delete(id)
│
├─ agent_run_repository.go # Execution history
│ ├─ Create(run) → id
│ ├─ GetByID(id) → AgentRun
│ ├─ ListByAgent(agentID) → []AgentRun
│ └─ UpdateStatus(id, status)
│
├─ environment_repository.go # Environment CRUD
│ ├─ Create(env) → id
│ ├─ GetByName(name) → Environment
│ └─ List() → []Environment
│
├─ mcp_server_repository.go # MCP server configs
│ ├─ Create(server) → id
│ ├─ GetByEnvironment(envID) → []MCPServer
│ └─ Delete(id)
│
└─ tool_repository.go # Tool definitions
├─ Create(tool) → id
├─ GetByServer(serverID) → []Tool
└─ GetByAgent(agentID) → []Tool
SCHEMA (simplified)
═══════════════════════════════════════════════════════════════════════
environments
├─ id (INTEGER PRIMARY KEY)
├─ name (TEXT UNIQUE)
├─ description (TEXT)
└─ created_at (DATETIME)
agents
├─ id (INTEGER PRIMARY KEY)
├─ environment_id (FOREIGN KEY)
├─ name (TEXT)
├─ prompt (TEXT)
├─ max_steps (INTEGER)
└─ created_at (DATETIME)
agent_runs
├─ id (TEXT PRIMARY KEY) -- UUID
├─ agent_id (FOREIGN KEY)
├─ task (TEXT)
├─ status (TEXT)
├─ response (TEXT)
├─ tool_calls (JSON)
├─ tokens_used (INTEGER)
├─ duration_ms (INTEGER)
└─ created_at (DATETIME)
mcp_servers
├─ id (INTEGER PRIMARY KEY)
├─ environment_id (FOREIGN KEY)
├─ name (TEXT)
├─ command (TEXT)
├─ args (JSON)
└─ env_vars (JSON)
tools
├─ id (INTEGER PRIMARY KEY)
├─ mcp_server_id (FOREIGN KEY)
├─ name (TEXT)
├─ description (TEXT)
└─ input_schema (JSON)
```
## Request Flow Example
Complete flow for `stn agent run analyzer "Check logs"`:
```
┌─────────────────────────────────────────────────────────────────────┐
│ REQUEST FLOW EXAMPLE │
│ stn agent run analyzer "Check logs" │
└─────────────────────────────────────────────────────────────────────┘
1. CLI ENTRY
cmd/main/main.go
└─ Parse command: "agent run analyzer 'Check logs'"
2. HANDLER
cmd/main/handlers/agent/execution.go
└─ RunAgentLocal()
├─ Load config.yaml
├─ Open database
└─ agentService.ExecuteAgent("analyzer", "Check logs")
3. SERVICE LAYER
internal/services/agent_service_impl.go
└─ ExecuteAgent()
├─ Get agent from database
├─ Create AgentRun record (status: "running")
└─ engine.ExecuteWithOptions(agent, task)
4. EXECUTION ENGINE
internal/services/agent_execution_engine.go
└─ ExecuteWithOptions()
│
├─ Load environment config
├─ Initialize GenKit (OpenAI/Gemini)
│
├─ MCPConnectionManager.DiscoverTools()
│ ├─ Connect to MCP servers
│ ├─ Call listTools on each
│ └─ Cache tools
│
├─ Build tool list for agent
│
└─ GenKit.Generate(prompt + task + tools)
│
├─ AI model processes request
├─ Returns tool call: {"name": "grep", "args": {...}}
│
└─ Execute tool via MCP
├─ Route to correct MCP server
├─ Execute grep tool
└─ Return results to AI
└─ AI generates final response
5. RESULT CAPTURE
└─ Update AgentRun
├─ status: "completed"
├─ response: "Found 3 errors in logs..."
├─ tool_calls: [{name: "grep", ...}]
├─ tokens_used: 1234
└─ duration_ms: 5678
6. LIGHTHOUSE (if configured)
└─ Send run data to CloudShip
├─ Include structured output
└─ Enable platform features
7. OUTPUT
└─ Print response to terminal
```
## Key Design Decisions
| Decision | Rationale |
| --------------------------- | --------------------------------------- |
| **Single execution engine** | All entry points use the same logic |
| **File-based config + DB** | GitOps-friendly, yet queryable |
| **MCP for tools** | Standard protocol, extensible |
| **GenKit abstraction** | Swap AI providers easily |
| **6-field cron** | Second-level precision for scheduling |
| **SQLite default** | Zero-config, portable, cloud-upgradable |
## Next Steps
Set up your local environment
Coding conventions and standards
# Code Style
Source: https://docs.cloudshipai.com/contributing/code-style
Coding conventions and best practices for Station
# Code Style Guide
Station follows standard Go conventions with some project-specific guidelines.
## Go Style
### Official Guidelines
Station follows the official Go style guides:
* [Effective Go](https://go.dev/doc/effective_go)
* [Go Code Review Comments](https://go.dev/wiki/CodeReviewComments)
* [Uber Go Style Guide](https://github.com/uber-go/guide/blob/master/style.md) (supplementary)
### Formatting
```bash theme={null}
# Format code (required before commit)
make fmt
# Or directly
gofmt -s -w .
goimports -w .
```
### Linting
```bash theme={null}
# Run linter
make lint
# Or directly
golangci-lint run
```
The project uses `golangci-lint` with these enabled linters:
* `gofmt` - Format checking
* `goimports` - Import organization
* `govet` - Go vet checks
* `errcheck` - Error handling
* `staticcheck` - Static analysis
* `gosimple` - Simplifications
* `ineffassign` - Unused assignments
## Naming Conventions
### Packages
```go theme={null}
// Good - short, lowercase, no underscores
package services
package repositories
package config
// Bad
package agent_services
package AgentRepository
```
### Functions and Methods
```go theme={null}
// Good - verb-noun, exported if needed
func (s *AgentService) Execute(ctx context.Context, id int64) error
func (r *AgentRepository) GetByID(ctx context.Context, id int64) (*Agent, error)
func parseConfig(path string) (*Config, error)
// Bad
func (s *AgentService) DoExecute(ctx context.Context, id int64) error // redundant "Do"
func (r *AgentRepository) agent_by_id(id int64) *Agent // snake_case
```
### Interfaces
```go theme={null}
// Good - suffix with -er for single method, or describe behavior
type AgentExecutor interface {
Execute(ctx context.Context, task string) (string, error)
}
type AgentService interface {
Execute(ctx context.Context, id int64, task string) (string, error)
Create(ctx context.Context, agent *Agent) (int64, error)
Update(ctx context.Context, agent *Agent) error
Delete(ctx context.Context, id int64) error
}
// Bad
type IAgentService interface { } // Don't prefix with I
```
### Variables
```go theme={null}
// Good
var defaultTimeout = 30 * time.Second
agentID := params.Get("id")
mcpServer := config.MCPServers[0]
// Bad
var DefaultTimeout = 30 * time.Second // unexported should be lowercase
agent_id := params.Get("id") // snake_case
```
### Constants
```go theme={null}
// Good
const (
DefaultMaxSteps = 5
DefaultAPIPort = 8585
StatusPending = "pending"
StatusRunning = "running"
StatusCompleted = "completed"
)
// Bad
const DEFAULT_MAX_STEPS = 5 // SCREAMING_SNAKE_CASE
```
## Code Organization
### File Structure
```go theme={null}
// Order of declarations in a file:
// 1. Package comment (if main file)
// 2. Package declaration
// 3. Imports (grouped: stdlib, external, internal)
// 4. Constants
// 5. Variables
// 6. Types (interfaces, then structs)
// 7. Functions (constructors first, then methods)
package services
import (
"context"
"database/sql"
"fmt"
"time"
"github.com/google/uuid"
"go.opentelemetry.io/otel"
"github.com/cloudshipai/station/internal/config"
"github.com/cloudshipai/station/internal/db/repositories"
)
const (
defaultTimeout = 30 * time.Second
)
var (
ErrNotFound = errors.New("not found")
)
type AgentService interface {
Execute(ctx context.Context, id int64, task string) error
}
type agentServiceImpl struct {
repo repositories.AgentRepository
config *config.Config
}
func NewAgentService(repo repositories.AgentRepository, cfg *config.Config) AgentService {
return &agentServiceImpl{repo: repo, config: cfg}
}
func (s *agentServiceImpl) Execute(ctx context.Context, id int64, task string) error {
// ...
}
```
### Import Grouping
```go theme={null}
import (
// Standard library
"context"
"fmt"
"time"
// External dependencies
"github.com/labstack/echo/v4"
"go.opentelemetry.io/otel"
// Internal packages
"github.com/cloudshipai/station/internal/config"
"github.com/cloudshipai/station/internal/services"
)
```
## Error Handling
### Error Wrapping
```go theme={null}
// Good - wrap errors with context
func (s *AgentService) Execute(ctx context.Context, id int64, task string) error {
agent, err := s.repo.GetByID(ctx, id)
if err != nil {
return fmt.Errorf("get agent %d: %w", id, err)
}
result, err := s.engine.Execute(ctx, agent, task)
if err != nil {
return fmt.Errorf("execute agent %s: %w", agent.Name, err)
}
return nil
}
// Bad - losing error context
func (s *AgentService) Execute(ctx context.Context, id int64, task string) error {
agent, err := s.repo.GetByID(ctx, id)
if err != nil {
return err // No context about where/why
}
return nil
}
```
### Custom Errors
```go theme={null}
// Define sentinel errors
var (
ErrAgentNotFound = errors.New("agent not found")
ErrInvalidInput = errors.New("invalid input")
ErrExecutionTimeout = errors.New("execution timeout")
)
// Use errors.Is for checking
if errors.Is(err, ErrAgentNotFound) {
return http.StatusNotFound, nil
}
```
### Don't Ignore Errors
```go theme={null}
// Good
result, err := s.Execute(ctx, task)
if err != nil {
log.Error("execution failed", "error", err)
return err
}
// Bad
result, _ := s.Execute(ctx, task) // Ignoring error!
```
## Context Usage
```go theme={null}
// Always pass context as first parameter
func (s *AgentService) Execute(ctx context.Context, id int64, task string) error {
// Use context for cancellation
select {
case <-ctx.Done():
return ctx.Err()
default:
}
// Pass context to downstream calls
agent, err := s.repo.GetByID(ctx, id)
if err != nil {
return err
}
return nil
}
```
## Concurrency
### Channel Patterns
```go theme={null}
// Use buffered channels when appropriate
results := make(chan Result, len(tasks))
// Always close channels from producer
go func() {
defer close(results)
for _, task := range tasks {
results <- process(task)
}
}()
// Consumer reads until closed
for result := range results {
handleResult(result)
}
```
### Mutex Usage
```go theme={null}
type SafeCounter struct {
mu sync.RWMutex
count int
}
func (c *SafeCounter) Increment() {
c.mu.Lock()
defer c.mu.Unlock()
c.count++
}
func (c *SafeCounter) Value() int {
c.mu.RLock()
defer c.mu.RUnlock()
return c.count
}
```
## Documentation
### Package Comments
```go theme={null}
// Package services provides the core business logic for Station.
// It includes agent execution, MCP management, and environment configuration.
package services
```
### Function Comments
```go theme={null}
// Execute runs the specified agent with the given task.
// It returns the agent's response or an error if execution fails.
//
// The execution respects the context deadline and will return
// context.DeadlineExceeded if the timeout is reached.
func (s *AgentService) Execute(ctx context.Context, id int64, task string) (string, error) {
// ...
}
```
### Inline Comments
```go theme={null}
func (s *AgentService) Execute(ctx context.Context, id int64, task string) error {
// Validate agent exists before execution
agent, err := s.repo.GetByID(ctx, id)
if err != nil {
return err
}
// Initialize MCP connections for tool access
// This may take a few seconds for large environments
mcpManager, err := s.initMCP(ctx, agent.Environment)
if err != nil {
return fmt.Errorf("init mcp: %w", err)
}
defer mcpManager.Close()
// Execute with timeout from agent config
timeout := time.Duration(agent.TimeoutSeconds) * time.Second
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
return s.engine.Execute(ctx, agent, task)
}
```
## Testing Style
See the [Testing Guide](/contributing/testing) for detailed testing conventions.
```go theme={null}
// Use descriptive test names
func TestAgentService_Execute_ReturnsErrorWhenAgentNotFound(t *testing.T) { }
func TestAgentService_Execute_SuccessfulExecution(t *testing.T) { }
func TestAgentService_Execute_TimeoutExceeded(t *testing.T) { }
// Use table-driven tests
func TestValidateInput(t *testing.T) {
tests := []struct {
name string
input string
wantErr bool
}{
{"valid input", "hello", false},
{"empty input", "", true},
}
// ...
}
```
## Pre-commit Checklist
Before committing:
1. **Format code**: `make fmt`
2. **Run linter**: `make lint`
3. **Run tests**: `make test`
4. **Check for issues**: `make check` (runs fmt, lint, test)
## Next Steps
Set up your development environment
Writing and running tests
# Development Setup
Source: https://docs.cloudshipai.com/contributing/development
Set up your local development environment for Station
# Development Setup
This guide covers setting up a local development environment for contributing to Station.
## Prerequisites
| Requirement | Version | Purpose |
| ----------- | ------- | ---------------------------------- |
| Go | 1.21+ | Core language |
| Docker | Latest | Jaeger, sandbox, integration tests |
| Make | Any | Build automation |
| Git | Any | Version control |
### Optional
| Requirement | Purpose |
| ----------- | ---------------------- |
| Node.js 18+ | Building documentation |
| SQLite CLI | Database debugging |
| Jaeger | Distributed tracing |
## Clone and Build
```bash theme={null}
# Clone the repository
git clone https://github.com/cloudshipai/station.git
cd station
# Build the binary
make build
# Or build and install to $GOPATH/bin
make install
# Verify installation
stn version
```
## Project Structure
```
station/
├── cmd/main/ # CLI entry point
│ ├── main.go # Application bootstrap
│ └── handlers/ # CLI command handlers
│ ├── agent/ # Agent commands
│ ├── env/ # Environment commands
│ ├── bundle/ # Bundle commands
│ └── ...
├── internal/
│ ├── api/v1/ # REST API handlers
│ ├── config/ # Configuration loading
│ ├── db/ # Database layer
│ │ ├── repositories/ # Data access layer
│ │ └── schema.sql # SQLite schema
│ ├── mcp/ # MCP server implementation
│ ├── services/ # Business logic (43+ modules)
│ └── workflows/ # Workflow engine
├── pkg/ # Public packages (reusable)
├── bundles/ # Example agent bundles
├── docs/ # Internal documentation
│ └── architecture/ # Architecture diagrams
└── Makefile # Build automation
```
## Running Locally
### Start the Server
```bash theme={null}
# Start with default configuration
stn serve
# Start with custom configuration
stn serve --config path/to/config.yaml
# Start with API + MCP server
stn serve --api-port 8585 --mcp-port 8586
```
### Create a Test Environment
```bash theme={null}
# Create a new environment
stn env create dev
# Sync environment (loads agents and MCP servers)
stn sync dev
# List environments
stn env list
```
### Run an Agent
```bash theme={null}
# Run an agent with a task
stn agent run my-agent "Hello, what can you do?"
# Run with variables
stn agent run my-agent "Analyze this" --var file=./data.json
# Run with streaming output
stn agent run my-agent "Process data" --stream
```
## Configuration
### Default Paths
| Platform | Config Directory |
| ----------- | -------------------- |
| Linux/macOS | `~/.config/station/` |
| Windows | `%APPDATA%\station\` |
### Configuration File
Create `config.yaml`:
```yaml theme={null}
# AI Provider Configuration
ai_provider: openai
ai_model: gpt-5-mini
# API Server
api_port: 8585
mcp_port: 8586
# Database
database_url: ~/.config/station/station.db
# Workspace (for environments)
workspace: ~/.config/station/environments
# Telemetry (optional)
telemetry:
enabled: true
jaeger_endpoint: http://localhost:4317
```
### Environment Variables
| Variable | Description | Default |
| ------------------ | -------------------- | -------------------------------- |
| `OPENAI_API_KEY` | OpenAI API key | - |
| `GOOGLE_API_KEY` | Google AI API key | - |
| `STN_AI_PROVIDER` | AI provider override | `openai` |
| `STN_AI_MODEL` | AI model override | `gpt-5-mini` |
| `STN_DATABASE_URL` | Database path | `~/.config/station/station.db` |
| `STN_WORKSPACE` | Environments path | `~/.config/station/environments` |
| `STN_API_PORT` | API server port | `8585` |
| `STN_MCP_PORT` | MCP server port | `8586` |
## Starting Infrastructure
### Jaeger (Distributed Tracing)
```bash theme={null}
# Start Jaeger with Docker
docker run -d --name jaeger \
-p 16686:16686 \
-p 4317:4317 \
-p 4318:4318 \
jaegertracing/jaeger:latest
# View traces at http://localhost:16686
```
### libsql (Optional Cloud Database)
For cloud database development:
```bash theme={null}
# Install libsql CLI
curl -fsSL https://github.com/libsql/libsql/releases/download/latest/libsql-linux-x64.tar.gz | tar xz
# Start local libsql server
libsql server --db-path ./station.db
```
## IDE Setup
### VS Code
Recommended extensions:
```json theme={null}
{
"recommendations": [
"golang.go",
"ms-azuretools.vscode-docker",
"mtxr.sqltools",
"humao.rest-client"
]
}
```
Settings for Go:
```json theme={null}
{
"go.useLanguageServer": true,
"go.lintTool": "golangci-lint",
"go.lintOnSave": "package",
"go.formatTool": "goimports",
"editor.formatOnSave": true
}
```
### GoLand / IntelliJ
1. Open the `station/` directory as a Go project
2. Enable "Go Modules integration"
3. Configure GOROOT to Go 1.21+
## Makefile Targets
```bash theme={null}
# Build the binary
make build
# Run tests
make test
# Run tests with coverage
make test-coverage
# Run linter
make lint
# Format code
make fmt
# Clean build artifacts
make clean
# Build and install
make install
# Generate mocks (for testing)
make mocks
# Run all checks (lint + test)
make check
```
## Common Development Tasks
### Adding a New CLI Command
1. Create handler in `cmd/main/handlers//`
2. Register command in `cmd/main/main.go`
3. Add tests in `cmd/main/handlers//*_test.go`
### Adding a New Service
1. Create service in `internal/services/.go`
2. Define interface if needed
3. Add to service registry if applicable
4. Write tests in `internal/services/_test.go`
### Adding a New API Endpoint
1. Add handler in `internal/api/v1/.go`
2. Register route in `internal/api/v1/routes.go`
3. Add tests in `internal/api/v1/_test.go`
### Adding a New MCP Tool
1. Add handler in `internal/mcp/handlers/`
2. Register in `internal/mcp/server.go`
3. Update tool discovery if needed
## Debugging
### Enable Debug Logging
```bash theme={null}
# Via environment variable
export STN_LOG_LEVEL=debug
stn serve
# Via flag
stn serve --log-level debug
```
### Database Inspection
```bash theme={null}
# Open SQLite shell
sqlite3 ~/.config/station/station.db
# Common queries
.tables # List tables
.schema agents # Show agent schema
SELECT * FROM agents LIMIT 10; # View agents
SELECT * FROM agent_runs ORDER BY created_at DESC LIMIT 5; # Recent runs
```
### Tracing with Jaeger
1. Start Jaeger (see above)
2. Configure telemetry in `config.yaml`
3. Run agents and view traces at [http://localhost:16686](http://localhost:16686)
## Station Lattice Development
Station Lattice enables multi-station mesh networking. This section covers development-specific workflows.
### Running Lattice Locally
```bash theme={null}
# Terminal 1: Start orchestrator station
stn serve --orchestration --workspace ./orchestrator
# Terminal 2: Start member station (connects to orchestrator)
stn serve --lattice nats://localhost:4222 --workspace ./member
# Verify connection
stn lattice stations list
stn lattice agents list
```
### Key Lattice Directories
| Directory | Purpose |
| ------------------------------ | --------------------------- |
| `internal/lattice/` | Core lattice implementation |
| `internal/lattice/work/` | JetStream work tracking |
| `cmd/main/lattice_commands.go` | CLI commands |
| `bundles/demo/` | Demo bundles for testing |
### NATS Subject Conventions
| Subject Pattern | Purpose |
| -------------------------------- | ------------------------------ |
| `lattice.station.{id}.heartbeat` | Station presence heartbeats |
| `lattice.agent.invoke.{agent}` | Request-reply agent invocation |
| `lattice.work.assign.{station}` | Async work assignment |
| `lattice.work.result.{work_id}` | Work completion results |
### Adding New Message Types
1. **Define the message struct** in `internal/lattice/messages.go`:
```go theme={null}
type MyNewMessage struct {
Type string `json:"type"`
StationID string `json:"station_id"`
Payload string `json:"payload"`
Timestamp time.Time `json:"timestamp"`
}
```
2. **Add publisher function** in appropriate file:
```go theme={null}
func (c *Client) PublishMyNewMessage(msg *MyNewMessage) error {
data, err := json.Marshal(msg)
if err != nil {
return fmt.Errorf("marshal message: %w", err)
}
return c.nc.Publish("lattice.my.subject", data)
}
```
### Testing Lattice Code
```bash theme={null}
# Run all lattice tests
go test ./internal/lattice/... -v
# Run E2E lattice tests (requires clean environment)
go test ./internal/lattice/e2e/... -v -timeout 5m
# Test with race detection
go test ./internal/lattice/... -race -v
```
### Common Gotchas
1. **Always close NATS connections** - Use `defer client.Close()` to prevent resource leaks
2. **JetStream KV eventual consistency** - Allow small delays when testing KV operations
3. **Port conflicts** - Use unique ports in tests to avoid conflicts with running stations
4. **Heartbeat timing** - Default heartbeat is 5s; tests may need shorter intervals
## Next Steps
Deep dive into system architecture
Running and writing tests
# Contributing Overview
Source: https://docs.cloudshipai.com/contributing/overview
Architecture and development guide for Station contributors
# Contributing to Station
This section covers Station's internal architecture, development setup, and testing for contributors.
## Architecture Overview
Station is a **modular, service-oriented AI agent orchestration platform** built in Go.
### Four-Layer Architecture
```
┌─────────────────────────────────────────────────────────────────┐
│ PRESENTATION LAYER │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ CLI │ │ API │ │ MCP Server │ │
│ │ (cmd/main) │ │ (:8585) │ │ (stdio) │ │
│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │
├─────────┼─────────────────┼─────────────────┼───────────────────┤
│ └─────────────────┼─────────────────┘ │
│ ▼ │
│ SERVICE LAYER │
│ ┌─────────────────────────────────┐ │
│ │ 43+ Focused Service Modules │ │
│ │ (internal/services/) │ │
│ └─────────────────┬───────────────┘ │
├───────────────────────────┼─────────────────────────────────────┤
│ ▼ │
│ DATA ACCESS LAYER │
│ ┌─────────────────────────────────┐ │
│ │ 11 Repository Modules │ │
│ │ (internal/db/repositories/) │ │
│ └─────────────────┬───────────────┘ │
├───────────────────────────┼─────────────────────────────────────┤
│ ▼ │
│ PERSISTENCE LAYER │
│ ┌──────────────────┐ ┌──────────────────┐ │
│ │ SQLite Database │ │ File System │ │
│ │ (station.db) │ │ (environments/) │ │
│ └──────────────────┘ └──────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
```
### Unified Execution Engine
All entry points converge at the **AgentExecutionEngine**:
| Entry Point | Path | Handler |
| ----------- | --------------------------------- | -------------------------------- |
| CLI | `stn agent run` | `cmd/main/handlers/agent/` |
| API | `POST /api/v1/agents/:id/execute` | `internal/api/v1/` |
| MCP | `call_agent` tool | `internal/mcp/` |
| Scheduler | Cron trigger | `internal/services/scheduler.go` |
### Core Services
| Category | Services |
| -------------- | ------------------------------------------------------------ |
| **Execution** | AgentService, AgentExecutionEngine, GenKitProvider |
| **MCP** | MCPConnectionManager, MCPToolDiscovery, ToolDiscoveryService |
| **Config** | DeclarativeSync, EnvironmentManagementService, AgentFileSync |
| **Scheduling** | SchedulerService |
| **Telemetry** | TelemetryService, DeploymentContextService |
## Repository Structure
```
station/
├── cmd/main/ # CLI entry point
│ └── handlers/ # CLI command handlers
├── internal/
│ ├── api/v1/ # REST API handlers
│ ├── config/ # Configuration loading
│ ├── db/ # Database layer
│ │ ├── repositories/ # Data access
│ │ └── schema.sql # Database schema
│ ├── mcp/ # MCP server implementation
│ ├── services/ # Business logic (43+ modules)
│ └── workflows/ # Workflow engine
├── pkg/ # Public packages
├── bundles/ # Agent bundles
└── docs/
└── architecture/ # Detailed architecture docs
```
## Key Files
| Component | Location |
| --------------- | --------------------------------------------- |
| Agent execution | `internal/services/agent_execution_engine.go` |
| MCP management | `internal/services/mcp_*.go` |
| Sync service | `internal/services/declarative_sync.go` |
| API handlers | `internal/api/v1/*.go` |
| CLI handlers | `cmd/main/handlers/` |
| Database schema | `internal/db/schema.sql` |
| MCP server | `internal/mcp/server.go` |
| Config loading | `internal/config/config.go` |
## Next Steps
Set up your local development environment
Detailed diagrams and component analysis
Running and writing tests
Conventions and best practices
# Testing Guide
Source: https://docs.cloudshipai.com/contributing/testing
Running and writing tests for Station
# Testing Guide
Station has comprehensive test coverage across unit, integration, and end-to-end tests.
## Running Tests
### All Tests
```bash theme={null}
# Run all tests
make test
# Or directly with Go
go test ./...
# With verbose output
go test ./... -v
# With race detection
go test ./... -race
```
### Specific Packages
```bash theme={null}
# Test a specific package
go test ./internal/services/... -v
# Test a specific file
go test ./internal/services/agent_service_test.go -v
# Test a specific function
go test ./internal/services -run TestAgentExecution -v
```
### Test Coverage
```bash theme={null}
# Generate coverage report
make test-coverage
# Or manually
go test ./... -coverprofile=coverage.out
go tool cover -html=coverage.out -o coverage.html
# View coverage in terminal
go tool cover -func=coverage.out
```
Current test coverage: **\~52.7%**
## Test Structure
```
station/
├── cmd/main/handlers/
│ └── agent/
│ ├── execution.go
│ └── execution_test.go # Handler tests
├── internal/
│ ├── services/
│ │ ├── agent_service.go
│ │ └── agent_service_test.go # Service tests
│ ├── api/v1/
│ │ ├── agents.go
│ │ └── agents_test.go # API tests
│ └── db/repositories/
│ ├── agent_repository.go
│ └── agent_repository_test.go # Repository tests
└── tests/
└── integration/ # Integration tests
```
## Writing Tests
### Unit Test Pattern
```go theme={null}
package services
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestAgentService_Execute(t *testing.T) {
// Arrange
ctx := context.Background()
svc := NewAgentService(mockRepo, mockEngine)
tests := []struct {
name string
agentID int64
task string
want string
wantErr bool
}{
{
name: "successful execution",
agentID: 1,
task: "Hello",
want: "Response",
wantErr: false,
},
{
name: "agent not found",
agentID: 999,
task: "Hello",
want: "",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Act
got, err := svc.Execute(ctx, tt.agentID, tt.task)
// Assert
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
assert.Equal(t, tt.want, got)
})
}
}
```
### Table-Driven Tests
Station uses table-driven tests extensively:
```go theme={null}
func TestValidateCronExpression(t *testing.T) {
tests := []struct {
name string
expression string
valid bool
}{
{"valid 6-field", "0 0 9 * * *", true},
{"valid 5-field", "0 9 * * *", true},
{"invalid format", "not-a-cron", false},
{"empty", "", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidateCronExpression(tt.expression)
if tt.valid {
assert.NoError(t, err)
} else {
assert.Error(t, err)
}
})
}
}
```
### Mocking
Station uses interfaces for testability. Generate mocks with:
```bash theme={null}
make mocks
```
Example mock usage:
```go theme={null}
type MockAgentRepository struct {
mock.Mock
}
func (m *MockAgentRepository) GetByID(ctx context.Context, id int64) (*Agent, error) {
args := m.Called(ctx, id)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(*Agent), args.Error(1)
}
func TestWithMock(t *testing.T) {
mockRepo := new(MockAgentRepository)
mockRepo.On("GetByID", mock.Anything, int64(1)).
Return(&Agent{ID: 1, Name: "test"}, nil)
svc := NewAgentService(mockRepo)
agent, err := svc.Get(context.Background(), 1)
require.NoError(t, err)
assert.Equal(t, "test", agent.Name)
mockRepo.AssertExpectations(t)
}
```
### Integration Tests
Integration tests use real databases and services:
```go theme={null}
func TestIntegration_AgentExecution(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
// Setup real database
db, cleanup := setupTestDB(t)
defer cleanup()
// Create real services
repos := repositories.New(db)
svc := services.NewAgentService(repos)
// Run integration test
// ...
}
```
Run integration tests:
```bash theme={null}
# Run all tests including integration
go test ./... -v
# Skip integration tests
go test ./... -short
```
### API Tests
```go theme={null}
func TestAPI_CreateAgent(t *testing.T) {
// Setup test server
router := setupTestRouter()
// Create request
body := `{"name": "test-agent", "prompt": "You are helpful"}`
req := httptest.NewRequest("POST", "/api/v1/agents", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer test-token")
// Execute
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
// Assert
assert.Equal(t, http.StatusCreated, w.Code)
var response map[string]interface{}
err := json.Unmarshal(w.Body.Bytes(), &response)
require.NoError(t, err)
assert.Equal(t, "test-agent", response["name"])
}
```
### Database Tests
```go theme={null}
func TestRepository_AgentCRUD(t *testing.T) {
// Use in-memory SQLite for tests
db, err := sql.Open("sqlite3", ":memory:")
require.NoError(t, err)
defer db.Close()
// Run migrations
_, err = db.Exec(schema)
require.NoError(t, err)
repo := NewAgentRepository(db)
// Test Create
agent := &Agent{Name: "test", Prompt: "Hello"}
id, err := repo.Create(context.Background(), agent)
require.NoError(t, err)
assert.Greater(t, id, int64(0))
// Test Read
found, err := repo.GetByID(context.Background(), id)
require.NoError(t, err)
assert.Equal(t, "test", found.Name)
// Test Update
found.Name = "updated"
err = repo.Update(context.Background(), found)
require.NoError(t, err)
// Test Delete
err = repo.Delete(context.Background(), id)
require.NoError(t, err)
}
```
## Test Helpers
### Test Database Setup
```go theme={null}
func setupTestDB(t *testing.T) (*sql.DB, func()) {
t.Helper()
// Create temp file
f, err := os.CreateTemp("", "station-test-*.db")
require.NoError(t, err)
f.Close()
// Open database
db, err := sql.Open("sqlite3", f.Name())
require.NoError(t, err)
// Run migrations
_, err = db.Exec(schema.SQL)
require.NoError(t, err)
cleanup := func() {
db.Close()
os.Remove(f.Name())
}
return db, cleanup
}
```
### Test Fixtures
```go theme={null}
func createTestAgent(t *testing.T, repo AgentRepository) *Agent {
t.Helper()
agent := &Agent{
Name: "test-agent-" + randomString(8),
Prompt: "You are a test agent",
MaxSteps: 5,
Environment: "default",
}
id, err := repo.Create(context.Background(), agent)
require.NoError(t, err)
agent.ID = id
return agent
}
```
## Continuous Integration
Tests run automatically on:
* Every push to `main`
* Every pull request
* Release tag creation
CI configuration runs:
```yaml theme={null}
# .github/workflows/test.yml
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.21'
- run: make test
- run: make lint
```
## Testing Best Practices
1. **Test behavior, not implementation** - Focus on what the code does, not how
2. **Use table-driven tests** - Makes adding test cases easy
3. **Mock at boundaries** - Mock external services, not internal code
4. **Keep tests fast** - Use in-memory databases, skip slow tests with `-short`
5. **Test error cases** - Ensure errors are handled correctly
6. **Clean up resources** - Use `defer` for cleanup
7. **Use meaningful names** - Test names should describe the scenario
## Next Steps
Coding conventions and standards
Understanding the codebase structure
# Introduction
Source: https://docs.cloudshipai.com/introduction
Welcome to CloudShip AI - Deploy AI agents anywhere
## What is CloudShip AI?
CloudShip AI is a platform for building, deploying, and managing AI agents at scale. It consists of two main components:
A lightweight runtime for deployable sub-agents with MCP tool integration. Run locally or in Docker.
Centralized management, monitoring, and bundle distribution for your Station deployments.
## Key Features
Create, configure, and run AI agents with support for OpenAI, Gemini, Anthropic, and custom providers.
Connect to any Model Context Protocol (MCP) server to extend your agents with powerful tools.
Package and distribute agent configurations as portable bundles. Install from CloudShip or custom registries.
Built-in OpenTelemetry integration with Jaeger for distributed tracing and monitoring.
## Quick Links
Install Station CLI in under a minute
Get your first agent running in 5 minutes
Explore the Station REST API
# Platform Bundles
Source: https://docs.cloudshipai.com/platform/bundles
Bundle management in CloudShip Platform
## Bundle Registry
CloudShip Platform hosts a bundle registry for sharing agent configurations across your organization.
## Uploading Bundles
### Via CLI
```bash theme={null}
# Upload from environment
stn bundle share production
# Upload existing bundle file
stn bundle share ./my-bundle.tar.gz
```
### Via Dashboard
1. Go to **Bundles** in CloudShip dashboard
2. Click **Upload Bundle**
3. Drag and drop your `.tar.gz` file
4. Add metadata (name, description, tags)
5. Click **Publish**
## Installing from CloudShip
```bash theme={null}
# Install by UUID
stn bundle install e26b414a-f076-4135-927f-810bc1dc892a my-environment
# Install with stn up
stn up --bundle e26b414a-f076-4135-927f-810bc1dc892a
```
## Bundle Visibility
| Visibility | Access |
| ---------------- | ---------------------- |
| **Private** | Only your organization |
| **Organization** | All org members |
| **Public** | Anyone (with link) |
## Cherry-Pick Manifests
Select specific agents from multiple bundles:
```json theme={null}
{
"sources": [
{
"bundle_id": "e26b414a-f076-4135-927f-810bc1dc892a",
"agents": ["security-scanner", "code-reviewer"]
},
{
"bundle_id": "f37c525b-g187-5246-a38g-921cd2ed933b",
"agents": ["devops-helper"]
}
]
}
```
Create custom bundle from manifest:
```bash theme={null}
curl -X POST https://app.cloudshipai.com/api/registry/custom-bundle/ \
-H "Authorization: Bearer $CLOUDSHIP_TOKEN" \
-d @manifest.json \
--output custom-bundle.tar.gz
```
## Version Management
### Semantic Versioning
Bundles support semantic versioning:
```json theme={null}
{
"name": "security-bundle",
"version": "1.2.3"
}
```
### Installing Specific Versions
```bash theme={null}
stn bundle install security-bundle@1.2.3 my-env
```
### Latest vs Pinned
* **Latest**: Always get newest version
* **Pinned**: Lock to specific version for reproducibility
## Organization Bundles
### Sharing Within Org
When you upload a bundle, choose organization visibility:
```bash theme={null}
stn bundle share ./bundle.tar.gz --visibility organization
```
### Team Permissions
| Role | Can Upload | Can Install | Can Delete |
| ------ | ---------- | ----------- | ---------- |
| Admin | ✓ | ✓ | ✓ |
| Member | ✓ | ✓ | Own only |
| Viewer | ✗ | ✓ | ✗ |
## Bundle Analytics
CloudShip tracks:
* Download counts
* Active installations
* Error rates
* Popular agents
View analytics in dashboard under **Bundles → Analytics**.
# Lighthouse
Source: https://docs.cloudshipai.com/platform/lighthouse
The CloudShip communication service
## What is Lighthouse?
Lighthouse is the gRPC service that enables communication between CloudShip Platform and registered Stations.
## Features
* **Bidirectional Streaming** - Real-time command dispatch and response
* **Station Management** - Track connected Stations and their capabilities
* **Secure Communication** - TLS-encrypted gRPC channels
* **Load Balancing** - Distribute commands across healthy Stations
## Architecture
```mermaid theme={null}
sequenceDiagram
participant CloudShip
participant Lighthouse
participant Station
Station->>Lighthouse: Register (registration_key)
Lighthouse->>Station: Connection Accepted
loop Management Channel
Station->>Lighthouse: Status Update
Lighthouse->>Station: Commands
end
CloudShip->>Lighthouse: Execute Agent
Lighthouse->>Station: Agent Task
Station->>Lighthouse: Agent Response
Lighthouse->>CloudShip: Result
```
## Communication Protocol
### Registration
Station connects with registration key:
```protobuf theme={null}
service Lighthouse {
rpc Register(RegisterRequest) returns (RegisterResponse);
rpc ManagementChannel(stream StationMessage) returns (stream LighthouseMessage);
}
```
### Commands
Lighthouse sends commands to Stations:
| Command | Description |
| ---------------- | ---------------------------- |
| `EXECUTE_AGENT` | Run an agent with task |
| `LIST_AGENTS` | Get available agents |
| `LIST_TOOLS` | Get available MCP tools |
| `INSTALL_BUNDLE` | Install bundle from registry |
| `SYNC` | Trigger configuration sync |
## Self-Hosted Lighthouse
For enterprise deployments, run your own Lighthouse:
### Requirements
* PostgreSQL database
* Redis (optional, for caching)
* TLS certificates
### Docker Deployment
```yaml theme={null}
services:
lighthouse:
image: ghcr.io/cloudshipai/lighthouse:latest
ports:
- "50051:50051"
environment:
- DATABASE_URL=postgresql://user:pass@postgres:5432/lighthouse
- GRPC_PORT=50051
- LOG_LEVEL=info
volumes:
- ./certs:/certs:ro
```
### Configuration
```yaml theme={null}
# lighthouse.yaml
grpc:
port: 50051
tls:
enabled: true
cert_file: /certs/server.crt
key_file: /certs/server.key
database:
url: postgresql://user:pass@localhost:5432/lighthouse
max_connections: 100
redis:
url: redis://localhost:6379/0
```
## Local Development
Run Lighthouse locally for testing:
```bash theme={null}
cd cloudshipai/infrastructure/lighthouse
go run cmd/main.go
```
Configure Station to connect:
```yaml theme={null}
# Station config.yaml
cloudship:
enabled: true
registration_key: "test-key"
endpoint: localhost:50051
use_tls: false # Disable TLS for local dev
```
## Monitoring
Lighthouse exposes metrics:
| Metric | Description |
| ------------------------------------- | ---------------------------- |
| `lighthouse_stations_connected` | Number of connected Stations |
| `lighthouse_commands_total` | Total commands processed |
| `lighthouse_command_duration_seconds` | Command execution time |
| `lighthouse_errors_total` | Error count |
Access metrics at `/metrics` endpoint.
## Troubleshooting
### Station Won't Connect
```
Error: connection refused
```
Check:
* Lighthouse is running
* Port 50051 is accessible
* TLS configuration matches
### Commands Timeout
```
Error: deadline exceeded
```
Check:
* Station is responsive
* Network latency
* Command timeout settings
### Authentication Failed
```
Error: invalid registration key
```
Check:
* Registration key is valid
* Key hasn't been used before
* Organization permissions
# Platform Overview
Source: https://docs.cloudshipai.com/platform/overview
CloudShip AI platform for centralized Station management
## What is CloudShip Platform?
CloudShip Platform provides centralized management for your Station deployments:
Register and manage multiple Station instances from one dashboard
Create, share, and install agent bundles across your organization
Centralized telemetry, logging, and performance metrics
OAuth-based authentication for secure MCP access
## Architecture
```mermaid theme={null}
graph TB
subgraph "CloudShip Platform"
Dashboard[Web Dashboard]
Lighthouse[Lighthouse Service]
Registry[Bundle Registry]
Telemetry[Telemetry Collector]
end
subgraph "Customer Infrastructure"
Station1[Station 1]
Station2[Station 2]
Station3[Station 3]
end
Station1 --> Lighthouse
Station2 --> Lighthouse
Station3 --> Lighthouse
Lighthouse --> Dashboard
Telemetry --> Dashboard
Registry --> Dashboard
```
## Key Components
### Lighthouse
The Lighthouse service provides:
* **gRPC Communication** - Secure bidirectional streaming with Stations
* **Command Dispatch** - Remote agent execution
* **Status Monitoring** - Real-time Station health
* **Bundle Delivery** - Push bundles to registered Stations
### Bundle Registry
Store and distribute agent configurations:
* **Version Control** - Track bundle versions
* **Access Control** - Organization-level permissions
* **Cherry-Pick** - Select specific agents from bundles
### Dashboard
Web interface for:
* Station registration and management
* Bundle creation and distribution
* Agent execution and monitoring
* Team collaboration
## Getting Started
Sign up at [app.cloudshipai.com](https://app.cloudshipai.com)
Set up your organization and invite team members
Generate a registration key for your Station
Connect your Station using the registration key
## Pricing
| Plan | Stations | Features |
| -------------- | --------- | ----------------------------------- |
| **Free** | 1 | Basic monitoring, public bundles |
| **Team** | 10 | Private bundles, team collaboration |
| **Enterprise** | Unlimited | SSO, audit logs, dedicated support |
## Next Steps
Register your Station with CloudShip
Learn about the bundle system
# Station Registration
Source: https://docs.cloudshipai.com/platform/registration
Connect your Station to CloudShip Platform
## Overview
Registering your Station with CloudShip enables:
* Remote agent execution
* Centralized monitoring
* Bundle distribution
* OAuth authentication for MCP
## Getting a Registration Key
Go to [app.cloudshipai.com](https://app.cloudshipai.com) and sign in
Click **Stations** in the sidebar
Click **New Registration Key** and give it a name
Copy the generated key (it won't be shown again)
## Registering Your Station
### During Init
```bash theme={null}
stn init --provider openai \
--cloudship-key "your-registration-key" \
--cloudship-endpoint "lighthouse.cloudship.ai:443" \
--yes
```
### Existing Station
Edit `~/.config/station/config.yaml`:
```yaml theme={null}
local_mode: false
cloudship:
enabled: true
registration_key: "your-registration-key"
endpoint: lighthouse.cloudship.ai:443
```
Then restart Station:
```bash theme={null}
stn down && stn up
# or
pkill stn && stn serve
```
### Via Environment Variables
```bash theme={null}
export STN_CLOUDSHIP_KEY="your-registration-key"
export STN_CLOUDSHIP_ENDPOINT="lighthouse.cloudship.ai:443"
export STATION_LOCAL_MODE="false"
stn serve
```
## Verification
After registration, verify the connection:
```bash theme={null}
stn status
```
You should see:
```
Station Status
├─ Mode: CloudShip Connected
├─ Registration: Active
├─ Lighthouse: lighthouse.cloudship.ai:443
└─ Station ID: abc123
```
In the CloudShip dashboard, your Station will appear in the **Stations** list.
## What Happens After Registration
Once registered, your Station:
1. **Opens a management channel** to Lighthouse
2. **Reports status** periodically (health, agents, tools)
3. **Receives commands** for remote execution
4. **Sends telemetry** if enabled
## Security
### Connection Security
* All communication uses **TLS encryption**
* Registration keys are **one-time use**
* Station authenticates with Lighthouse on each connection
### Data Privacy
* Agent prompts stay on your Station
* Only execution results are sent to CloudShip (if requested)
* Telemetry is opt-in
### Revoking Access
To disconnect a Station:
1. In CloudShip dashboard, go to **Stations**
2. Click the Station you want to remove
3. Click **Revoke Registration**
Or locally:
```yaml theme={null}
# config.yaml
local_mode: true
cloudship:
enabled: false
```
## Local Development with Lighthouse
For testing CloudShip integration locally:
```bash theme={null}
# Start local Lighthouse (in cloudshipai repo)
cd cloudshipai/lighthouse
go run cmd/main.go
# Configure Station to use local Lighthouse
stn init --provider openai \
--cloudship-key "test-key" \
--cloudship-endpoint "localhost:50051" \
--yes
```
Local Lighthouse requires additional setup. See [Lighthouse documentation](/platform/lighthouse).
## Troubleshooting
### Connection Failed
```
Error: failed to connect to Lighthouse
```
Check:
* Internet connectivity
* Registration key validity
* Endpoint URL (should include port)
### Registration Rejected
```
Error: registration key invalid or expired
```
Generate a new registration key in the CloudShip dashboard.
### Already Registered
```
Error: station already registered
```
Each registration key can only be used once. Either:
* Use a new registration key
* Delete the existing Station in CloudShip dashboard
# Quickstart
Source: https://docs.cloudshipai.com/quickstart
Get Station running in 2 minutes
## Prerequisites
* **Docker** - Required for:
* [Jaeger](https://www.jaegertracing.io/) - OTEL tracing backend for observability
* [Ship CLI](https://github.com/cloudshipai/ship) - MCP tools for filesystem operations
* [Sandbox](/station/sandbox) - Isolated container for agent code execution
* [`stn up`](/station/docker) - Run environments/bundles in containers
* **AI Provider** - Choose one:
* **OpenAI API Key** (recommended) - gpt-5, gpt-5-mini, etc.
* **Google Gemini API Key**
* **Anthropic API Key** - pay-per-token billing
## Step 1: Install Station
```bash theme={null}
curl -fsSL https://raw.githubusercontent.com/cloudshipai/station/main/install.sh | bash
```
Verify the installation:
```bash theme={null}
stn --version
```
## Step 2: Initialize with Your AI Provider
**Anthropic OAuth Unavailable**: Anthropic has restricted third-party OAuth tokens. Claude Max/Pro subscription authentication is **not working until further notice**. Please use API key authentication instead.
```bash theme={null}
export OPENAI_API_KEY="sk-..."
stn init --provider openai --ship
```
Defaults to gpt-5-mini.
```bash theme={null}
export GEMINI_API_KEY="..."
stn init --provider gemini --ship
```
```bash theme={null}
export ANTHROPIC_API_KEY="sk-ant-api03-..."
stn init --provider anthropic --ship
```
Uses pay-per-token billing (not Claude Max/Pro subscription).
**What is Ship?** [Ship](https://github.com/cloudshipai/ship) is an MCP CLI tool that provides filesystem and development tools for Station agents.
### Git-Backed Workspace (Optional)
For version-controlled agent configurations:
```bash theme={null}
# Initialize in a specific directory
stn init --provider openai --ship --config ~/my-station-workspace
# Your agents, MCP configs, and variables are now version-controllable
cd ~/my-station-workspace
git init && git add . && git commit -m "Initial Station config"
```
## Step 3: Start Jaeger (Tracing)
Start the Jaeger tracing backend for observability:
```bash theme={null}
stn jaeger up
```
Jaeger UI available at [http://localhost:16686](http://localhost:16686).
## Step 4: Connect Your MCP Client
```bash theme={null}
claude mcp add station -e OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 --scope user -- stn stdio
```
Verify: `claude mcp list`
**With custom workspace:**
```bash theme={null}
claude mcp add station -e OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 --scope user -- stn stdio --config ~/my-station-workspace
```
Edit your config file:
| OS | Path |
| ------- | ----------------------------------------------------------------- |
| macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |
| Windows | `%APPDATA%\Claude\claude_desktop_config.json` |
| Linux | `~/.config/Claude/claude_desktop_config.json` |
```json theme={null}
{
"mcpServers": {
"station": {
"command": "stn",
"args": ["stdio"],
"env": {
"OTEL_EXPORTER_OTLP_ENDPOINT": "http://localhost:4318"
}
}
}
}
```
**With custom workspace:**
```json theme={null}
{
"mcpServers": {
"station": {
"command": "stn",
"args": ["stdio", "--config", "/path/to/my-station-workspace"],
"env": {
"OTEL_EXPORTER_OTLP_ENDPOINT": "http://localhost:4318"
}
}
}
}
```
Add to `.cursor/mcp.json` in your project (or `~/.cursor/mcp.json` for global):
```json theme={null}
{
"mcpServers": {
"station": {
"command": "stn",
"args": ["stdio"],
"env": {
"OTEL_EXPORTER_OTLP_ENDPOINT": "http://localhost:4318"
}
}
}
}
```
Add to `opencode.jsonc`:
```jsonc theme={null}
{
"mcp": {
"station": {
"enabled": true,
"type": "local",
"command": ["stn", "stdio"],
"environment": {
"OTEL_EXPORTER_OTLP_ENDPOINT": "http://localhost:4318"
}
}
}
}
```
## Step 5: Start Using Station
Restart your editor. Station provides:
* **Web UI** at [http://localhost:8585](http://localhost:8585) for configuration
* **Jaeger UI** at [http://localhost:16686](http://localhost:16686) for traces
* **41 MCP tools** available in your AI assistant
**Try your first command:**
```
"Show me all Station MCP tools available"
```
## Step 6: Interactive Hands-On Tutorial (Optional)
Ready to dive deeper? Copy this prompt into your MCP client (Claude, Cursor, etc.) for a guided, interactive tour of Station's features:
```text theme={null}
You are my Station onboarding guide. Walk me through an interactive hands-on tutorial.
RULES:
1. Create a todo list to track progress through each section
2. At each section, STOP and let me engage before continuing
3. Use Station MCP tools to demonstrate - don't just explain, DO IT
4. Keep it fun and celebrate wins!
THE JOURNEY:
## 1. Hello World Agent
- Create a "hello-world" agent that greets users and tells a joke
- Call the agent and show the result
- NOTE: Agent execution may take 10-30 seconds depending on your AI model
- Point me to http://localhost:8585 to see the agent in the UI
[STOP for me to try it]
## 2. Faker Tools & MCP Templates
- Explain Faker tools (AI-generated mock data for safe development)
- Note: Real MCP tools are added via Station UI or template.json
- Explain MCP templates - they keep credentials safe when deploying
- Create a "prometheus-metrics" faker for realistic metrics
- IMPORTANT: Faker tool calls can take 30-60+ seconds as the AI generates realistic mock data. This is normal!
- Show me results at http://localhost:8585
[STOP to see the faker]
## 3. DevOps Investigation Agent
- Create a "metrics-investigator" agent using our prometheus faker
- Call it: "Check for performance issues in the last hour"
- NOTE: This may take a minute as the agent uses faker tools to simulate real metrics
- Direct me to http://localhost:8585 to inspect the run
[STOP to review the investigation]
## 4. Multi-Agent Hierarchy
- Create an "incident-coordinator" that delegates to:
- metrics-investigator (existing)
- logs-investigator (new - create a logs faker)
- Show hierarchy structure in the .prompt file
- Call coordinator: "Investigate why the API is slow"
- Multi-agent runs take longer as each agent executes sequentially
- Check out the delegation chain at http://localhost:8585
[STOP to see delegation]
## 5. Inspecting Runs
- Use inspect_run to show detailed execution
- Explain: tool calls, delegations, timing
- Compare with the visual view at http://localhost:8585
[STOP to explore]
## 6. Workflow with Human-in-the-Loop
- Create a workflow: investigate → switch on severity → human_approval if high → report
- Make it complex (switch/parallel), not sequential
- Start the workflow
- Show me the workflow state at http://localhost:8585
[STOP for me to approve/reject]
## 7. Evaluation & Reporting
- Run evals with evaluate_benchmark
- Generate a performance report
- View detailed metrics at http://localhost:8585
[STOP to review]
## 8. Grand Finale
- Direct me to http://localhost:8585 (Station UI)
- Quick tour: Agents, MCP servers, Runs, Workflows
- Celebrate!
## 9. Want More? (Optional)
Briefly explain these advanced features (no demo needed):
- **Schedules**: Cron-based agent scheduling
- **Sandboxes**: Isolated code execution (Python/Node/Bash)
- **Notify Webhooks**: Send alerts to Slack, ntfy, Discord
- **Bundles**: Package and share agent teams
- **Deploy**: `stn deploy` to Fly.io, Docker, K8s
- **CloudShip**: Centralized management and team OAuth
Start now with Section 1!
```
**Performance Note**: Faker tools generate AI-powered mock data, which can take 30-60+ seconds per call. This is normal! Real MCP tools (like Prometheus, Datadog) are much faster since they query actual APIs.
## Next Steps
Build custom AI agents with prompts and tools
Connect MCP servers to give your agents powerful tools
Create agent hierarchies with coordinators and specialists
Version control your agents and collaborate with your team
# Agentic Harness
Source: https://docs.cloudshipai.com/station/agentic-harness
Claude Agent SDK-like execution engine with doom loop detection, context compaction, and git integration
The **Agentic Harness** is an alternative execution engine for Station agents that provides advanced capabilities beyond the standard Genkit-based execution.
## Overview
Add `harness: agentic` to any agent's dotprompt file to enable:
* **Manual agentic loop** - Step-by-step control over agent execution
* **Doom loop detection** - Prevents agents from getting stuck in repetitive patterns
* **Context compaction** - Automatically summarizes history when approaching context limits
* **Git integration** - Auto-branch creation and commit management
* **Workspace isolation** - Sandboxed file system access
* **Built-in tools** - File and bash tools that work independently of MCP
## When to Use
| Use Case | Harness |
| ------------------------------- | ---------------- |
| Simple queries, quick responses | Default (Genkit) |
| Long-running coding tasks | `agentic` |
| Multi-step file operations | `agentic` |
| Tasks requiring git branches | `agentic` |
| Complex debugging/investigation | `agentic` |
## Agent Configuration
Enable the harness in your agent's dotprompt frontmatter:
```yaml theme={null}
---
model: anthropic/claude-sonnet-4-20250514
harness: agentic
harness_config:
max_steps: 50
doom_loop_threshold: 3
timeout: 10m
sandbox: # Optional: isolated execution environment
mode: docker # host | docker | e2b (experimental)
image: python:3.11-slim
tools:
- read
- write
- edit
- bash
- glob
- grep
---
You are a code analysis agent. Analyze the codebase and suggest improvements.
```
### Agent-Level Options
| Option | Default | Description |
| --------------------- | ------- | ----------------------------------------------------- |
| `max_steps` | 50 | Maximum tool call iterations |
| `doom_loop_threshold` | 3 | Consecutive identical calls to trigger loop detection |
| `timeout` | 10m | Maximum execution time |
| `sandbox` | null | Isolated execution environment (see below) |
### Sandbox Configuration
The `sandbox` option under `harness_config` controls WHERE tools execute:
```yaml theme={null}
harness_config:
sandbox:
mode: docker # Execution mode
image: python:3.11-slim # Docker image (for docker mode)
network: false # Disable network access
timeout: 5m # Per-command timeout
memory: 4g # Memory limit
cpu: 2 # CPU limit
environment: # Environment variables
PYTHONPATH: /workspace
```
**Sandbox Modes:**
| Mode | Description | File Persistence |
| -------- | -------------------------------------- | -------------------- |
| `host` | Tools execute directly on host machine | Yes |
| `docker` | Tools execute in Docker containers | Yes (volume mounted) |
| `e2b` | Tools execute in cloud VMs | No (experimental) |
**Docker mode** is recommended for production. Files persist across container restarts via volume mounting.
**E2B mode** is experimental - data doesn't persist between sandbox destroys.
## Global Configuration
Configure harness defaults in `config.yaml`. Running `stn init` sets sensible defaults:
```yaml theme={null}
harness:
workspace:
path: ./workspace
mode: host # "host" or "sandbox"
compaction:
enabled: true
threshold: 0.85 # Compact at 85% of context window
protect_tokens: 40000 # Keep last N tokens from compaction
git:
auto_branch: true
branch_prefix: agent/
auto_commit: false
require_approval: true
workflow_branch_strategy: shared
nats:
enabled: true
kv_bucket: harness-state
object_bucket: harness-files
max_file_size: 100MB
ttl: 24h
permissions:
external_directory: deny
```
## Key Features
### Doom Loop Detection
Detects when an agent is stuck repeating the same action:
```yaml theme={null}
# In dotprompt frontmatter
harness_config:
doom_loop_threshold: 3 # Trigger after 3 identical tool calls
```
When detected, the harness interrupts the loop and prompts the agent to try a different approach.
### Context Compaction
Automatically summarizes conversation history when approaching context limits:
```yaml theme={null}
harness:
compaction:
enabled: true
threshold: 0.85 # Start compacting at 85% of window
protect_tokens: 40000 # Never compact the last 40k tokens
```
The compactor uses the same model to create a summary, preserving important context while freeing up space for new interactions.
### Git Integration
Automatic branch creation for agent work:
```yaml theme={null}
harness:
git:
auto_branch: true # Create branches automatically
branch_prefix: agent/ # Branch naming: agent/task-name-timestamp-id
auto_commit: false # Require explicit commits
require_approval: true # Human approval before push
```
When enabled, the harness:
1. Creates a new branch when execution starts
2. Tracks all file changes
3. Can commit changes with generated messages
4. Supports push with approval workflow
### Workspace Isolation
Control where agents can read/write files:
```yaml theme={null}
harness:
workspace:
path: ./workspace # Root directory for agent operations
mode: host # "host" for direct access, "sandbox" for isolation
permissions:
external_directory: deny # Block access outside workspace
```
## Built-in Tools
The harness provides built-in tools that work independently of MCP servers:
| Tool | Description | Example |
| ------------ | -------------------------- | ----------------------------------------------- |
| `read` | Read file contents | `read(path: "src/main.go")` |
| `write` | Write file contents | `write(path: "out.txt", content: "...")` |
| `edit` | String replacement editing | `edit(path: "file.go", old: "foo", new: "bar")` |
| `bash` | Execute shell commands | `bash(command: "ls -la")` |
| `glob` | Find files by pattern | `glob(pattern: "**/*.go")` |
| `grep` | Search file contents | `grep(pattern: "TODO", path: "src/")` |
| `git_status` | Get git status | `git_status()` |
| `git_diff` | Get git diff | `git_diff()` |
| `git_log` | Get recent commits | `git_log(count: 10)` |
### Tool Permissions
Fine-grained control over tool capabilities:
```yaml theme={null}
harness:
permissions:
bash:
allow_write: false # Read-only commands
allowed_commands: # Whitelist
- ls
- cat
- grep
- find
blocked_commands: # Blacklist
- rm
- sudo
```
## Workflow Integration
Harness agents work seamlessly with Station workflows:
```yaml theme={null}
# workflow.yaml
id: code-review-pipeline
name: Code Review Pipeline
states:
- name: analyze
type: agent
agent: code-analyzer # Has harness: agentic
transition: report
- name: report
type: agent
agent: report-generator
transition: end
```
### Shared Git Branches in Workflows
When multiple agents collaborate on the same codebase:
```yaml theme={null}
harness:
git:
workflow_branch_strategy: shared # All workflow steps share one branch
```
## Example: Code Review Agent
```yaml theme={null}
---
model: anthropic/claude-sonnet-4-20250514
harness: agentic
harness_config:
max_steps: 100
timeout: 15m
tools:
- read
- glob
- grep
- bash
---
You are a senior code reviewer. Analyze the codebase for:
- Code quality issues
- Security vulnerabilities
- Performance problems
- Missing tests
Use glob to find relevant files, read to examine them, and grep to search for patterns.
Provide a detailed report with specific line numbers and suggested fixes.
```
## Example: Refactoring Agent
```yaml theme={null}
---
model: anthropic/claude-sonnet-4-20250514
harness: agentic
harness_config:
max_steps: 200
doom_loop_threshold: 5
tools:
- read
- write
- edit
- glob
- grep
- git_status
- git_diff
- bash
---
You are a refactoring specialist. Your task is to:
1. Understand the current code structure
2. Make targeted improvements
3. Ensure tests still pass
4. Commit changes with clear messages
Always run tests after changes: `bash(command: "go test ./...")`
Check your changes: `git_diff()`
```
## Observability
Harness executions are fully traced with OpenTelemetry:
```bash theme={null}
# View traces in Jaeger
stn jaeger up
# Open http://localhost:16686
```
Traces include:
* Each agentic loop iteration
* Tool calls with inputs/outputs
* Doom loop detection events
* Compaction events
* Git operations
## Testing
Run harness tests:
```bash theme={null}
# Unit tests
go test ./pkg/harness/... -v
# E2E tests with real LLM
HARNESS_E2E_TEST=1 go test ./pkg/harness/... -v -run "E2E" -timeout 5m
```
## Next Steps
Chain harness agents into multi-step workflows
Version control your agents and configurations
Isolated container execution for untrusted code
Monitor agent performance with Jaeger tracing
# Agent Development
Source: https://docs.cloudshipai.com/station/agents
Create AI agents using dotprompt format
## What Are Station Agents?
Station agents are AI-powered automation tools that:
* Execute multi-step tasks autonomously
* Access tools and APIs through MCP servers
* Run on your infrastructure with your credentials
Unlike ChatGPT or Claude, Station agents have direct access to your tools (AWS, databases, filesystems) and can execute complex workflows without copy-pasting commands.
## Dotprompt Format
Every agent is a `.prompt` file with YAML frontmatter and a template body:
```yaml theme={null}
---
metadata:
name: "Cost Analyzer"
description: "Analyzes AWS costs and finds savings"
tags: ["finops", "aws"]
model: gpt-4o-mini
max_steps: 8
tools:
- "__get_cost_and_usage"
- "__list_cost_allocation_tags"
---
{{role "system"}}
You are a FinOps analyst specializing in AWS cost analysis.
Your process:
1. Query AWS Cost Explorer for the past 30 days
2. Identify cost spikes exceeding 20% baseline
3. Break down costs by service
4. Provide actionable recommendations
{{role "user"}}
{{userInput}}
```
## Frontmatter Reference
| Field | Type | Required | Description |
| ---------------------- | ------- | -------- | --------------------------------- |
| `metadata.name` | string | Yes | Agent display name |
| `metadata.description` | string | Yes | What the agent does |
| `metadata.tags` | array | No | Categories for search |
| `model` | string | Yes | AI model to use |
| `max_steps` | integer | Yes | Maximum tool calls (5-15 typical) |
| `tools` | array | Yes | MCP tools the agent can use |
## Model Selection
| Model | Use Case | Speed | Cost |
| -------------------------- | ----------------------- | ------ | ------ |
| `gpt-4o-mini` | Simple tasks, file ops | Fast | Low |
| `gpt-4o` | Complex reasoning | Medium | Medium |
| `claude-3-5-sonnet-latest` | Code analysis, security | Medium | Medium |
## Creating Agents
```bash theme={null}
# Interactive creation
stn agent create
# With flags
stn agent create --name "my-agent" --model gpt-4o-mini
```
Create a `.prompt` file in your environment's agents directory:
```
~/.config/station/environments/default/agents/my-agent.prompt
```
## Running Agents
```bash theme={null}
# Run an agent
stn agent run "Cost Analyzer" "Analyze last month's AWS spending"
# With real-time output
stn agent run "Cost Analyzer" "Find cost savings" --tail
```
## Discovering Tools
List available MCP tools for your agents:
```bash theme={null}
# All tools in current environment
stn mcp tools
# Search for specific tools
stn mcp tools | grep aws
```
## Coding Backends
Agents can be enhanced with coding capabilities that allow them to read, write, and modify files.
### OpenCode Backend
Enable AI coding with filesystem access via OpenCode:
```yaml theme={null}
---
metadata:
name: "Code Assistant"
description: "AI coding assistant"
model: openai/gpt-4o
coding:
enabled: true
---
You are an expert software engineer. Use coding tools to implement features.
```
This gives the agent these tools:
| Tool | Description |
| --------------- | ------------------------------------------ |
| `coding_open` | Start a coding session in a directory |
| `code` | Execute coding tasks (read/write/refactor) |
| `coding_close` | End the session |
| `coding_commit` | Commit changes to git |
| `coding_push` | Push to remote repository |
The transport mechanism (HTTP or NATS) is configured at the Station level, not per-agent. This makes agent definitions portable across different deployments. See [OpenCode Backend](/station/opencode) for backend configuration.
### Coding Frontmatter Options
| Field | Type | Required | Description |
| ----------------------- | ------- | -------- | ---------------------------------- |
| `coding.enabled` | boolean | Yes | Enable coding tools for this agent |
| `coding.workspace_path` | string | No | Default workspace directory |
Full guide to OpenCode integration, HTTP vs NATS backends, and container mode
### Sandbox Backend
For isolated code execution in containers (different from OpenCode), use the sandbox backend:
```yaml theme={null}
---
model: openai/gpt-4o
sandbox:
mode: code
session: workflow
---
```
Run code safely in isolated Docker containers
## Notifications
Enable agents to send webhook notifications (ntfy, Slack, or any webhook endpoint):
```yaml theme={null}
---
model: anthropic/claude-sonnet-4-20250514
notify: true
---
You are a monitoring agent. Send notifications when tasks complete or issues arise.
```
This gives the agent the `notify` tool with parameters:
| Parameter | Description |
| ---------- | ------------------------------------------------- |
| `message` | Notification content (required) |
| `title` | Subject line (optional) |
| `priority` | `min`, `low`, `default`, `high`, `urgent` |
| `tags` | Emoji tags like `["warning", "white_check_mark"]` |
Full guide to webhook configuration and formats
## Next Steps
Send webhook notifications from agents
Connect agents to external services
Build hierarchical agent teams
Orchestrate multi-step agent tasks
Test and score your agents
# Approval Webhooks
Source: https://docs.cloudshipai.com/station/approval-webhooks
Get notified when workflows need human approval via webhooks to Slack, ntfy, PagerDuty, or custom systems
## Overview
When a workflow reaches a `human_approval` step, Station can notify external systems via webhooks. This enables human-in-the-loop automation with:
* **Slack notifications** with approve/reject buttons
* **ntfy.sh alerts** for mobile push notifications
* **PagerDuty escalations** for critical decisions
* **Custom dashboards** showing pending approvals
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ APPROVAL WEBHOOK FLOW │
└─────────────────────────────────────────────────────────────────────────────┘
┌──────────────┐
│ Workflow │
│ Running │
└──────┬───────┘
│
▼
┌───────────────────────┐
│ human_approval │
│ step │
└───────────┬───────────┘
│
▼
┌───────────────────────┐ ┌─────────────────────────────────────┐
│ Create Approval │ │ WEBHOOK NOTIFICATION │
│ Record in DB │ │ │
└───────────┬───────────┘ │ POST https://ntfy.sh/your-topic │
│ │ │
├────────────────▶│ { │
│ │ "event": "approval.requested", │
│ │ "approval_id": "appr-abc123", │
│ │ "message": "Approve deploy?", │
│ │ "approve_url": "http://...", │
│ │ "reject_url": "http://..." │
│ │ } │
│ └─────────────────────────────────────┘
│
▼
┌───────────────────────┐
│ WORKFLOW PAUSED │◄───────────────────────────────┐
│ (waiting_approval) │ │
└───────────┬───────────┘ │
│ │
│ Human reviews notification │
│ │
▼ │
┌──────────────┐ │
│ Decision │ │
└──────┬───────┘ │
│ │
┌───────┴───────┐ │
│ │ │
▼ ▼ │
┌────────┐ ┌──────────┐ │
│APPROVE │ │ REJECT │ │
└───┬────┘ └────┬─────┘ │
│ │ API Call │
│ ├───────────────────────────────────►│
│ │ POST /workflow-approvals/{id}/reject
│ API Call │ │
├──────────────┼───────────────────────────────────►│
│ │ POST /workflow-approvals/{id}/approve
▼ ▼
┌────────────────────────┐
│ Workflow Continues │
│ or Fails │
└────────────────────────┘
```
## Configuration
### Config File
Add to your `config.yaml`:
```yaml theme={null}
notifications:
# Webhook URL to POST when approval is requested
approval_webhook_url: "https://ntfy.sh/station-approvals"
# Timeout for webhook delivery (default: 10 seconds)
approval_webhook_timeout: 10
```
### Environment Variables
```bash theme={null}
export STN_APPROVAL_WEBHOOK_URL="https://ntfy.sh/station-approvals"
export STN_APPROVAL_WEBHOOK_TIMEOUT=10
```
## Webhook Payload
When a workflow reaches a `human_approval` step, Station sends:
```json theme={null}
{
"event": "approval.requested",
"approval_id": "appr-run123-approve_deploy",
"workflow_id": "deploy-production",
"workflow_name": "Production Deployment",
"run_id": "run-abc123",
"step_name": "approve_deploy",
"message": "Approve deployment of api-service v2.3.0 to production?",
"approvers": ["oncall-sre", "platform-leads"],
"timeout_seconds": 1800,
"created_at": "2025-01-04T17:30:00Z",
"approve_url": "http://localhost:8587/workflow-approvals/appr-run123-approve_deploy/approve",
"reject_url": "http://localhost:8587/workflow-approvals/appr-run123-approve_deploy/reject"
}
```
### Payload Fields
| Field | Type | Description |
| ----------------- | ------ | ---------------------------------------------------- |
| `event` | string | Always `"approval.requested"` |
| `approval_id` | string | Unique ID for this approval request |
| `workflow_id` | string | ID of the workflow definition |
| `workflow_name` | string | Human-readable workflow name |
| `run_id` | string | ID of this workflow run instance |
| `step_name` | string | Name of the approval step |
| `message` | string | Human-readable message (supports template variables) |
| `approvers` | array | List of allowed approvers (optional) |
| `timeout_seconds` | int | Seconds until approval expires |
| `created_at` | string | ISO 8601 timestamp |
| `approve_url` | string | URL to POST for approval |
| `reject_url` | string | URL to POST for rejection |
## Integration Examples
### ntfy.sh
[ntfy](https://ntfy.sh) is a simple HTTP-based pub-sub notification service - perfect for mobile push notifications.
Get it on [Android](https://play.google.com/store/apps/details?id=io.heckel.ntfy) or [iOS](https://apps.apple.com/us/app/ntfy/id1625396347)
Open the app and subscribe to `station-approvals` (or your chosen topic name)
```yaml theme={null}
notifications:
approval_webhook_url: https://ntfy.sh/station-approvals
approval_webhook_timeout: 10
```
```bash theme={null}
curl -d "Test notification from Station" https://ntfy.sh/station-approvals
```
For rich notifications with titles, priorities, and action buttons, use a webhook proxy that transforms Station's JSON payload into ntfy's format. See the advanced examples below.
### Slack
Configure a Slack Incoming Webhook:
```yaml theme={null}
notifications:
approval_webhook_url: "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXX"
```
For interactive approve/reject buttons, you'll need a small webhook proxy to transform the payload into Slack Block Kit format:
```json theme={null}
{
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Approval Required*\n\nApprove deployment of `api-service v2.3.0` to production?"
}
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": { "type": "plain_text", "text": "Approve" },
"style": "primary",
"url": "http://station:8587/workflow-approvals/appr-abc123/approve"
},
{
"type": "button",
"text": { "type": "plain_text", "text": "Reject" },
"style": "danger",
"url": "http://station:8587/workflow-approvals/appr-abc123/reject"
}
]
}
]
}
```
### PagerDuty
Send approval requests as PagerDuty incidents:
```yaml theme={null}
notifications:
approval_webhook_url: "https://events.pagerduty.com/v2/enqueue"
```
You'll need a webhook proxy to transform to PagerDuty Events API v2 format.
### Custom Webhook Proxy
Build a simple proxy to transform Station's payload for any system:
```python theme={null}
from flask import Flask, request
import requests
app = Flask(__name__)
NTFY_TOPIC = "https://ntfy.sh/station-approvals"
@app.route('/webhook', methods=['POST'])
def handle_approval():
data = request.json
# Build ntfy message with actions
message = f"{data['message']}\n\nWorkflow: {data['workflow_name']}"
headers = {
"Title": "Approval Required",
"Priority": "high",
"Tags": "warning",
"Actions": f"http, Approve, {data['approve_url']}; http, Reject, {data['reject_url']}"
}
requests.post(NTFY_TOPIC, data=message, headers=headers)
return {"status": "ok"}
if __name__ == '__main__':
app.run(port=5000)
```
Then configure Station to use your proxy:
```yaml theme={null}
notifications:
approval_webhook_url: http://localhost:5000/webhook
```
## Approval API
Once notified, approvers can use the URLs in the payload or call the API directly.
### Approve a Request
```bash theme={null}
curl -X POST http://localhost:8587/workflow-approvals/{approval_id}/approve \
-H "Content-Type: application/json" \
-d '{"comment": "Reviewed and approved"}'
```
**Response:**
```json theme={null}
{
"approval_id": "appr-abc123",
"status": "approved",
"decided_by": "api-user",
"decided_at": "2025-01-04T17:35:00Z"
}
```
### Reject a Request
```bash theme={null}
curl -X POST http://localhost:8587/workflow-approvals/{approval_id}/reject \
-H "Content-Type: application/json" \
-d '{"reason": "Missing security review"}'
```
### CLI Commands
```bash theme={null}
# List pending approvals
stn workflow approvals list --status pending
# Approve
stn workflow approvals approve appr-abc123 --comment "LGTM"
# Reject
stn workflow approvals reject appr-abc123 --reason "Needs review"
# Get details
stn workflow approvals get appr-abc123
```
## Audit Logging
All webhook deliveries and approval decisions are logged for compliance and debugging.
### Webhook Delivery Logs
Every webhook attempt is recorded with:
* Request payload sent
* Response status code
* Response body (truncated)
* Duration in milliseconds
* Error message (if failed)
### View Audit Trail
```bash theme={null}
curl http://localhost:8587/workflow-approvals/{approval_id}/audit
```
**Response:**
```json theme={null}
{
"logs": [
{
"event_type": "webhook.attempt",
"webhook_url": "https://ntfy.sh/station-approvals",
"created_at": "2025-01-04T17:30:00.100Z"
},
{
"event_type": "webhook.success",
"response_status": 200,
"duration_ms": 150,
"created_at": "2025-01-04T17:30:00.250Z"
},
{
"event_type": "approval.approved",
"metadata": {
"decided_by": "alice@example.com",
"comment": "Looks good"
},
"created_at": "2025-01-04T17:35:00Z"
}
]
}
```
### Audit Event Types
| Event Type | Description |
| ------------------- | ------------------------------------ |
| `webhook.attempt` | Webhook delivery started |
| `webhook.success` | Webhook delivered successfully (2xx) |
| `webhook.failure` | Webhook delivery failed |
| `approval.approved` | Approval was granted |
| `approval.rejected` | Approval was denied |
| `approval.timeout` | Approval expired without decision |
## Retry Behavior
Station automatically retries failed webhook deliveries:
* **Max retries:** 3 attempts
* **Backoff:** Exponential (1s, 4s, 9s)
* **Timeout:** Configurable per-request (default 10s)
All retry attempts are logged in the audit trail.
## Troubleshooting
1. Verify webhook URL is correct:
```bash theme={null}
curl -X POST "YOUR_WEBHOOK_URL" \
-H "Content-Type: application/json" \
-d '{"test": true}'
```
2. Check Station logs:
```bash theme={null}
STN_LOG_LEVEL=debug stn serve 2>&1 | grep -i webhook
```
3. Check audit logs:
```bash theme={null}
curl http://localhost:8587/workflow-approvals/{id}/audit
```
Check the audit log for the response body:
```sql theme={null}
SELECT event_type, response_status, error_message
FROM notification_logs
WHERE approval_id = 'appr-xxx'
ORDER BY created_at DESC;
```
1. Verify Station is accessible from where approvals happen
2. Check approval hasn't expired: `stn workflow approvals get appr-xxx`
3. Check approval wasn't already decided
1. Check workflow run status: `stn workflow runs get run-xyz --steps`
2. Check NATS is running: `stn status`
3. Check logs for errors
## Security Considerations
Always use HTTPS for webhook URLs in production to protect approval payloads.
### Recommendations
1. **Use HTTPS** - Encrypt webhook traffic
2. **Protect approval API** - Run Station on internal network or use authentication
3. **Audit retention** - Configure log retention for compliance
4. **Validate approvers** - Use the `approvers` field to restrict who can approve
## Comparison: Notifications vs Approval Webhooks
| Feature | Notify Tool | Approval Webhooks |
| -------- | ------------------------ | ----------------------------------- |
| Trigger | Agent calls `notify()` | Workflow hits `human_approval` step |
| Purpose | Alert users about events | Block workflow until human decision |
| Payload | Customizable message | Structured approval request |
| Response | Fire-and-forget | Approve/reject via API |
| Config | `notify:` section | `notifications:` section |
## Next Steps
* [Workflows](/station/workflows) - Create workflows with approval steps
* [Notifications](/station/notifications) - Agent-initiated notifications
* [Webhooks](/station/webhooks) - Trigger agents from external systems
# Authentication
Source: https://docs.cloudshipai.com/station/authentication
Configure AI providers and CloudShip authentication
# Authentication
Station supports multiple authentication methods for AI providers and CloudShip platform integration.
## AI Provider Authentication
**Anthropic OAuth Unavailable**: Anthropic has restricted third-party use of OAuth tokens. Claude Max/Pro subscription authentication (`stn auth anthropic login`) is **not working until further notice**. Please use API key authentication instead.
### API Keys (Recommended)
Set your API key as an environment variable:
```bash theme={null}
# OpenAI
export OPENAI_API_KEY="sk-..."
# Google Gemini
export GEMINI_API_KEY="..."
# Anthropic (pay-per-token billing)
export ANTHROPIC_API_KEY="sk-ant-api03-..."
```
### Authentication Priority
Station checks for credentials in this order:
| Priority | Method | Description |
| -------- | --------------------------- | ------------------------------------------------------------- |
| 1 | `STN_AI_AUTH_TYPE=api_key` | Force API key mode (override) |
| ~~2~~ | ~~Station OAuth tokens~~ | ~~`stn auth anthropic login`~~ **DEPRECATED** |
| ~~3~~ | ~~Claude Code credentials~~ | ~~`~/.claude/.credentials.json`~~ **DEPRECATED** |
| 4 | Environment variable | `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, etc. (**Recommended**) |
### Deployments
For all Station instances (local, Docker, K8s, Fly.io), use API keys:
```bash theme={null}
docker run \
-e OPENAI_API_KEY=$OPENAI_API_KEY \
-e STN_AI_PROVIDER=openai \
ghcr.io/cloudshipai/station:latest
```
***
## CloudShip Authentication
Connect your Station to [CloudShip](https://cloudshipai.com) for centralized management, team collaboration, and OAuth-protected MCP access.
### Login with API Key
```bash theme={null}
stn auth login
```
```
Using config file: /home/user/.config/station/config.yaml
🔭 OTEL telemetry enabled - provider=jaeger, endpoint=http://localhost:4318
Enter your CloudShip API key: ▌
```
Get your API key from your [CloudShip dashboard](https://app.cloudshipai.com/settings/api-keys).
### Using Registration Key
For automated deployments, use a registration key in your config:
```yaml theme={null}
# config.yaml
cloudship:
enabled: true
registration_key: "sk-reg-..."
name: "my-station"
tags: ["production", "us-east-1"]
```
```bash theme={null}
stn serve
# Output: Successfully registered with CloudShip management channel
```
### Check Connection Status
```bash theme={null}
stn auth status
```
```
CloudShip Connection:
✅ Connected to CloudShip
Organization: My Company
Station: production-us-east
Last sync: 2 minutes ago
AI Provider:
✅ Authenticated with OpenAI (API Key)
Model: gpt-5-mini
```
### Logout
```bash theme={null}
# Logout from CloudShip
stn auth logout
```
***
## OAuth for MCP Access
When CloudShip OAuth is enabled, MCP clients authenticate through CloudShip before accessing your Station's agents.
### Who Can Access?
Only users who:
1. Have a **CloudShip account**
2. Are **members of your organization**
3. Successfully **authenticate via OAuth**
### Enable OAuth
```yaml theme={null}
# config.yaml
cloudship:
enabled: true
registration_key: "your-key"
name: "my-station"
oauth:
enabled: true
client_id: "your-oauth-client-id" # From CloudShip OAuth Apps
```
### How It Works
```
MCP Client Station CloudShip
| | |
|------ POST /mcp --------->| |
|<----- 401 Unauthorized ---| |
| | |
|------- [Browser Login] -------------------------------->|
|<------ [Access Token] ----------------------------------|
| | |
|------ POST /mcp --------->| |
| Authorization: Bearer |------ Validate Token ------>|
| |<------ {active: true} ------|
|<----- MCP Response -------| |
```
### MCP Client Configuration
Point your MCP client to port 8587 (Dynamic Agent MCP):
```json theme={null}
{
"mcpServers": {
"my-station": {
"url": "https://my-station.example.com:8587/mcp"
}
}
}
```
When connecting, the client will:
1. Receive a 401 with OAuth discovery URL
2. Open CloudShip login in your browser
3. After authentication, automatically retry with the access token
***
## Security Notes
* **Registration keys** should be kept secret - they authorize Station connections
* **OAuth tokens** are validated on every MCP request via CloudShip introspection
* **PKCE** is required for all OAuth flows (S256 code challenge)
* Station caches validated tokens for 5 minutes to reduce introspection calls
## Next Steps
* [Quick Start](/station/quickstart) - Get Station running
* [CloudShip Integration](/station/cloudship) - Full CloudShip setup guide
* [MCP Tools](/station/mcp/tools) - Available MCP tools
# Bundles
Source: https://docs.cloudshipai.com/station/bundles
Package and distribute agent configurations
## What are Bundles?
Bundles are portable packages containing complete Station environment configurations:
* MCP server definitions
* Agent prompts
* Variable schemas
* Documentation
Bundles enable:
* **Sharing** configurations between teams
* **Deploying** pre-configured agents instantly
* **Version control** for agent configurations
## Bundle Structure
```
my-bundle.tar.gz/
├── manifest.json # Bundle metadata
├── template.json # MCP server configurations
├── variables.schema.json # Variable validation schema
├── README.md # Documentation
├── examples/
│ └── development.vars.yml
└── agents/
├── analyst.prompt
└── reviewer.prompt
```
## Creating Bundles
### Via MCP Tool
```
"Create a bundle from the production environment"
```
Station uses the `create_bundle_from_environment` tool to package your environment.
### Via CLI
```bash theme={null}
# Create bundle from default environment
stn bundle create default --output my-bundle.tar.gz
# Create from specific environment
stn bundle create production --output prod-bundle.tar.gz
```
### Bundle Contents
The created bundle includes:
* All MCP servers from `template.json`
* All agents from `agents/*.prompt`
* Variable schema from `variables.schema.json`
* Environment documentation
## Installing Bundles
### From CloudShip
```bash theme={null}
# Install by bundle UUID
stn bundle install e26b414a-f076-4135-927f-810bc1dc892a my-environment
```
### From URL
```bash theme={null}
# Install from GitHub release
stn bundle install https://github.com/org/repo/releases/download/v1.0/bundle.tar.gz my-env
```
### From Local File
```bash theme={null}
# Install from local file
stn bundle install ./my-bundle.tar.gz my-environment
```
### With `stn up`
Install bundle when starting Docker container:
```bash theme={null}
stn up --bundle e26b414a-f076-4135-927f-810bc1dc892a
```
## Sharing Bundles
### Upload to CloudShip
```bash theme={null}
# Share environment as bundle
stn bundle share production
# Share existing bundle file
stn bundle share ./my-bundle.tar.gz
```
After sharing, you'll receive a bundle UUID for distribution.
### Self-Hosted Distribution
Host bundles on any HTTP server:
```bash theme={null}
# Upload to your server
scp my-bundle.tar.gz user@server:/var/www/bundles/
# Install from URL
stn bundle install https://server/bundles/my-bundle.tar.gz my-env
```
## Bundle Manifest
The `manifest.json` describes the bundle:
```json theme={null}
{
"name": "security-scanner",
"version": "1.0.0",
"description": "Security scanning agents with vulnerability detection",
"author": "CloudShip AI",
"created": "2024-01-15T10:00:00Z",
"station_version": ">=0.1.0",
"variables": [
{
"name": "GITHUB_TOKEN",
"description": "GitHub API token for repository access",
"required": true
}
]
}
```
## Variable Handling
### Defining Variables
In `variables.schema.json`:
```json theme={null}
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"GITHUB_TOKEN": {
"type": "string",
"description": "GitHub API token"
},
"SLACK_WEBHOOK": {
"type": "string",
"description": "Slack webhook URL"
}
},
"required": ["GITHUB_TOKEN"]
}
```
### Providing Variables
When installing, Station prompts for required variables:
```bash theme={null}
stn bundle install ./bundle.tar.gz my-env
# Enter value for GITHUB_TOKEN: ghp_xxxxx
# Enter value for SLACK_WEBHOOK (optional): https://hooks.slack.com/...
```
Or provide via file:
```bash theme={null}
stn bundle install ./bundle.tar.gz my-env --vars ./my-vars.yml
```
## Demo Bundles
Station includes demo bundles for testing:
```bash theme={null}
# List available demos
stn mock list
# Run a demo MCP server
stn mock cloudquery
stn mock aws-cost-explorer
```
## Best Practices
Use semantic versioning in manifest:
```json theme={null}
{
"version": "1.2.3"
}
```
Always include descriptions for required variables:
```json theme={null}
{
"GITHUB_TOKEN": {
"description": "GitHub API token with repo and read:org scopes"
}
}
```
Add example variable files:
```yaml theme={null}
# examples/development.vars.yml
GITHUB_TOKEN: ghp_your_dev_token
SLACK_WEBHOOK: "" # Optional in dev
```
Install your bundle in a fresh environment before sharing:
```bash theme={null}
rm -rf ~/.config/station/environments/test
stn bundle install ./my-bundle.tar.gz test
stn sync test
```
# Claude Code Plugin
Source: https://docs.cloudshipai.com/station/claude-code
Use Station with Claude Code via the official plugin and MCP integration
Station provides two [Claude Code plugins](https://github.com/cloudshipai/station/tree/main/claude-code-plugin) that give Claude Code access to 55+ MCP tools for agent orchestration. Choose the integration style that fits your workflow.
## Choose Your Plugin
Station offers two plugin options:
| Plugin | Best For | What's Included |
| ------------------- | ------------------------------------------ | ------------------------------------ |
| **`station`** | Users who want lightweight guidance | Skills + Slash Commands + MCP Server |
| **`station-agent`** | Power users who want autonomous operations | Pre-configured Subagent + MCP Server |
**Lightweight integration** - Claude learns Station via skills that inject knowledge into your conversation.
* **Skills**: `station`, `station-agents`, `station-mcp`, `station-deploy`, `station-benchmark`, `station-workflows`
* **Slash Commands**: `/station`, `/station-agent`, `/station-workflow`, `/station-bundle`
* **MCP Server**: 55+ tools for agent management, execution, and workflows
Best when you want direct control over Station operations in your main conversation.
**Full integration** - A dedicated Station expert subagent that Claude can delegate to.
* **Subagent**: `station-operator` - autonomous Station operations
* **MCP Server**: 55+ tools pre-configured for the subagent
* **Tracing**: Reminds you to start Jaeger for observability
Best when you want Claude to handle Station tasks autonomously with cleaner context separation.
## Quick Start
### Option 1: Install from Marketplace (Recommended)
```bash theme={null}
# Add the Station marketplace
/plugin marketplace add cloudshipai/station
# Choose ONE of these plugins:
/plugin install station@cloudshipai-station # Skills-based (lightweight)
/plugin install station-agent@cloudshipai-station # Subagent-based (full integration)
```
### Option 2: Direct GitHub Install
```bash theme={null}
# Skills-based plugin
/plugin install cloudshipai/station/claude-code-plugin
# Subagent-based plugin
/plugin install cloudshipai/station/claude-code-plugin-agent
```
### Option 3: Local Installation
If you've cloned the Station repository locally:
```bash theme={null}
# Skills-based plugin
/plugin install ./station/claude-code-plugin
# Subagent-based plugin
/plugin install ./station/claude-code-plugin-agent
```
### Option 4: Manual MCP Configuration
Add Station directly to your `.mcp.json` (MCP tools only, no skills or subagent):
```json theme={null}
{
"mcpServers": {
"station": {
"command": "stn",
"args": ["stdio"],
"env": {
"OTEL_EXPORTER_OTLP_ENDPOINT": "http://localhost:4318"
}
}
}
}
```
The `OTEL_EXPORTER_OTLP_ENDPOINT` enables distributed tracing. Start Jaeger with `stn jaeger up` to view traces at [http://localhost:16686](http://localhost:16686).
## Prerequisites
Before using the plugin:
1. **Station CLI installed**: See [Installation](/station/installation)
2. **Station initialized**: Run `stn init` to set up your workspace
3. **At least one agent**: Create an agent or install a bundle
```bash theme={null}
# Verify installation
stn --version
# Initialize Station
stn init
# Create a simple agent
stn agent create --name "Hello Agent" --model gpt-4o-mini
```
## Skills
Skills are comprehensive guides that teach Claude Code how to use Station. Load them with `/skill `:
### Available Skills
| Skill | Command | Description |
| ------------------ | ----------------------- | ------------------------------------------------------ |
| **station** | `/skill station` | Core CLI reference - commands, agent format, workflows |
| **station-config** | `/skill station-config` | Configuration deep-dive - all config options explained |
### Using Skills
```
# Load the core Station skill before working with agents
/skill station
# Now ask questions or give commands
Create an agent that monitors Kubernetes pods and alerts on failures
```
Skills provide Claude with:
* Complete command reference with examples
* Agent format (Dotprompt) specification
* Workflow state machine patterns
* MCP tool usage patterns
* Best practices and common patterns
Load `/skill station` at the start of a session when doing significant Station work. It gives Claude comprehensive context to help you more effectively.
Skills are only available in the `station` plugin. The `station-agent` plugin uses a dedicated subagent instead.
### Skill Contents
The core Station skill covers:
* Agent lifecycle (create, run, list, update, delete)
* Dotprompt format with YAML frontmatter
* MCP server tools and configuration
* Workflow state machines
* Environment management
* Bundle creation and installation
The configuration skill covers:
* Global config (`~/.config/station/config.yaml`)
* AI provider setup (OpenAI, Anthropic, etc.)
* Coding backend configuration
* CloudShip platform integration
* Environment variables
* OAuth authentication
## Station Operator Subagent
The `station-operator` subagent is only available in the `station-agent` plugin.
When you install the `station-agent` plugin, you get a dedicated **Station Operator** subagent that Claude can delegate to for autonomous Station operations.
### Capabilities
The `station-operator` subagent can:
| Capability | Description |
| -------------------------- | ------------------------------------------------------------------ |
| **Create & Manage Agents** | Uses `create_agent`, `update_agent`, `delete_agent`, `list_agents` |
| **Execute Agents** | Uses `call_agent`, `list_runs`, `inspect_run` |
| **Configure MCP Servers** | Uses `add_mcp_server_to_environment`, `discover_tools` |
| **Handle Workflows** | Uses `execute_workflow`, `list_approvals`, `approve_step` |
| **Debug Runs** | Analyzes execution history, tool calls, and costs |
### How It Works
Claude automatically delegates Station tasks to the subagent when appropriate:
```
User: Create a Station agent that monitors Kubernetes pods
Claude: [Invokes station-operator subagent]
[Subagent creates agent using create_agent tool]
[Subagent returns result with agent details]
Claude: I've created your Kubernetes pod monitor agent...
```
You can also invoke it explicitly:
```
Use the station-operator subagent to debug my last failed agent run
```
### Tracing Setup
The subagent reminds you to set up Jaeger for observability on first interaction:
```bash theme={null}
# Start Jaeger for distributed tracing
stn jaeger up
# View traces at http://localhost:16686
```
### Skills vs Subagent: When to Use Each
| Scenario | Recommended |
| ------------------------------ | --------------------------------- |
| Learning Station commands | `station` plugin (skills) |
| Step-by-step guidance | `station` plugin (skills) |
| Quick autonomous tasks | `station-agent` plugin (subagent) |
| Complex multi-step operations | `station-agent` plugin (subagent) |
| Keeping main context clean | `station-agent` plugin (subagent) |
| Direct control over operations | `station` plugin (skills) |
## Available Slash Commands
The plugin provides four slash commands that teach Claude Code how to work with Station:
| Command | Purpose |
| ------------------- | ---------------------------------------------- |
| `/station` | Core Station concepts and MCP tools overview |
| `/station-agent` | Create and manage AI agents |
| `/station-workflow` | Build multi-step workflows with state machines |
| `/station-bundle` | Package and distribute agent bundles |
### Using Commands
```
# Get Station overview
/station
# Create an agent
/station-agent
# Build a workflow
/station-workflow
# Package agents
/station-bundle
```
## MCP Tools
After installation, Claude Code has access to Station's MCP tools:
### Agent Management
| Tool | Description |
| ---------------------- | ---------------------------------------- |
| `station_create_agent` | Create a new agent with prompt and model |
| `station_list_agents` | List all agents in an environment |
| `station_call_agent` | Execute an agent with a task |
| `station_update_agent` | Modify agent configuration |
| `station_delete_agent` | Remove an agent |
### Execution & Monitoring
| Tool | Description |
| ---------------------- | ---------------------------- |
| `station_list_runs` | View execution history |
| `station_inspect_run` | Get detailed run information |
| `station_get_run_logs` | Retrieve execution logs |
### Environment & Configuration
| Tool | Description |
| ---------------------------- | --------------------------- |
| `station_list_environments` | List available environments |
| `station_create_environment` | Create a new environment |
| `station_get_config` | View Station configuration |
### Workflows
| Tool | Description |
| ------------------------- | ------------------------------- |
| `station_create_workflow` | Create a state machine workflow |
| `station_run_workflow` | Execute a workflow |
| `station_list_workflows` | List available workflows |
Use `/station` to see the full list of 55+ available MCP tools.
## Usage Examples
### Creating an Agent
Ask Claude Code directly:
```
Create a Station agent that monitors Kubernetes pod health
and alerts on failures. Use gpt-4o-mini model.
```
Claude will use `station_create_agent` with the appropriate configuration.
### Running an Agent
```
Run my "Pod Monitor" agent with the task "Check all pods in production namespace"
```
### Building Multi-Agent Teams
```
Create an incident response team with:
1. An "Incident Coordinator" that delegates to specialists
2. A "Kubernetes Expert" for K8s troubleshooting
3. A "Log Analyzer" for log pattern analysis
Set up the coordinator to call the specialists as tools.
```
### Creating Workflows
```
Create a workflow that:
1. Triages incoming alerts by severity
2. Investigates high-severity issues automatically
3. Requires human approval before remediation
4. Documents the resolution
```
## Agent Format (Dotprompt)
Station agents use the [Dotprompt format](https://firebase.google.com/docs/genkit/dotprompt) - YAML frontmatter with Handlebars templates:
```yaml theme={null}
---
metadata:
name: "My Agent"
description: "What this agent does"
model: gpt-4o-mini
max_steps: 8
tools:
- "__tool_name"
---
{{role "system"}}
You are an expert assistant that...
{{role "user"}}
{{userInput}}
```
The `{{userInput}}` variable is populated with the task when running the agent. Always include it in your prompt.
## MCP Configuration Options
### Basic stdio Mode
```json theme={null}
{
"mcpServers": {
"station": {
"command": "stn",
"args": ["stdio"]
}
}
}
```
### With Custom Config
```json theme={null}
{
"mcpServers": {
"station": {
"command": "stn",
"args": ["--config", "/path/to/config.yaml", "stdio"]
}
}
}
```
### HTTP Mode (Remote Station)
Connect to a running Station server:
```json theme={null}
{
"mcpServers": {
"station": {
"type": "http",
"url": "http://localhost:8586/mcp"
}
}
}
```
### Multiple Environments
```json theme={null}
{
"mcpServers": {
"station-dev": {
"command": "stn",
"args": ["--config", "~/.station/dev.yaml", "stdio"]
},
"station-prod": {
"command": "stn",
"args": ["--config", "~/.station/prod.yaml", "stdio"]
}
}
}
```
### With Telemetry
```json theme={null}
{
"mcpServers": {
"station": {
"command": "stn",
"args": ["stdio"],
"env": {
"OTEL_EXPORTER_OTLP_ENDPOINT": "http://localhost:4318"
}
}
}
}
```
## Troubleshooting
### Plugin Not Working
1. Verify Station is installed:
```bash theme={null}
stn --version
```
2. Test MCP manually:
```bash theme={null}
echo '{"jsonrpc":"2.0","method":"tools/list","id":1}' | stn stdio
```
3. Reinstall the plugin:
```bash theme={null}
/plugin uninstall station
/plugin install cloudshipai/station
```
### MCP Tools Not Available
1. Check `.mcp.json` exists in your project root
2. Restart Claude Code after configuration changes
3. Ask Claude: "List available Station MCP tools"
### Agent Creation Failing
1. Check environment exists:
```bash theme={null}
stn env list
```
2. Verify AI provider is configured:
```bash theme={null}
stn provider status
```
3. Check MCP tools are available:
```bash theme={null}
stn mcp tools
```
## Best Practices
### 1. Choose the Right Plugin
| If you want... | Use |
| ----------------------------------------- | --------------------------- |
| Lightweight guidance in your conversation | `station` plugin |
| Autonomous Station operations | `station-agent` plugin |
| Both (learning + automation) | Install both, use as needed |
### 2. Enable Tracing
Always start Jaeger for observability when debugging:
```bash theme={null}
stn jaeger up
# View traces at http://localhost:16686
```
### 3. Use MCP Over CLI
Prefer MCP tools for structured responses:
```
# Good - Claude uses MCP tool with structured response
"Create an agent called 'Cost Analyzer' that..."
# Avoid - asking Claude to run CLI commands
"Run: stn agent create --name 'Cost Analyzer'..."
```
### 4. Use Slash Commands for Context (Skills Plugin)
Start complex tasks with the relevant slash command:
```
/station-workflow
Now create a workflow that handles deployment approvals...
```
### 5. Organize by Environment
Use separate MCP entries for different environments to avoid mistakes:
```json theme={null}
{
"mcpServers": {
"station-dev": { "command": "stn", "args": ["--config", "~/.station/dev.yaml", "stdio"] },
"station-prod": { "command": "stn", "args": ["--config", "~/.station/prod.yaml", "stdio"] }
}
}
```
## Next Steps
Create custom AI agents
Full MCP tools reference
Multi-step orchestration
Package and distribute agents
# CloudShip Integration
Source: https://docs.cloudshipai.com/station/cloudship
Connect Station to CloudShip for centralized management and team collaboration
# CloudShip Integration
Connect your Station to [CloudShip](https://cloudshipai.com) for centralized management, OAuth authentication, and team collaboration.
## Why CloudShip?
| Feature | Standalone Station | With CloudShip |
| -------------- | ------------------ | ------------------------ |
| Management | Local only | Centralized dashboard |
| Authentication | Manual API keys | OAuth for team members |
| Collaboration | Single user | Organization-wide access |
| Audit Trail | Local logs | Centralized tracking |
## Quick Setup
### 1. Get a Registration Key
From your [CloudShip dashboard](https://app.cloudshipai.com):
1. Go to **Settings > Stations**
2. Click **Create Registration Key**
3. Copy the key
### 2. Configure Station
Add to your `config.yaml`:
```yaml theme={null}
cloudship:
enabled: true
registration_key: "sk-reg-..."
name: "my-station"
tags: ["production", "us-east-1"]
```
### 3. Start Station
```bash theme={null}
stn serve
# Output: Successfully registered with CloudShip management channel
```
Your Station is now connected and visible in your CloudShip dashboard.
## Authentication Methods
### Interactive Login
```bash theme={null}
stn auth login
```
```
Using config file: /home/user/.config/station/config.yaml
Enter your CloudShip API key: ▌
```
Get your API key from [CloudShip Settings > API Keys](https://app.cloudshipai.com/settings/api-keys).
### Registration Key (Automated)
For automated deployments, use a registration key in config:
```yaml theme={null}
cloudship:
enabled: true
registration_key: "sk-reg-..."
```
### Check Status
```bash theme={null}
stn auth status
```
```
CloudShip Connection:
✅ Connected to CloudShip
Organization: My Company
Station: production-us-east
Last sync: 2 minutes ago
```
## OAuth for MCP Access
When CloudShip OAuth is enabled, MCP clients authenticate through CloudShip before accessing your Station's agents.
### Who Can Access?
Only users who:
1. Have a **CloudShip account**
2. Are **members of your organization**
3. Successfully **authenticate via OAuth**
### Enable OAuth
1. **Create an OAuth App** in CloudShip (Settings > OAuth Apps)
2. **Configure Station**:
```yaml theme={null}
cloudship:
enabled: true
registration_key: "your-key"
name: "my-station"
oauth:
enabled: true
client_id: "your-oauth-client-id"
```
3. **Invite team members** to your CloudShip organization
### How OAuth Works
```
MCP Client Station CloudShip
| | |
|------ POST /mcp --------->| |
|<----- 401 Unauthorized ---| |
| WWW-Authenticate: | |
| Bearer resource_metadata="..." |
| | |
|------- [OAuth Discovery] ------------------------------>|
|<------ [Authorization Server Metadata] -----------------|
| | |
|------- [Browser Login] -------------------------------->|
|<------ [Authorization Code] ----------------------------|
| | |
|------- [Token Exchange] ------------------------------->|
|<------ [Access Token] ----------------------------------|
| | |
|------ POST /mcp --------->| |
| Authorization: Bearer |------ Validate Token ------>|
| |<------ {active: true} ------|
|<----- MCP Response -------| |
```
**Flow steps:**
1. MCP client sends request to Station
2. Station returns 401 with `WWW-Authenticate` header containing OAuth metadata URL
3. Client discovers CloudShip's authorization server endpoints
4. User logs in via browser, authorizes access
5. Client exchanges authorization code for access token
6. Client retries request with Bearer token
7. Station validates token with CloudShip, returns MCP response
### MCP Client Configuration
Point your MCP client to port 8587 (Dynamic Agent MCP):
```json theme={null}
{
"mcpServers": {
"my-station": {
"url": "https://my-station.example.com:8587/mcp"
}
}
}
```
When connecting:
1. Client receives 401 with OAuth discovery URL
2. Browser opens for CloudShip login
3. After authentication, client automatically retries with token
## Configuration Reference
```yaml theme={null}
cloudship:
# Enable CloudShip integration
enabled: true
# Registration key from CloudShip dashboard
registration_key: "sk-reg-..."
# Unique station name (required for multi-station support)
name: "production-us-east"
# Tags for filtering and organization
tags: ["production", "us-east-1", "sre-team"]
# CloudShip endpoints (defaults shown - usually no need to change)
endpoint: "lighthouse.cloudshipai.com:443"
use_tls: true
base_url: "https://app.cloudshipai.com"
# OAuth settings for MCP authentication
oauth:
enabled: false
client_id: ""
# Auto-configured from base_url:
# auth_url: "https://app.cloudshipai.com/oauth/authorize/"
# token_url: "https://app.cloudshipai.com/oauth/token/"
# introspect_url: "https://app.cloudshipai.com/oauth/introspect/"
```
## Development Setup
### Local Development (No CloudShip)
```yaml theme={null}
# config.yaml - no cloudship section needed
ai_provider: anthropic
ai_model: claude-sonnet-4-20250514
```
### Local Lighthouse (Testing)
For testing CloudShip integration locally:
```yaml theme={null}
cloudship:
enabled: true
registration_key: "your-dev-key"
name: "dev-station"
endpoint: "localhost:50051"
use_tls: false
base_url: "http://localhost:8000"
oauth:
enabled: true
client_id: "your-dev-client-id"
introspect_url: "http://localhost:8000/oauth/introspect/"
```
### Production CloudShip (Recommended)
```yaml theme={null}
cloudship:
enabled: true
registration_key: "your-registration-key"
name: "dev-station"
# Uses defaults: endpoint=lighthouse.cloudshipai.com:443, use_tls=true
```
## Multi-Station Management
### Naming Stations
Each Station needs a unique name within your organization:
```yaml theme={null}
# Station 1: Production US
cloudship:
name: "prod-us-east"
tags: ["production", "us-east-1"]
# Station 2: Production EU
cloudship:
name: "prod-eu-west"
tags: ["production", "eu-west-1"]
# Station 3: Development
cloudship:
name: "dev-local"
tags: ["development", "local"]
```
### Filtering by Tags
In CloudShip dashboard, filter Stations by tags to manage specific environments.
## Security
### Registration Keys
* Keep registration keys secret
* Rotate keys periodically
* Use different keys for different environments
### OAuth Tokens
* Validated on every MCP request
* PKCE required (S256 code challenge)
* Cached for 5 minutes to reduce introspection calls
### Audit Trail
CloudShip logs all:
* Station connections/disconnections
* Agent executions triggered via MCP
* OAuth authentications
* Configuration changes
## Troubleshooting
### Connection Failed
```
Error: failed to connect to CloudShip
```
**Check:**
1. Registration key is valid
2. Network allows outbound to `lighthouse.cloudshipai.com:443`
3. TLS is properly configured
### OAuth 401 Errors
```
Error: 401 Unauthorized
```
**Check:**
1. OAuth is enabled in config
2. Client ID is correct
3. User is member of organization
### Token Expired
Tokens auto-refresh. If issues persist:
```bash theme={null}
stn auth logout
stn auth login
```
## Next Steps
* [Authentication](/station/authentication) - All auth options
* [Deployment](/station/deployment/production) - Production setup
* [Observability](/station/observability) - Centralized tracing
# CLI Commands
Source: https://docs.cloudshipai.com/station/commands
Complete reference for Station CLI commands
## Command Overview
Station CLI (`stn`) provides commands for managing agents, MCP servers, and deployments.
```bash theme={null}
stn [command] [subcommand] [flags]
```
## Core Commands
### `stn init`
Initialize Station configuration.
```bash theme={null}
stn init [flags]
```
| Flag | Description |
| ----------------- | ------------------------------------ |
| `--provider` | AI provider (openai, gemini, custom) |
| `--model` | AI model name |
| `--api-key` | API key for provider |
| `--base-url` | Custom API endpoint |
| `--yes`, `-y` | Use defaults without prompts |
| `--ship` | Enable Ship CLI integration |
| `--cloudship-key` | CloudShip registration key |
### `stn serve`
Start the Station server.
```bash theme={null}
stn serve [flags]
```
| Flag | Description |
| -------------------- | ------------------------------- |
| `--api-port` | API server port (default: 8585) |
| `--mcp-port` | MCP server port (default: 8586) |
| `--ssh-port` | SSH server port (default: 2222) |
| `--database` | Database file path |
| `--local` | Force local mode |
| `--enable-telemetry` | Enable OpenTelemetry |
### `stn up`
Start Station in a Docker container.
```bash theme={null}
stn up [flags]
```
| Flag | Description |
| ------------------- | -------------------------------- |
| `--workspace`, `-w` | Workspace directory to mount |
| `--provider` | AI provider for initialization |
| `--bundle` | CloudShip bundle ID to install |
| `--upgrade` | Rebuild container image |
| `--env`, `-e` | Additional environment variables |
| `--develop` | Enable Genkit Developer UI |
### `stn down`
Stop the Station container.
```bash theme={null}
stn down [flags]
```
| Flag | Description |
| ----------------- | --------------------- |
| `--remove-volume` | Delete all data |
| `--remove-image` | Remove Docker image |
| `--clean-mcp` | Remove from .mcp.json |
## Agent Commands
### `stn agent create`
Create a new agent.
```bash theme={null}
stn agent create --name "my-agent" --description "My agent description"
```
| Flag | Description |
| --------------- | --------------------- |
| `--name` | Agent name (required) |
| `--description` | Agent description |
| `--env` | Environment name |
| `--model` | AI model override |
### `stn agent run`
Execute an agent.
```bash theme={null}
stn agent run ""
```
| Flag | Description |
| ------------- | -------------------- |
| `--env` | Environment name |
| `--variables` | JSON input variables |
| `--stream` | Stream output |
### `stn agent list`
List all agents.
```bash theme={null}
stn agent list [--env ]
```
## MCP Commands
### `stn mcp list`
List MCP configurations.
```bash theme={null}
stn mcp list [--env ]
```
### `stn mcp tools`
List available MCP tools.
```bash theme={null}
stn mcp tools [--filter ]
```
### `stn mcp status`
Show MCP configuration status.
```bash theme={null}
stn mcp status [environment]
```
### `stn sync`
Sync file-based configurations.
```bash theme={null}
stn sync [environment]
```
| Flag | Description |
| ----------- | -------------------- |
| `--dry-run` | Preview changes |
| `--verbose` | Show detailed output |
## Bundle Commands
### `stn bundle create`
Create a bundle from an environment.
```bash theme={null}
stn bundle create [--output ]
```
### `stn bundle install`
Install a bundle.
```bash theme={null}
stn bundle install [--force]
```
Sources can be:
* CloudShip bundle UUID
* URL to bundle file
* Local file path
### `stn bundle share`
Upload a bundle to CloudShip.
```bash theme={null}
stn bundle share
```
## Utility Commands
### `stn status`
Show Station server status.
```bash theme={null}
stn status
```
### `stn logs`
Show container logs.
```bash theme={null}
stn logs [--follow]
```
### `stn jaeger`
Manage Jaeger telemetry.
```bash theme={null}
stn jaeger up # Start Jaeger
stn jaeger down # Stop Jaeger
stn jaeger status # Check status
stn jaeger clean # Remove data
```
### `stn config`
Manage configuration.
```bash theme={null}
stn config show # Show all config
stn config get # Get a value
stn config set # Set a value
```
## Global Flags
These flags work with any command:
| Flag | Description |
| -------------------- | -------------------- |
| `--config` | Config file path |
| `--enable-telemetry` | Enable OpenTelemetry |
| `--otel-endpoint` | OTLP endpoint URL |
| `-h`, `--help` | Show help |
| `-v`, `--version` | Show version |
## Examples
```bash theme={null}
export OPENAI_API_KEY="sk-..."
stn init --provider openai --yes
stn serve
```
```bash theme={null}
stn up --bundle e26b414a-f076-4135-927f-810bc1dc892a --provider openai
```
```bash theme={null}
stn agent run code-reviewer --variables '{"code": "print(1)", "language": "python"}'
```
```bash theme={null}
stn jaeger up
stn serve --enable-telemetry --otel-endpoint http://localhost:4318
# View traces at http://localhost:16686
```
# Configuration
Source: https://docs.cloudshipai.com/station/configuration
Configure Station for your needs
## Configuration Files
Station uses a hierarchical configuration system:
| File | Purpose |
| ------------------------------------ | ------------------------------ |
| `~/.config/station/config.yaml` | Global settings |
| `environments/{env}/template.json` | MCP server configurations |
| `environments/{env}/variables.yml` | Environment-specific variables |
| `environments/{env}/agents/*.prompt` | Agent definitions |
## Global Configuration
The main `config.yaml` file controls Station's behavior:
```yaml theme={null}
# AI Provider Configuration
ai_provider: openai # openai, anthropic, gemini, custom
ai_model: gpt-4o # default model for agents
ai_api_key: "" # or use STN_AI_API_KEY env var
ai_base_url: "" # for custom providers
# Anthropic OAuth (for Claude Max/Pro subscribers)
ai_auth_type: oauth # oauth or api_key
ai_oauth_token: "" # set via `stn auth anthropic login`
ai_oauth_refresh_token: "" # auto-managed
ai_oauth_expires_at: 0 # auto-managed
# Server Configuration
api_port: 8585 # REST API and Web UI
mcp_port: 8586 # MCP Server for AI editors
ssh_port: 2222 # SSH Admin Interface
admin_username: admin # SSH username
# Database
database_url: /home/user/.config/station/station.db
# Operating Mode
local_mode: true # true for standalone, false for CloudShip
debug: false # enable debug logging
# Telemetry
telemetry_enabled: false
otel_endpoint: http://localhost:4318
# CloudShip Integration
cloudship:
enabled: false
registration_key: ""
endpoint: lighthouse.cloudship.ai:443
```
## Environment Variables
All settings can be overridden via environment variables:
| Variable | Config Key | Description |
| ----------------------------- | --------------- | -------------------- |
| `STN_AI_PROVIDER` | `ai_provider` | AI provider name |
| `STN_AI_MODEL` | `ai_model` | Default model |
| `STN_AI_API_KEY` | `ai_api_key` | API key |
| `STN_AI_BASE_URL` | `ai_base_url` | Custom API endpoint |
| `STN_API_PORT` | `api_port` | API server port |
| `STN_MCP_PORT` | `mcp_port` | MCP server port |
| `STN_SSH_PORT` | `ssh_port` | SSH server port |
| `STATION_LOCAL_MODE` | `local_mode` | Local/CloudShip mode |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | `otel_endpoint` | Telemetry endpoint |
Environment variables take precedence over config file values.
## AI Provider Authentication
Station supports multiple AI providers with different authentication methods.
### OpenAI / Gemini (API Key)
```yaml theme={null}
ai_provider: openai
ai_model: gpt-4o
ai_api_key: sk-... # or set STN_AI_API_KEY
```
### Anthropic (API Key)
```yaml theme={null}
ai_provider: anthropic
ai_model: claude-sonnet-4-20250514
ai_api_key: sk-ant-api03-...
```
### Anthropic OAuth (Claude Max/Pro)
Claude Max and Pro subscribers can use OAuth instead of an API key. This uses your existing subscription—no separate API billing.
```bash theme={null}
# Login via browser
stn auth anthropic login
# Check token status
stn auth anthropic status
# Output: Token expires: 2025-12-30T16:59:42-06:00 (5h remaining)
# Logout
stn auth anthropic logout
```
After login, your config is automatically updated:
```yaml theme={null}
ai_provider: anthropic
ai_model: claude-sonnet-4-20250514
ai_auth_type: oauth
ai_oauth_token: sk-ant-oat01-... # auto-set
ai_oauth_refresh_token: sk-ant-ort01-... # auto-set
ai_oauth_expires_at: 1767135582033 # auto-set
```
OAuth tokens expire after \~4 hours but are automatically refreshed before expiry. The refresh token is stored securely in your config.
**Supported Claude Models:**
* `claude-opus-4-5-20251101` (Claude 4.5 Opus)
* `claude-sonnet-4-20250514` (Claude 4 Sonnet)
* `claude-sonnet-4-5-20250929` (Claude 4.5 Sonnet)
* `claude-haiku-4-5-20251001` (Claude 4.5 Haiku)
* `claude-3-5-sonnet-20241022` (Claude 3.5 Sonnet)
* `claude-3-5-haiku-20241022` (Claude 3.5 Haiku)
* `claude-3-opus-20240229` (Claude 3 Opus)
## MCP Server Configuration
Configure MCP servers in `template.json`:
```json theme={null}
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/workspace"],
"env": {}
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "{{GITHUB_TOKEN}}"
}
}
}
}
```
### Template Variables
Use `{{VARIABLE_NAME}}` syntax for dynamic values. Define them in `variables.yml`:
```yaml theme={null}
GITHUB_TOKEN: ghp_your_token_here
DATABASE_URL: postgresql://localhost/mydb
```
Or set them as environment variables - Station will prompt for missing values during `stn sync`.
## Agent Configuration
Define agents in `.prompt` files using dotprompt format:
````yaml theme={null}
---
name: code-reviewer
description: Reviews code for best practices and security issues
model: openai/gpt-4o
tools:
- filesystem_read
- github_pr_comments
config:
temperature: 0.7
maxOutputTokens: 4096
input:
schema:
type: object
properties:
code:
type: string
description: The code to review
language:
type: string
description: Programming language
output:
schema:
type: object
properties:
issues:
type: array
items:
type: object
properties:
severity: { type: string }
message: { type: string }
line: { type: number }
---
You are an expert code reviewer. Analyze the provided {{language}} code and identify:
1. Security vulnerabilities
2. Performance issues
3. Best practice violations
4. Code style improvements
Code to review:
```{{language}}
{{code}}
````
Provide detailed feedback with line numbers where applicable.
````
## Port Configuration
Default ports and their purposes:
| Port | Service | Description |
|------|---------|-------------|
| 8585 | API/UI | REST API and Web management UI |
| 8586 | MCP | Model Context Protocol server |
| 8587 | Agent MCP | Dynamic Agent MCP (OAuth protected) |
| 2222 | SSH | SSH Admin Interface |
To change ports:
```yaml
# config.yaml
api_port: 9000
mcp_port: 9001
ssh_port: 2223
````
Or via environment:
```bash theme={null}
STN_API_PORT=9000 STN_MCP_PORT=9001 stn serve
```
## Telemetry Configuration
Enable OpenTelemetry for distributed tracing:
```yaml theme={null}
# config.yaml
telemetry_enabled: true
otel_endpoint: http://localhost:4318
```
Or start Jaeger and enable on the fly:
```bash theme={null}
# Start Jaeger
stn jaeger up
# Start Station with telemetry
stn serve --enable-telemetry
```
## Workflow and Embedded NATS
Station includes an **embedded NATS server** for workflow orchestration and OpenCode communication. This eliminates the need for a separate NATS installation in most deployments.
### How Embedded NATS Works
When you start Station with workflows enabled (`stn serve`), it automatically:
1. Starts an embedded NATS server on port 4222
2. Configures workflow engine to use it
3. Allows OpenCode containers to connect via `host.docker.internal:4222`
```
┌─────────────────────────────────────────────────────────────┐
│ Station Process │
│ │
│ ┌─────────────────┐ ┌─────────────────────────────┐ │
│ │ Workflow Engine │─────▶│ Embedded NATS (port 4222) │ │
│ └─────────────────┘ └─────────────────────────────┘ │
│ │ │
└────────────────────────────────────│────────────────────────┘
│
▼
┌─────────────────────┐
│ OpenCode Container │
│ NATS_URL=nats:// │
│ host.docker.internal│
│ :4222 │
└─────────────────────┘
```
### Environment Variables
| Variable | Default | Description |
| ------------------------ | ----------------------- | ----------------------------------------------------------------- |
| `WORKFLOW_NATS_URL` | `nats://localhost:4222` | NATS server URL. If set to non-default, embedded NATS is disabled |
| `WORKFLOW_NATS_PORT` | `4222` | Port for embedded NATS server |
| `WORKFLOW_NATS_EMBEDDED` | Auto-detected | Force embedded NATS on (`true`) or off (`false`) |
### Auto-Detection Logic
Station automatically determines whether to use embedded NATS:
| Condition | Result |
| ------------------------------------------------------ | -------------------------------------------- |
| `WORKFLOW_NATS_URL` not set or `nats://localhost:4222` | **Embedded NATS enabled** |
| `WORKFLOW_NATS_URL` set to external server | **Embedded NATS disabled** |
| `WORKFLOW_NATS_EMBEDDED=true` | **Force embedded** (overrides URL detection) |
| `WORKFLOW_NATS_EMBEDDED=false` | **Force external** (must set URL) |
### Configuration Examples
No configuration needed—embedded NATS starts automatically:
```bash theme={null}
# Just start Station
stn serve
# OpenCode container connects to:
# NATS_URL=nats://host.docker.internal:4222
```
Change the embedded NATS port:
```bash theme={null}
WORKFLOW_NATS_PORT=4223 stn serve
# OpenCode container connects to:
# NATS_URL=nats://host.docker.internal:4223
```
Use an existing NATS server:
```bash theme={null}
WORKFLOW_NATS_URL=nats://nats.example.com:4222 stn serve
# Embedded NATS is automatically disabled
# OpenCode container should connect to same external server
```
Override auto-detection:
```bash theme={null}
# Force embedded even with custom URL
WORKFLOW_NATS_URL=nats://localhost:4222 \
WORKFLOW_NATS_EMBEDDED=true \
stn serve
# Force external (must provide URL)
WORKFLOW_NATS_EMBEDDED=false \
WORKFLOW_NATS_URL=nats://external:4222 \
stn serve
```
### Docker Compose with Embedded NATS
When running Station on the host and OpenCode in a container:
```yaml theme={null}
version: '3.8'
services:
opencode:
image: ghcr.io/sst/opencode:latest
environment:
- NATS_URL=nats://host.docker.internal:4222
extra_hosts:
- "host.docker.internal:host-gateway" # Required for Linux
volumes:
- ./workspaces:/workspaces
```
The `extra_hosts` configuration is only needed on Linux. macOS and Windows Docker Desktop include `host.docker.internal` automatically.
### Verifying NATS Connectivity
```bash theme={null}
# Check if embedded NATS is running
netstat -tlnp | grep 4222
# From OpenCode container, test connection
docker exec opencode-container nats-ping nats://host.docker.internal:4222
# View NATS logs (if using external)
nats server ping
```
## CloudShip Integration
To connect to CloudShip platform:
```yaml theme={null}
# config.yaml
local_mode: false
cloudship:
enabled: true
registration_key: "your-key-from-cloudship-ui"
endpoint: lighthouse.cloudship.ai:443
```
Get your registration key from [CloudShip Dashboard](https://app.cloudshipai.com/stations).
## Notify Tool
Enable agent notifications via webhooks (ntfy, Slack, etc.):
```yaml theme={null}
# config.yaml
notify:
webhook_url: https://ntfy.sh/station
api_key: tk_your_ntfy_api_key # optional
timeout_seconds: 10
```
Once configured, agents with `notify: true` in their frontmatter can send notifications:
```yaml theme={null}
---
model: openai/gpt-4o
notify: true
---
You can use the notify tool to alert users about task completion or errors.
```
### Environment Variables
| Variable | Description |
| ------------------------ | ------------------------------ |
| `STN_NOTIFY_WEBHOOK_URL` | Webhook URL for notifications |
| `STN_NOTIFY_API_KEY` | API key/token for webhook auth |
| `STN_NOTIFY_TIMEOUT` | Request timeout in seconds |
### Supported Webhook Formats
| Service | URL Format | Notes |
| ---------------- | -------------------------------- | ------------------------------ |
| ntfy.sh | `https://ntfy.sh/your-topic` | Supports title, priority, tags |
| Self-hosted ntfy | `https://ntfy.example.com/topic` | Same as ntfy.sh |
| Generic webhook | Any URL | Receives JSON payload |
## OpenCode Integration
Enable AI coding capabilities with [OpenCode](https://github.com/sst/opencode):
```yaml theme={null}
# config.yaml
coding:
opencode:
url: http://localhost:4096
```
### Starting OpenCode
```bash theme={null}
# Default (localhost only)
opencode
# For container mode (stn up) - REQUIRED
opencode --hostname 0.0.0.0
# Custom port
opencode --port 4000
```
When using `stn up` container mode, OpenCode must be started with `--hostname 0.0.0.0` to allow connections from the container. Station automatically rewrites `localhost` to `host.docker.internal` in the container config.
### Environment Variables
| Variable | Description |
| ------------------ | ---------------------------- |
| `STN_OPENCODE_URL` | Override OpenCode server URL |
Full OpenCode integration guide with coding tools and workflows
## Config Commands
Manage configuration via CLI:
```bash theme={null}
# Show current config
stn config show
# Set a value
stn config set ai_model gpt-4o-mini
# Get a value
stn config get ai_provider
```
## Next Steps
Learn all Station CLI commands
Start the Station server
# Container Lifecycle
Source: https://docs.cloudshipai.com/station/container-lifecycle
How stn up and stn down work - complete guide to Station container management
## Overview
`stn up` starts Station as an isolated Docker container, while `stn down` gracefully stops it. Data persists across restarts unless explicitly deleted.
## How `stn up` Works
When you run `stn up`, here's what happens:
```
YOU (Developer)
|
| $ stn up --bundle --workspace ~/code
v
+------------------------------------------------------------------+
| stn up |
+------------------------------------------------------------------+
|
| 1. CHECK DOCKER
| - Is Docker daemon running?
| - Is station-server container already running?
|
| 2. PREPARE VOLUMES
| - Create station-config volume (first run)
| - Create station-cache volume (build cache)
| - Import host ~/.config/station/config.yaml if exists
|
| 3. BUILD/PULL IMAGE
| - Try: docker pull ghcr.io/cloudshipai/station:latest
| - Fallback: docker build (if Dockerfile exists)
|
| 4. INSTALL BUNDLE (if --bundle flag)
| - Download from CloudShip API (if UUID)
| - Download from URL (if http://)
| - Use local file path
|
| 5. START CONTAINER
v
+------------------------------------------------------------------+
| Docker Container: station-server |
| |
| Volumes Mounted: |
| - station-config:/home/station/.config/station (data) |
| - station-cache:/home/station/.cache (build cache) |
| - ~/code:/workspace (your workspace - read/write) |
| - /var/run/docker.sock (Docker-in-Docker for Dagger) |
| |
| Command: stn serve --database ... --mcp-port 8586 |
+------------------------------------------------------------------+
|
v
+------------------------------------------------------------------+
| stn serve (inside container) |
| |
| STARTUP SEQUENCE: |
| 1. Load config.yaml |
| 2. Initialize SQLite database |
| 3. Run database migrations |
| 4. Create default environment if none exists |
| 5. DeclarativeSync: Sync files to database |
| - Scan environments/default/mcp-configs/*.json |
| - Connect to each MCP server, discover tools |
| - Scan environments/default/agents/*.prompt |
| - Parse prompts, create agent records |
| 6. Initialize Genkit (AI provider: OpenAI/Gemini) |
| 7. Initialize Lighthouse client (CloudShip connection) |
| 8. Start scheduler service (cron jobs) |
| 9. Start all servers |
+------------------------------------------------------------------+
```
### Running Services
After startup, Station exposes three services:
| Port | Service | Description |
| ---- | ------------------- | ------------------------------------------------------- |
| 8585 | API/UI Server | Web interface for settings, agent management (dev mode) |
| 8586 | MCP Server | Main MCP endpoint - tools, agents, data ingestion |
| 8587 | Dynamic Agent MCP | Agent execution - `run_agent`, `list_agents` |
| 4000 | Genkit Developer UI | Only when `--develop` flag is used |
### MCP Configuration
`stn up` automatically updates `.mcp.json` in your workspace:
```json theme={null}
{
"mcpServers": {
"station": {
"type": "http",
"url": "http://localhost:8586/mcp"
}
}
}
```
This allows Claude Desktop, Cursor, and other MCP clients to discover Station's tools and agents.
## How `stn down` Works
```
$ stn down [--remove-volume] [--clean-mcp]
|
v
+------------------------------------------------------------------+
| stn down |
| |
| 1. docker stop station-server (graceful SIGTERM, 3s timeout) |
| 2. docker rm station-server (remove container) |
| |
| Optional flags: |
| --remove-volume: docker volume rm station-config |
| WARNING: DELETES ALL agents, configs, database |
| |
| --clean-mcp: Remove "station" from .mcp.json |
| --remove-image: docker rmi station-server:latest |
| --force: SIGKILL if graceful stop fails |
+------------------------------------------------------------------+
```
### Data Preservation
By default, `stn down` preserves all your data:
| Data | Preserved? | How to Delete |
| ----------------------- | ---------- | ------------------------------------ |
| `station-config` volume | Yes | `stn down --remove-volume` |
| `station-cache` volume | Yes | `docker volume rm station-cache` |
| Workspace files | Always | (Your files, not managed by Station) |
## Bundle Development Workflow
Here's how to develop and test bundles with Station:
### Step 1: Create Bundle Files Locally
```
~/.config/station/environments/my-bundle/
├── agents/
│ ├── code-reviewer.prompt # Agent definition with tools
│ ├── deploy-helper.prompt # Another agent
│ └── ...
│
├── mcp-configs/
│ ├── github.json # GitHub MCP server config
│ ├── slack.json # Slack MCP server config
│ └── custom-tool.json # Your custom MCP server
│
└── variables.yml # Environment variables template
```
Example `variables.yml`:
```yaml theme={null}
variables:
- name: GITHUB_TOKEN
description: "GitHub access token"
required: true
- name: SLACK_BOT_TOKEN
description: "Slack bot token"
required: true
```
### Step 2: Test Locally with `stn serve`
```bash theme={null}
stn serve --environment my-bundle
```
This runs Station directly (no Docker), reading your files:
* DeclarativeSync scans `environments/my-bundle/`
* Connects to MCP servers defined in `mcp-configs/*.json`
* Loads agents from `agents/*.prompt`
* Exposes everything via MCP on ports 8586/8587
Make changes to your files, restart `stn serve`, and changes take effect immediately.
### Step 3: Package as a Bundle
```bash theme={null}
stn bundle create my-bundle -o my-bundle.tar.gz
```
Creates a tarball containing:
* `agents/*.prompt`
* `mcp-configs/*.json`
* `variables.yml`
* `manifest.json` (metadata)
### Step 4: Test the Bundle with `stn up`
```bash theme={null}
# Start fresh (removes previous data)
stn down --remove-volume
# Install and run your bundle in a container
stn up --bundle ./my-bundle.tar.gz
```
This simulates exactly how CloudShip users will run your bundle:
1. Creates isolated Docker container
2. Installs bundle into container's default environment
3. Runs DeclarativeSync to load everything
4. Starts MCP servers and agents
### Step 5: Publish to CloudShip
```bash theme={null}
stn bundle push my-bundle.tar.gz
```
Users can then install with:
```bash theme={null}
stn up --bundle
```
## Command Reference
### `stn up` Flags
| Flag | Description |
| ----------------- | --------------------------------------------------------- |
| `--workspace, -w` | Workspace directory to mount (default: current directory) |
| `--bundle` | CloudShip bundle ID, URL, or local file path to install |
| `--provider` | AI provider: openai, gemini, anthropic, custom |
| `--model` | AI model to use (e.g., gpt-4o-mini, gemini-2.0-flash-exp) |
| `--api-key` | API key for AI provider |
| `--base-url` | Custom base URL for OpenAI-compatible endpoints |
| `--develop` | Enable Genkit Developer UI mode (port 4000) |
| `--environment` | Station environment to use in develop mode |
| `--upgrade` | Rebuild container image before starting |
| `--env` | Additional environment variables to pass through |
| `--detach, -d` | Run container in background (default: true) |
| `--yes, -y` | Use defaults without interactive prompts |
### `stn down` Flags
| Flag | Description |
| ----------------- | --------------------------------------------------------------- |
| `--remove-volume` | Delete ALL Station data (environments, agents, bundles, config) |
| `--clean-mcp` | Remove Station from .mcp.json |
| `--remove-image` | Remove Docker image after stopping |
| `--force` | Force stop (kill) if graceful stop fails |
## Common Workflows
```bash theme={null}
# Remove all previous data
stn down --remove-volume
# Start with new bundle
stn up --bundle
```
```bash theme={null}
# Restart to pick up config changes
stn restart
# Or rebuild with latest image
stn down
stn up --upgrade
```
```bash theme={null}
# Test bundle locally first (no Docker)
stn serve --environment my-bundle
# When ready, test in container
stn bundle create my-bundle -o my-bundle.tar.gz
stn down --remove-volume
stn up --bundle ./my-bundle.tar.gz
```
```bash theme={null}
# Check status
stn status
# Follow logs
stn logs -f
# Show last 500 lines
stn logs --tail 500
```
## Environment Variables Passed to Container
`stn up` automatically passes through these environment variables:
| Category | Variables |
| ------------ | ------------------------------------------------------------------------- |
| AI Providers | `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `GEMINI_API_KEY`, `GOOGLE_API_KEY` |
| AWS | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION` |
| CloudShip | `STN_CLOUDSHIP_KEY`, `STN_CLOUDSHIP_ENDPOINT` |
| Tools | `GITHUB_TOKEN`, `SLACK_BOT_TOKEN` |
| Telemetry | `OTEL_EXPORTER_OTLP_ENDPOINT` |
Pass additional variables with `--env`:
```bash theme={null}
stn up --env CUSTOM_VAR=value --env ANOTHER_VAR=value
```
# Database & Persistence
Source: https://docs.cloudshipai.com/station/database
SQLite, cloud databases, and continuous backup with Litestream
# Database & Persistence
Station uses SQLite by default, with support for cloud databases and continuous backup for production deployments.
## Storage Options
| Option | Use Case | Setup |
| ------------------ | ---------------------------- | ------------------------ |
| **Local SQLite** | Development, single instance | Zero config (default) |
| **Cloud Database** | Multi-instance, teams | libsql connection string |
| **Litestream** | Production backup | S3/GCS replication |
## Local Development (Default)
Station uses a local SQLite file - zero configuration required:
```bash theme={null}
stn serve
# Database created at ~/.config/station/station.db
```
**Or specify a custom location:**
```yaml theme={null}
# config.yaml
database_url: /path/to/custom/station.db
```
## Cloud Database (libsql)
For multi-instance deployments or team collaboration, use a libsql-compatible cloud database like [Turso](https://turso.tech).
### Setup
1. **Create a database:**
```bash theme={null}
turso db create station-prod
turso db tokens create station-prod
```
2. **Configure Station:**
```bash theme={null}
export DATABASE_URL="libsql://station-prod-your-org.turso.io?authToken=your-token"
stn serve
```
Or in config:
```yaml theme={null}
# config.yaml
database_url: "libsql://station-prod-your-org.turso.io?authToken={{ .TURSO_AUTH_TOKEN }}"
```
### Benefits
* **Shared state** across multiple Station instances
* **Team collaboration** with centralized data
* **Multi-region** replication
* **Automatic backups** by the provider
* **Edge locations** for low latency
### Docker Deployment
```yaml theme={null}
# docker-compose.yml
services:
station:
image: ghcr.io/cloudshipai/station:latest
environment:
- DATABASE_URL=libsql://station-prod.turso.io?authToken=${TURSO_AUTH_TOKEN}
```
## Continuous Backup (Litestream)
For single-instance production deployments with disaster recovery, use [Litestream](https://litestream.io) for continuous SQLite replication.
### How It Works
```
Station ──writes──> SQLite ──replicates──> S3/GCS/Azure
│
Station (new instance) <──restores on startup─┘
```
### Docker with Litestream
Station's production Docker image includes Litestream:
```bash theme={null}
docker run -d \
-e LITESTREAM_S3_BUCKET=my-backups \
-e LITESTREAM_S3_ACCESS_KEY_ID=xxx \
-e LITESTREAM_S3_SECRET_ACCESS_KEY=yyy \
-e LITESTREAM_S3_REGION=us-east-1 \
ghcr.io/cloudshipai/station:production
```
### Configuration Options
**AWS S3:**
```bash theme={null}
export LITESTREAM_S3_BUCKET=my-station-backups
export LITESTREAM_S3_ACCESS_KEY_ID=AKIA...
export LITESTREAM_S3_SECRET_ACCESS_KEY=...
export LITESTREAM_S3_REGION=us-east-1
```
**Google Cloud Storage:**
```bash theme={null}
export LITESTREAM_GCS_BUCKET=my-station-backups
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
```
**Azure Blob Storage:**
```bash theme={null}
export LITESTREAM_AZURE_ACCOUNT_NAME=mystorageaccount
export LITESTREAM_AZURE_ACCOUNT_KEY=...
export LITESTREAM_AZURE_CONTAINER=station-backups
```
### Kubernetes Deployment
```yaml theme={null}
apiVersion: apps/v1
kind: Deployment
metadata:
name: station
spec:
replicas: 1 # Single replica with Litestream
template:
spec:
containers:
- name: station
image: ghcr.io/cloudshipai/station:production
env:
- name: LITESTREAM_S3_BUCKET
value: "station-backups"
- name: LITESTREAM_S3_ACCESS_KEY_ID
valueFrom:
secretKeyRef:
name: aws-credentials
key: access-key-id
- name: LITESTREAM_S3_SECRET_ACCESS_KEY
valueFrom:
secretKeyRef:
name: aws-credentials
key: secret-access-key
volumeMounts:
- name: data
mountPath: /data
volumes:
- name: data
emptyDir: {} # Ephemeral - Litestream restores on startup
```
### Benefits
* **Continuous replication** - Changes streamed in real-time
* **Automatic restore** - New instances restore from backup
* **Point-in-time recovery** - Restore to any point in time
* **Zero data loss** - Even on server failures
* **Cost effective** - Just object storage costs
## Migration
### Local to Cloud Database
1. **Export data:**
```bash theme={null}
sqlite3 ~/.config/station/station.db .dump > backup.sql
```
2. **Import to Turso:**
```bash theme={null}
turso db shell station-prod < backup.sql
```
3. **Update config:**
```yaml theme={null}
database_url: "libsql://station-prod.turso.io?authToken=..."
```
### Cloud to Local
```bash theme={null}
# Dump from Turso
turso db shell station-prod ".dump" > backup.sql
# Import locally
sqlite3 station.db < backup.sql
```
## Database Schema
Station's database stores:
| Table | Purpose |
| --------------- | ------------------------------ |
| `agents` | Agent definitions and metadata |
| `runs` | Execution history and results |
| `run_events` | Step-by-step execution logs |
| `mcp_configs` | MCP server configurations |
| `schedules` | Agent scheduling data |
| `workflows` | Workflow definitions |
| `workflow_runs` | Workflow execution history |
### Viewing Data
```bash theme={null}
# SQLite CLI
sqlite3 ~/.config/station/station.db
# List tables
.tables
# View recent runs
SELECT id, agent_id, status, created_at FROM runs ORDER BY created_at DESC LIMIT 10;
# View agent execution times
SELECT agent_id, AVG(duration_ms) as avg_ms FROM runs GROUP BY agent_id;
```
## Backup Best Practices
### Development
* Local SQLite is sufficient
* Git-backed workspace provides config backup
### Staging
* Use cloud database (Turso) for team access
* Or Litestream to staging S3 bucket
### Production
**Option A: Cloud Database (Turso)**
* Best for: Multiple instances, team access
* Pros: Managed, multi-region, automatic backups
* Cons: Dependency on external service
**Option B: Litestream**
* Best for: Single instance, cost-sensitive
* Pros: Simple, cheap (just S3), fast local reads
* Cons: Single writer only
**Option C: Both**
* Primary: Turso for live operations
* Secondary: Periodic SQLite exports to S3
## Troubleshooting
### Connection Failed
```
Error: failed to connect to database
```
**Check:**
1. `DATABASE_URL` is correctly formatted
2. Auth token is valid and not expired
3. Network allows outbound to database endpoint
### Litestream Not Restoring
```
Error: no backup found
```
**Check:**
1. S3 bucket exists and is accessible
2. Correct region configured
3. IAM credentials have read access
### Database Locked
```
Error: database is locked
```
**Solutions:**
1. Ensure only one Station instance writes
2. Use cloud database for multi-instance
3. Check for zombie processes: `lsof station.db`
## Next Steps
* [Deployment](/station/deployment/production) - Production setup
* [GitOps](/station/gitops) - Version control your config
* [CloudShip](/station/cloudship) - Centralized management
# Cloud Deployment
Source: https://docs.cloudshipai.com/station/deployment
Deploy Station to Fly.io, Kubernetes, and bare metal servers
The `stn deploy` command provides production-ready deployment to multiple platforms with built-in secrets management, persistent storage, and CloudShip integration.
## Deployment Targets
| Target | Best For | Command |
| -------------- | ----------------------------------- | --------------------- |
| **Fly.io** | Quick cloud deployment, global edge | `--target fly` |
| **Kubernetes** | Enterprise, existing K8s clusters | `--target kubernetes` |
| **Ansible** | Bare metal, VMs, on-premise | `--target ansible` |
## Fly.io Deployment
The fastest path to production. Deploys Station with persistent storage, automatic TLS, and global edge distribution.
### Quick Deploy
```bash theme={null}
# Deploy an environment to Fly.io
stn deploy my-env --target fly
# Deploy with a custom app name
stn deploy my-env --target fly --name my-station
# Deploy to a specific region
stn deploy my-env --target fly --region syd
```
### What Gets Deployed
* Docker image with your agents baked in
* 3GB persistent volume for database and configs
* Dedicated IPv4 address
* Automatic TLS certificate
* All secrets set via `fly secrets`
### Example Output
```
🚀 Deploying environment 'my-env' to fly (region: ord)
✓ Built image: station-my-env:latest
✓ App created: my-station
✓ 14 secrets set
✓ IPv4 allocated
✓ Volume created
✓ Deployed to Fly.io
✅ Deployment Complete!
🤖 Agent MCP Endpoint:
https://my-station.fly.dev/mcp
📋 Available Agents (3):
- agent_cost-analyzer
- agent_security-scanner
- agent_deployment-helper
```
### Add to Claude Desktop
After deployment, add the MCP endpoint to Claude Desktop:
```json theme={null}
{
"mcpServers": {
"my-station": {
"url": "https://my-station.fly.dev/mcp"
}
}
}
```
### Fly.io Options
```bash theme={null}
# Enable auto-stop when idle (saves cost, but loses persistent CloudShip connection)
stn deploy my-env --target fly --auto-stop
# Tear down deployment
stn deploy my-env --target fly --destroy
# Enable development UI
fly secrets set STN_DEV_MODE=true --app my-station
```
## Kubernetes Deployment
Generates production-ready Kubernetes manifests or deploys directly to your cluster.
### Generate Manifests
```bash theme={null}
# Generate manifests to a directory
stn deploy my-env --target kubernetes --dry-run --output-dir ./k8s/
# Preview what would be generated
stn deploy my-env --target k8s --dry-run
```
### Deploy to Cluster
```bash theme={null}
# Deploy to default namespace
stn deploy my-env --target kubernetes
# Deploy to specific namespace
stn deploy my-env --target k8s --namespace production
# Use specific kubectl context
stn deploy my-env --target k8s --context my-cluster
```
### Generated Resources
* **Deployment** - Station container with agents
* **Service** - ClusterIP for internal access
* **Secret** - API keys and CloudShip credentials
* **PersistentVolumeClaim** - Database and config storage
* **ConfigMap** - Environment configuration
### Runtime Secrets
For production, use runtime secrets instead of baking them into manifests:
```bash theme={null}
# Station fetches secrets from AWS SSM at startup
stn deploy my-env --target k8s \
--secrets-backend aws-ssm \
--secrets-path /station/prod/
```
See [Secrets Management](#secrets-management) below.
## Ansible Deployment
Deploys Station to any Linux server via SSH. Generates an Ansible playbook that:
* Installs Docker
* Pulls the Station image
* Configures systemd service
* Sets up persistent storage
### Generate Playbook
```bash theme={null}
# Preview the generated files
stn deploy my-env --target ansible --dry-run --output-dir /tmp/ansible-deploy
# Generated files:
# - playbook.yml
# - inventory.ini
# - vars/main.yml
# - templates/docker-compose.yml.j2
# - templates/station.service.j2
```
### Deploy to Servers
```bash theme={null}
# Deploy to servers specified in inventory
stn deploy my-env --target ansible
# Specify hosts directly
stn deploy my-env --target ansible --hosts user@server1.example.com --hosts user@server2.example.com
# Use custom SSH key
stn deploy my-env --target ansible --ssh-key ~/.ssh/deploy_key --ssh-user deploy
```
### Inventory Configuration
The generated `inventory.ini`:
```ini theme={null}
[station_servers]
192.168.1.100 ansible_user=ubuntu ansible_ssh_private_key_file=~/.ssh/id_rsa
[station_servers:vars]
ansible_python_interpreter=/usr/bin/python3
```
### Manual Playbook Run
```bash theme={null}
cd /tmp/ansible-deploy
ansible-playbook -i inventory.ini playbook.yml
```
### Verify Deployment
After deployment, verify Station is running:
```bash theme={null}
# Check service status
ssh user@server systemctl status station-my-env
# Check logs
ssh user@server docker logs station-my-env
# Test agent endpoint
curl http://server:8587/health
```
## Secrets Management
Station supports runtime secrets fetching from external secret stores. Instead of baking secrets into deployment configs, the container fetches them at startup.
Runtime secrets loading requires Station v0.24.9+ which includes AWS CLI in the container image. The container fetches secrets at startup before the Station process begins serving requests.
### Supported Backends
| Backend | URI Format | Example |
| ----------------------- | ----------------------- | --------------------------------------------------------- |
| AWS Secrets Manager | `aws-secretsmanager://` | `aws-secretsmanager://station/prod` |
| AWS SSM Parameter Store | `aws-ssm://` | `aws-ssm:///station/prod/` |
| HashiCorp Vault | `vault://` | `vault://secret/data/station/prod` |
| GCP Secret Manager | `gcp-secretmanager://` | `gcp-secretmanager://projects/my-project/secrets/station` |
| SOPS | `sops://` | `sops://./secrets/prod.enc.yaml` |
### AWS SSM Parameter Store
Store secrets as SSM parameters:
```bash theme={null}
# Create parameters
aws ssm put-parameter --name "/station/prod/OPENAI_API_KEY" --value "sk-..." --type SecureString
aws ssm put-parameter --name "/station/prod/STN_CLOUDSHIP_KEY" --value "csk_..." --type SecureString
```
Deploy with SSM backend:
```bash theme={null}
stn deploy my-env --target fly \
--secrets-backend aws-ssm \
--secrets-path /station/prod/
```
At startup, Station loads all parameters under `/station/prod/` and injects them into config:
```
🔐 Loading secrets from backend: aws-ssm (path: /station/prod/)
Injected: [OPENAI_API_KEY→config, STN_CLOUDSHIP_KEY→config]
✅ Loaded 5 secrets from aws-ssm
```
### AWS Secrets Manager
Store secrets as a JSON object:
```bash theme={null}
aws secretsmanager create-secret \
--name station/prod \
--secret-string '{"OPENAI_API_KEY":"sk-...","STN_CLOUDSHIP_KEY":"csk_..."}'
```
Deploy:
```bash theme={null}
stn deploy my-env --target k8s \
--secrets-backend aws-secretsmanager \
--secrets-path station/prod
```
### HashiCorp Vault
```bash theme={null}
# Store secrets
vault kv put secret/station/prod OPENAI_API_KEY=sk-... STN_CLOUDSHIP_KEY=csk_...
# Deploy with Vault
stn deploy my-env --target k8s \
--secrets-backend vault \
--secrets-path secret/data/station/prod
```
Set Vault address and token via environment:
```bash theme={null}
export VAULT_ADDR=https://vault.example.com
export VAULT_TOKEN=hvs.xxx
```
### Supported Secret Keys
Station automatically maps these secret keys to configuration:
| Secret Key | Config Field |
| ------------------------ | ---------------------------- |
| `STN_AI_API_KEY` | AI provider API key |
| `OPENAI_API_KEY` | OpenAI API key (fallback) |
| `ANTHROPIC_API_KEY` | Anthropic API key (fallback) |
| `STN_CLOUDSHIP_KEY` | CloudShip registration key |
| `STN_CLOUDSHIP_ENDPOINT` | CloudShip endpoint |
| `STN_CLOUDSHIP_NAME` | Station name in CloudShip |
All other secrets are injected as environment variables.
## Export Variables
See what secrets your deployment needs:
```bash theme={null}
# Show required variables
stn deploy export-vars my-env
# Generate .env template
stn deploy export-vars my-env --format env > secrets.env
# For bundle-based deployment
stn deploy export-vars --bundle-id e26b414a-f076-4135-927f-810bc1dc892a
```
## Bundle-Based Deployment
Deploy directly from CloudShip bundles without a local environment:
```bash theme={null}
# Deploy a bundle from CloudShip
stn deploy --bundle-id e26b414a-f076-4135-927f-810bc1dc892a --target fly
# Deploy a local bundle file
stn deploy --bundle ./my-agents.tar.gz --target k8s --name my-station
# Deploy from URL
stn deploy --bundle https://example.com/bundle.tar.gz --target ansible
```
## CloudShip Integration
When `cloudship.enabled: true` in your config, deployed Stations automatically:
* Connect to CloudShip Lighthouse via gRPC
* Report online status with heartbeats
* Accept remote agent execution requests
* Stream telemetry and run data
Configure in deployment:
```bash theme={null}
stn deploy my-env --target fly # CloudShip config from local station is included
```
Or set manually:
```bash theme={null}
fly secrets set STN_CLOUDSHIP_ENABLED=true --app my-station
fly secrets set STN_CLOUDSHIP_KEY=csk_xxx --app my-station
fly secrets set STN_CLOUDSHIP_ENDPOINT=lighthouse.cloudshipai.com:443 --app my-station
```
## Deployment Lifecycle
### Update Deployment
Re-run deploy to update with new agents or configuration:
```bash theme={null}
stn deploy my-env --target fly # Rebuilds and redeploys
```
### Destroy Deployment
```bash theme={null}
# Fly.io
stn deploy my-env --target fly --destroy
# Kubernetes
kubectl delete -f ./k8s/
# Ansible - run with station_state=absent
ansible-playbook -i inventory.ini playbook.yml -e "station_state=absent"
```
### Check Status
```bash theme={null}
# Fly.io
fly status --app my-station
fly logs --app my-station
# Kubernetes
kubectl get pods -l app=station
kubectl logs -l app=station
# Ansible-deployed
ssh user@server systemctl status station-my-env
```
## Troubleshooting
### Fly.io Issues
```bash theme={null}
# Check logs
fly logs --app my-station
# SSH into container
fly ssh console --app my-station
# Check secrets
fly secrets list --app my-station
```
### Kubernetes Issues
```bash theme={null}
# Check pod status
kubectl describe pod -l app=station
# Check events
kubectl get events --sort-by='.lastTimestamp'
# View logs
kubectl logs -l app=station --tail=100
```
### Ansible Issues
```bash theme={null}
# Run with verbose output
ansible-playbook -i inventory.ini playbook.yml -vvv
# Check systemd status on remote
ssh user@server journalctl -u station-my-env -f
```
### Secrets Not Loading
Verify the secrets backend is configured:
```bash theme={null}
# Check environment variables in container
fly ssh console --app my-station -C "env | grep STN_SECRETS"
# Should show:
# STN_SECRETS_BACKEND=aws-ssm
# STN_SECRETS_PATH=/station/prod/
```
Verify AWS credentials (for SSM/Secrets Manager):
```bash theme={null}
# Container needs AWS credentials via IAM role or environment
fly secrets set AWS_ACCESS_KEY_ID=xxx --app my-station
fly secrets set AWS_SECRET_ACCESS_KEY=xxx --app my-station
```
# Docker Deployment
Source: https://docs.cloudshipai.com/station/docker
Deploy Station using Docker
## Quick Start with `stn up`
The simplest way to run Station in Docker:
```bash theme={null}
stn up
```
This single command handles everything: building images, creating volumes, starting services, and configuring MCP endpoints.
### Primary Use Case: Running Bundles
`stn up` is designed to make running agent bundles effortless. Whether from CloudShip, a URL, or a local file:
```bash theme={null}
# Run a bundle from your CloudShip account
stn up --bundle finops-cost-analyzer
# Run a bundle from any URL
stn up --bundle https://github.com/myorg/agents/releases/download/v1.0/bundle.tar.gz
# Run a local bundle file you're developing
stn up --bundle ./my-agents.tar.gz
```
The bundle is automatically installed into the container's default environment and all agents become available immediately.
### Secondary Use Case: Testing Local Configurations
For developers building custom agents, `stn up` provides an isolated container environment that mirrors production:
```bash theme={null}
# Mount your local workspace into the container
stn up --workspace ~/my-agent-project
# Test a specific environment configuration
stn up --environment staging
# Enable development mode with Genkit reflection UI
stn up --develop
```
This ensures your agents work correctly in the same containerized environment they'll run in production, without affecting your local system.
## Manual Docker Deployment
### Using Docker Compose
Station provides a `docker-compose.yml` for production deployments:
```yaml theme={null}
version: '3.8'
services:
jaeger:
image: jaegertracing/all-in-one:1.53
ports:
- "16686:16686" # Jaeger UI
- "4317:4317" # OTLP gRPC
- "4318:4318" # OTLP HTTP
environment:
- COLLECTOR_OTLP_ENABLED=true
station:
image: ghcr.io/cloudshipai/station:latest
ports:
- "8585:8585" # API/UI
- "8586:8586" # MCP
- "8587:8587" # Agent MCP
volumes:
- station_data:/home/station/.config/station
- ./workspace:/workspace
environment:
- OPENAI_API_KEY=${OPENAI_API_KEY}
- OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger:4318
depends_on:
- jaeger
volumes:
station_data:
```
Start with:
```bash theme={null}
docker-compose up -d
```
### Building Custom Image
Build from source:
```bash theme={null}
cd station/
docker build -t my-station:latest .
```
Or build with UI embedded:
```bash theme={null}
make build-with-ui
docker build -t my-station:latest .
```
## Zero-Config Deployment
Station supports automatic bundle installation from mounted directories:
```yaml theme={null}
services:
station:
image: ghcr.io/cloudshipai/station:latest
volumes:
- ./bundles:/bundles:ro # Auto-install bundles from here
- station_data:/home/station/.config/station
environment:
- OPENAI_API_KEY=${OPENAI_API_KEY}
```
Drop `.tar.gz` bundle files in `./bundles/` and they install automatically on startup.
## Environment Variables
Configure Station via environment variables:
```yaml theme={null}
environment:
# AI Provider
- OPENAI_API_KEY=${OPENAI_API_KEY}
- STN_AI_PROVIDER=openai
- STN_AI_MODEL=gpt-4o
# Ports
- STN_API_PORT=8585
- STN_MCP_PORT=8586
# Mode
- STATION_LOCAL_MODE=true
# Telemetry
- OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger:4318
# CloudShip (optional)
- STN_CLOUDSHIP_KEY=your-key
- STN_CLOUDSHIP_ENDPOINT=lighthouse.cloudship.ai:443
```
## Volume Mounts
| Mount | Purpose |
| ------------------------------- | -------------------------- |
| `/home/station/.config/station` | Configuration and database |
| `/workspace` | Workspace for agents |
| `/bundles` | Auto-install bundles |
## Networking
### Internal Docker Network
For container-to-container communication, use Docker's internal DNS:
```yaml theme={null}
environment:
- OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger:4318 # jaeger is service name
```
### Host Network Access
From inside the container, access host services:
```yaml theme={null}
environment:
# Use host.docker.internal on Mac/Windows
- DATABASE_URL=postgresql://host.docker.internal:5432/mydb
```
On Linux, add:
```yaml theme={null}
extra_hosts:
- "host.docker.internal:host-gateway"
```
## Health Checks
Add health checks for orchestration:
```yaml theme={null}
services:
station:
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8585/api/v1/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
```
## Kubernetes Deployment
Example Kubernetes deployment:
```yaml theme={null}
apiVersion: apps/v1
kind: Deployment
metadata:
name: station
spec:
replicas: 1
selector:
matchLabels:
app: station
template:
metadata:
labels:
app: station
spec:
containers:
- name: station
image: ghcr.io/cloudshipai/station:latest
ports:
- containerPort: 8585
- containerPort: 8586
env:
- name: OPENAI_API_KEY
valueFrom:
secretKeyRef:
name: station-secrets
key: openai-api-key
volumeMounts:
- name: station-data
mountPath: /home/station/.config/station
volumes:
- name: station-data
persistentVolumeClaim:
claimName: station-pvc
```
## Troubleshooting
### Container Won't Start
Check logs:
```bash theme={null}
docker logs station-server
```
### Permission Issues
Station runs as user `station` (UID 1000). Ensure mounted volumes are accessible:
```bash theme={null}
chmod -R 755 ./workspace
```
### Port Conflicts
Check if ports are in use:
```bash theme={null}
lsof -i :8585
lsof -i :8586
```
# Evaluation & Testing
Source: https://docs.cloudshipai.com/station/evaluation
Test agents with LLM-as-judge scoring
## Why Built-In Evaluation?
**Traditional Testing:**
* Manual testing with ad-hoc prompts
* Subjective quality checks
* No baseline for comparisons
**Station's Evaluation:**
* Automated scenario generation
* LLM-as-judge scoring
* Business-focused metrics
* Full execution traces
## Via MCP Tools
The easiest way to run evaluations is through your AI assistant:
```
"Generate 50 test scenarios for the cost-analyzer agent and run them"
```
Station uses these MCP tools:
| Tool | Purpose |
| ------------------------- | ---------------------------------------------- |
| `generate_and_test_agent` | Generate scenarios + execute tests in one step |
| `batch_execute_agents` | Run multiple agents in parallel |
| `evaluate_benchmark` | LLM-as-judge scoring on a run |
| `evaluate_dataset` | Score entire dataset |
| `list_benchmark_results` | View evaluation results |
| `get_benchmark_status` | Check async evaluation progress |
**Reports:**
| Tool | Purpose |
| ----------------- | ---------------------------------- |
| `create_report` | Define team performance criteria |
| `generate_report` | Run benchmarks and generate report |
| `list_reports` | List all reports |
| `get_report` | Get report details |
## Via CLI
### 1. Generate Test Scenarios
Station AI generates diverse test scenarios based on your agent's purpose:
```bash theme={null}
stn benchmark generate --agent "Cost Analyzer" --count 50
```
**Variation Strategies:**
* `comprehensive` - Wide range of scenarios (default)
* `edge_cases` - Unusual boundary conditions
* `common` - Typical real-world cases
### 2. Execute Tests
Run all scenarios with trace capture:
```bash theme={null}
stn benchmark run --agent "Cost Analyzer"
```
Results saved to timestamped dataset:
```
~/.config/station/environments/default/datasets/
└── agent-42-20251215-103045/
├── dataset.json
└── runs/
```
### 3. Evaluate Quality
LLM-as-judge analyzes each run:
```bash theme={null}
stn benchmark evaluate --dataset agent-42-20251215-103045
```
## Quality Metrics
| Metric | Description | Weight |
| ---------------- | -------------------------- | ------ |
| **Accuracy** | Correctness of results | 30% |
| **Completeness** | All aspects addressed | 25% |
| **Tool Usage** | Appropriate tool selection | 20% |
| **Efficiency** | Minimal unnecessary steps | 15% |
| **Safety** | No harmful actions | 10% |
## Evaluation Report
```json theme={null}
{
"agent": "Cost Analyzer",
"scenarios_tested": 50,
"pass_rate": 0.92,
"average_score": 8.4,
"metrics": {
"accuracy": 8.7,
"completeness": 8.2,
"tool_usage": 8.5,
"efficiency": 8.1,
"safety": 9.0
},
"production_ready": true
}
```
## Team Reports
Evaluate multi-agent teams against business goals.
### Via MCP
```
"Create a performance report for my SRE team measuring incident response time and accuracy"
```
```
"Generate the SRE team report"
```
### Via CLI
```bash theme={null}
stn report generate --environment default
```
### Report Metrics
| Metric | Description |
| ---------------- | ------------------------ |
| **Team Score** | Overall 1-10 rating |
| **MTTR** | Mean Time to Resolution |
| **Cost Savings** | \$ identified by agents |
| **Accuracy** | vs ground truth |
| **Tool Cost** | Execution cost per agent |
### Example Report Output
```
Team Performance: 7.5/10
✅ Multi-agent coordination: 8.5/10 - Excellent delegation
✅ Tool utilization: 8.0/10 - Effective use of all tools
✅ Root cause analysis: 7.5/10 - Identifies issues accurately
⚠️ Resolution speed: 7.0/10 - Room for improvement
⚠️ Communication clarity: 6.5/10 - Could be more concise
```
## Viewing Traces
Every evaluation run captures full execution traces:
```bash theme={null}
# Start Jaeger
docker run -d --name jaeger \
-p 16686:16686 -p 4317:4317 -p 4318:4318 \
jaegertracing/all-in-one:latest
# View traces at http://localhost:16686
```
## Best Practices
Run evaluation before promoting agents to production.
Include boundary conditions to find failure modes.
Compare scores across agent versions.
Manually inspect low-scoring runs to improve prompts.
## CLI Reference
```bash theme={null}
# Generate scenarios
stn benchmark generate --agent --count --strategy
# Run benchmarks
stn benchmark run --agent [--concurrent ]
# Evaluate dataset
stn benchmark evaluate --dataset
# List datasets
stn benchmark list
# Generate team report
stn report generate --environment
```
## Next Steps
Package tested agents for distribution
Centralized monitoring and management
# Faker System
Source: https://docs.cloudshipai.com/station/fakers
AI-powered mock data for safe agent development and testing
# Faker System
Station's Faker system generates realistic mock data using AI, enabling safe development and testing without production credentials.
## Why Fakers?
| Without Fakers | With Fakers |
| ------------------------------ | ----------------------------- |
| Need production credentials | No credentials required |
| Risk of affecting real systems | Completely isolated |
| Limited test scenarios | Unlimited realistic scenarios |
| Expensive API calls | Free, local generation |
## Quick Start
### Via MCP Tool
```
"Create a prometheus-metrics faker that generates realistic Kubernetes metrics"
```
Station uses the `faker_create_standalone` tool to set up the faker.
### Via CLI
```bash theme={null}
stn faker create prometheus-metrics \
--goal "Generate realistic Prometheus metrics for a microservices environment"
```
## How It Works
```
Agent ──calls tool──> Faker MCP Server ──AI generates──> Realistic Mock Data
│
└── Uses Station's AI provider (no extra config)
```
Fakers are MCP servers that:
1. Receive tool calls from agents
2. Use AI to generate contextually appropriate responses
3. Return realistic mock data
## Creating Fakers
### MCP Tool (Recommended)
```
"Create a datadog faker with tools for querying metrics, logs, and APM data"
```
### Programmatic
```json theme={null}
{
"faker_name": "datadog",
"description": "Mock Datadog monitoring data",
"goal": "Generate realistic Datadog metrics, logs, and APM traces for a production e-commerce application with occasional performance issues",
"tools": [
{
"name": "get_metrics",
"description": "Query time series metrics",
"inputSchema": {
"type": "object",
"properties": {
"query": {"type": "string"},
"from": {"type": "integer"},
"to": {"type": "integer"}
}
}
},
{
"name": "search_logs",
"description": "Search application logs",
"inputSchema": {
"type": "object",
"properties": {
"query": {"type": "string"},
"limit": {"type": "integer"}
}
}
}
]
}
```
### In template.json
```json theme={null}
{
"mcpServers": {
"datadog": {
"command": "stn",
"args": [
"faker",
"--ai-instruction",
"Generate production incident data: high CPU, memory leaks, error spikes for an e-commerce platform"
]
}
}
}
```
## Configuration
### Goal/Instruction
The `goal` or `ai-instruction` guides the AI in generating appropriate data:
**Good:**
```
"Generate realistic Kubernetes metrics for a production cluster with 50 nodes,
running microservices. Include occasional resource pressure and pod restarts."
```
**Too vague:**
```
"Generate some metrics"
```
### Tool Definitions
Define tools that match your real MCP server's interface:
```json theme={null}
{
"tools": [
{
"name": "get_pod_metrics",
"description": "Get CPU and memory metrics for pods",
"inputSchema": {
"type": "object",
"properties": {
"namespace": {"type": "string"},
"pod_name": {"type": "string"},
"metric": {"type": "string", "enum": ["cpu", "memory", "network"]}
},
"required": ["namespace"]
}
}
]
}
```
## Examples
### Infrastructure Monitoring
```bash theme={null}
stn faker create kubernetes \
--goal "Generate Kubernetes cluster metrics for a production environment with 3 namespaces (frontend, backend, data). Include realistic resource utilization, occasional OOM kills, and pod restarts."
```
### Security Scanning
```bash theme={null}
stn faker create security-scanner \
--goal "Generate security scan results for a Node.js application. Include a mix of critical, high, and low severity vulnerabilities in dependencies, with realistic CVE IDs and remediation suggestions."
```
### Cost Analysis
```bash theme={null}
stn faker create aws-cost-explorer \
--goal "Generate AWS cost data for a medium-sized SaaS company. Include EC2, RDS, S3, and Lambda costs with realistic daily variations and occasional cost spikes from autoscaling events."
```
### Incident Response
```bash theme={null}
stn faker create pagerduty \
--goal "Generate PagerDuty incident data for an SRE team. Include a mix of acknowledged, triggered, and resolved incidents across different services with realistic escalation patterns."
```
## Using Fakers in Agents
### Assign to Agent
```yaml theme={null}
---
metadata:
name: "metrics-investigator"
description: "Investigate performance issues using metrics"
tools:
- "__get_metrics" # From datadog faker
- "__query_time_series" # From prometheus faker
---
{{role "system"}}
You investigate performance issues by analyzing metrics data.
```
### In template.json
```json theme={null}
{
"mcpServers": {
"prometheus": {
"command": "stn",
"args": ["faker", "--config", "prometheus-faker.json"]
},
"datadog": {
"command": "stn",
"args": ["faker", "--ai-instruction", "Generate realistic APM data for microservices"]
}
}
}
```
## Faker vs Real MCP Server
### Development with Faker
```json theme={null}
{
"mcpServers": {
"datadog": {
"command": "stn",
"args": ["faker", "--ai-instruction", "Generate monitoring data"]
}
}
}
```
### Production with Real Server
```json theme={null}
{
"mcpServers": {
"datadog": {
"command": "datadog-mcp",
"env": {
"DD_API_KEY": "{{ .DATADOG_API_KEY }}",
"DD_APP_KEY": "{{ .DATADOG_APP_KEY }}"
}
}
}
}
```
Use different `template.json` files per environment to swap between faker and real.
## Advanced Configuration
### Persistence
By default, fakers don't persist data between calls. For stateful scenarios:
```json theme={null}
{
"faker_name": "stateful-db",
"persist": true,
"goal": "Simulate a database with user records that persist between queries"
}
```
### Auto-sync
Faker configurations can auto-sync to your environment:
```json theme={null}
{
"auto_sync": true // Updates template.json automatically
}
```
### Debug Mode
Enable verbose logging to see AI prompts and responses:
```bash theme={null}
stn faker create my-faker --goal "..." --debug
```
## Testing Agents with Fakers
### Generate Test Scenarios
```
"Generate 10 test scenarios for the incident-coordinator agent using fakers"
```
### Run Evaluation
```bash theme={null}
# Create fakers for all dependencies
stn faker create datadog --goal "Generate incident data"
stn faker create kubernetes --goal "Generate cluster issues"
# Run agent evaluation
stn eval run incident-coordinator --scenarios 100
```
## Best Practices
1. **Match real schemas** - Faker tool schemas should match your real MCP servers
2. **Be specific in goals** - Detailed instructions produce more realistic data
3. **Include edge cases** - Mention error conditions and anomalies in goals
4. **Version your fakers** - Keep faker configs in Git alongside agents
5. **Test transitions** - Ensure agents work with both faker and real data
## Troubleshooting
### Generic/Unrealistic Data
**Problem:** Faker returns too generic data
**Solution:** Make the goal more specific:
```
# Too generic
"Generate metrics"
# Better
"Generate Prometheus metrics for a Kubernetes cluster running an e-commerce
application. Include realistic CPU/memory patterns with daily traffic cycles,
occasional memory leaks in the checkout service, and 99.9% uptime for core services."
```
### Schema Mismatch
**Problem:** Agent expects different data format
**Solution:** Define explicit output schema in tool definition:
```json theme={null}
{
"name": "get_metrics",
"outputSchema": {
"type": "object",
"properties": {
"series": {
"type": "array",
"items": {
"type": "object",
"properties": {
"timestamp": {"type": "integer"},
"value": {"type": "number"}
}
}
}
}
}
}
```
### Slow Responses
**Problem:** Faker takes too long
**Solution:**
1. Use a faster model for fakers
2. Simplify the goal
3. Cache common responses
## Next Steps
* [Sandbox](/station/sandbox) - Isolated code execution
* [Evaluation](/station/agents/monitoring) - Test agent performance
* [Bundles](/station/bundles/creating) - Package agents with fakers
# File Management
Source: https://docs.cloudshipai.com/station/files
Upload, download, and manage files for sandbox staging
The `stn files` commands manage files in NATS Object Store for staging data to/from sandbox containers.
## Overview
Files serve as a staging area between your local system and sandbox containers:
1. **Upload** files from local filesystem
2. **Agents stage** files into sandbox using `sandbox_stage_file`
3. **Agents process** data in the sandbox
4. **Agents publish** results using `sandbox_publish_file`
5. **Download** results to local filesystem
File staging bypasses LLM context entirely—no token costs, no size limits, full binary support.
## Commands
### Upload
Upload a file to NATS Object Store.
```bash theme={null}
stn files upload [flags]
```
| Flag | Description |
| ----------- | ----------------------------------------- |
| `--key` | Custom file key (default: auto-generated) |
| `--ttl` | Time-to-live (e.g., `24h`, `7d`) |
| `--station` | Station API URL for remote upload |
```bash Basic theme={null}
stn files upload data.csv
# Output: files/f_01JGXYZ123ABC (2.4 MB)
```
```bash Custom Key theme={null}
stn files upload --key mydata/input.csv data.csv
```
```bash With Expiration theme={null}
stn files upload --ttl 24h report.pdf
```
```bash Remote Station theme={null}
stn files upload --station http://localhost:8585 data.csv
```
### Download
Download a file from the object store.
```bash theme={null}
stn files download [flags]
```
| Flag | Short | Description |
| ----------- | ----- | ---------------- |
| `--output` | `-o` | Output file path |
| `--station` | | Station API URL |
```bash Basic theme={null}
stn files download f_abc123 -o output.csv
```
```bash Full Key theme={null}
stn files download files/f_abc123
```
```bash Workflow Output theme={null}
stn files download runs/run_xyz/output/result.csv -o result.csv
```
You can use either the full key (`files/f_abc123`) or just the file ID (`f_abc123`)—it auto-expands.
### List
List files in the object store.
```bash theme={null}
stn files list [flags]
```
| Flag | Description |
| ----------- | -------------------- |
| `--prefix` | Filter by key prefix |
| `--json` | Output as JSON |
| `--station` | Station API URL |
```bash All Files theme={null}
stn files list
```
```bash User Uploads Only theme={null}
stn files list --prefix files/
```
```bash Workflow Outputs theme={null}
stn files list --prefix runs/
```
```bash JSON Output theme={null}
stn files list --json
```
**Example output:**
```
📁 Files
Found 3 file(s):
• files/f_01JGABC123DEF
Size: 2.4 MB | Type: text/csv | Created: 2025-01-15 10:30
• files/f_01JGXYZ789UVW
Size: 128 KB | Type: application/json | Created: 2025-01-15 11:45
• runs/run_abc/output/summary.csv
Size: 64 KB | Type: text/csv | Created: 2025-01-15 12:00
Expires: 2025-01-22 12:00
```
### Info
Show metadata for a file.
```bash theme={null}
stn files info [flags]
```
| Flag | Description |
| ----------- | --------------- |
| `--station` | Station API URL |
```bash theme={null}
stn files info f_abc123
```
**Output:**
```
ℹ️ File Info
Key: files/f_01JGABC123DEF
Size: 2.4 MB
Content-Type: text/csv
Checksum: sha256:abc123...
Created: 2025-01-15T10:30:00Z
```
### Delete
Delete a file from the object store.
```bash theme={null}
stn files delete [flags]
```
| Flag | Short | Description |
| ----------- | ----- | ----------------- |
| `--force` | `-f` | Skip confirmation |
| `--station` | | Station API URL |
```bash theme={null}
# With confirmation
stn files delete f_abc123
# Skip confirmation
stn files delete f_abc123 --force
```
## File Key Conventions
Station uses a hierarchical key structure:
| Pattern | Description | Lifecycle |
| ------------------------- | ----------------- | ----------------------- |
| `files/{file_id}` | User uploads | Permanent until deleted |
| `runs/{run_id}/output/*` | Workflow outputs | Auto-cleanup after TTL |
| `sessions/{session_id}/*` | Session artifacts | Cleanup with session |
**File ID format:** `f_{ulid}` (time-ordered, globally unique)
## Local vs Remote Mode
Connects directly to NATS JetStream on the local machine.
```bash theme={null}
# Uses WORKFLOW_NATS_URL (default: nats://127.0.0.1:4222)
stn files upload data.csv
stn files list
```
Requires NATS server running locally.
Connects to Station API via HTTP.
```bash theme={null}
stn files upload --station http://remote:8585 data.csv
stn files download --station http://remote:8585 f_abc -o out.csv
```
Useful when Station runs on a remote server or you don't have direct NATS access.
## Complete Example
Process a large CSV file through a sandbox workflow:
```bash theme={null}
# 1. Upload input file (5 MB CSV)
$ stn files upload sales_data.csv
📤 Upload File
✅ Uploaded successfully
Key: files/f_01JGABC123DEF
Size: 5.2 MB
Type: text/csv
# 2. Run workflow referencing the file
$ stn workflow run csv-analyzer \
--input '{"input_file": "files/f_01JGABC123DEF"}'
# Workflow runs:
# - Agent opens sandbox
# - Agent stages file: sandbox_stage_file(file_key="files/f_01JGABC123DEF")
# - Agent processes with Python/pandas
# - Agent publishes: sandbox_publish_file(source="output/results.csv")
# Output: "Analysis complete. Results: files/f_01JGXYZ789UVW"
# 3. Download results
$ stn files download f_01JGXYZ789UVW -o analysis_results.csv
📥 Download File
✅ Downloaded successfully
Output: analysis_results.csv
Size: 128 KB
Type: text/csv
```
## Configuration
### Environment Variables
| Variable | Default | Description |
| ------------------- | ----------------------- | -------------------------- |
| `WORKFLOW_NATS_URL` | `nats://127.0.0.1:4222` | NATS server for local mode |
### Station Config
```yaml theme={null}
storage:
bucket: "sandbox-files" # Object Store bucket
max_file_size: 104857600 # 100 MB max file size
max_total_bytes: 10737418240 # 10 GB total storage
default_ttl: 0 # No expiration by default
```
## Troubleshooting
```
Error: failed to connect to NATS at nats://127.0.0.1:4222
```
**Fix:** Ensure NATS is running or set custom URL:
```bash theme={null}
export WORKFLOW_NATS_URL=nats://your-nats-server:4222
```
```
Error: file not found: files/f_abc123
```
**Fix:** Verify the file key:
```bash theme={null}
stn files list --prefix files/
```
```
Error: file exceeds maximum size of 100 MB
```
**Fix:** Increase `storage.max_file_size` in config or split the file.
## Next Steps
Learn about sandbox file staging tools
Build multi-step agent pipelines
# GitHub Actions
Source: https://docs.cloudshipai.com/station/github-actions
Run AI agents in CI/CD workflows using the Station GitHub Action
# GitHub Actions
Run Station AI agents directly in your GitHub workflows without installing Station locally. The [station-action](https://github.com/cloudshipai/station-action) supports three modes for loading agents.
## Quick Start
The easiest way to add a Station agent workflow to your repository is using the CLI:
```bash theme={null}
stn github init
```
This interactive command will:
1. Ask how you want to provide agents (CloudShip bundle ID or local environment)
2. Help you select an agent to run
3. Configure the workflow trigger (push, PR, schedule, manual)
4. Generate `.github/workflows/station-agent.yml`
5. Tell you which GitHub secrets to configure
**Example session:**
```
$ stn github init
🚀 Station GitHub Actions Setup
================================
How would you like to provide agents?
1. CloudShip Bundle ID (recommended - keeps repo clean)
2. Local environment (agents stored in repo)
Choice [1]: 1
Enter your CloudShip Bundle ID: 970fa728-4276-4443-9e51-35919b650d7a
Enter agent name to run: posthog-dashboard-reporter
When should this workflow run?
1. On push to main branch
2. On pull requests
3. On a schedule (e.g., daily)
4. Manual trigger only
Choice [4]: 4
✅ GitHub Actions workflow created!
📄 File: .github/workflows/station-agent.yml
🔐 Required GitHub Secrets:
OPENAI_API_KEY - Your OpenAI API key
CLOUDSHIP_API_KEY - Your CloudShip API key
Set secrets at: https://github.com///settings/secrets/actions
```
***
### Manual Setup
Alternatively, you can manually create the workflow. The simplest approach is using a CloudShip bundle ID:
```yaml theme={null}
name: Run AI Agent
on: [push]
jobs:
analyze:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: cloudshipai/station-action@main
with:
agent: 'posthog-dashboard-reporter'
task: 'List all my dashboards and summarize my analytics setup.'
bundle-id: '970fa728-4276-4443-9e51-35919b650d7a'
cloudship-api-key: ${{ secrets.CLOUDSHIP_API_KEY }}
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
POSTHOG_API_KEY: ${{ secrets.POSTHOG_API_KEY }}
```
## Agent Source Modes
Station action supports three ways to load agents:
Use a bundle published to CloudShip. This is the cleanest approach - no Station files need to be committed to your repository.
**Step 1: Publish your bundle to CloudShip**
From your local Station workspace:
```bash theme={null}
# Share an environment as a bundle
stn bundle share default
# Output:
# Bundle shared successfully!
# Bundle ID: 970fa728-4276-4443-9e51-35919b650d7a
```
**Step 2: Use the bundle ID in your workflow**
```yaml theme={null}
- uses: cloudshipai/station-action@main
with:
agent: 'my-agent'
task: 'Perform the task'
bundle-id: '970fa728-4276-4443-9e51-35919b650d7a'
cloudship-api-key: ${{ secrets.CLOUDSHIP_API_KEY }}
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
```
Get your CloudShip API key from [app.cloudshipai.com](https://app.cloudshipai.com) under Settings > API Keys.
Download a bundle from any URL (S3, GitHub Releases, etc.):
```yaml theme={null}
- uses: cloudshipai/station-action@main
with:
agent: 'my-agent'
task: 'Perform the task'
bundle-url: 'https://github.com/myorg/myrepo/releases/download/v1.0.0/bundle.tar.gz'
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
```
**Creating a bundle for URL distribution:**
```bash theme={null}
# Build a bundle locally
stn bundle build default -o ./my-bundle.tar.gz
# Upload to your release/storage
gh release upload v1.0.0 ./my-bundle.tar.gz
```
Use agents defined in your repository's `environments/` folder:
```yaml theme={null}
- uses: cloudshipai/station-action@main
with:
agent: 'my-agent'
task: 'Perform the task'
environment: 'default'
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
```
**Repository structure:**
```
your-repo/
├── environments/
│ └── default/
│ ├── agents/
│ │ └── my-agent.yaml
│ └── mcp/
│ └── my-tools.yaml
└── .github/
└── workflows/
└── agent.yml
```
This mode is useful when you want to version control your agents alongside your application code.
## Action Inputs
| Input | Description | Required | Default |
| ------------------- | ------------------------------------------------------- | -------- | ---------------- |
| `agent` | Agent name to run | Yes | - |
| `task` | Task description for the agent | Yes | - |
| `bundle-id` | CloudShip bundle ID | No\* | - |
| `bundle-url` | URL to download bundle from | No\* | - |
| `environment` | Local environment name | No\* | `default` |
| `cloudship-api-key` | CloudShip API key (for bundle-id mode) | No | - |
| `provider` | AI provider (`openai`, `anthropic`, `gemini`, `ollama`) | No | `openai` |
| `model` | Model override | No | Provider default |
| `base-url` | Custom API endpoint | No | - |
| `timeout` | Execution timeout in seconds | No | `300` |
| `max-steps` | Maximum agent steps | No | `50` |
\*At least one of `bundle-id`, `bundle-url`, or `environment` must be specified. If none are provided, the action looks for a local `environments/default` folder.
## AI Provider Configuration
```yaml theme={null}
- uses: cloudshipai/station-action@main
with:
agent: 'my-agent'
task: 'Analyze the codebase'
bundle-id: 'your-bundle-id'
cloudship-api-key: ${{ secrets.CLOUDSHIP_API_KEY }}
provider: 'openai'
model: 'gpt-4o'
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
```
```yaml theme={null}
- uses: cloudshipai/station-action@main
with:
agent: 'my-agent'
task: 'Analyze the codebase'
bundle-id: 'your-bundle-id'
cloudship-api-key: ${{ secrets.CLOUDSHIP_API_KEY }}
provider: 'anthropic'
model: 'claude-sonnet-4-20250514'
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
```
```yaml theme={null}
- uses: cloudshipai/station-action@main
with:
agent: 'my-agent'
task: 'Analyze the codebase'
bundle-id: 'your-bundle-id'
cloudship-api-key: ${{ secrets.CLOUDSHIP_API_KEY }}
provider: 'gemini'
model: 'gemini-2.0-flash-exp'
env:
GOOGLE_API_KEY: ${{ secrets.GOOGLE_API_KEY }}
```
## Complete Examples
### Analytics Reporter
Run a PostHog analytics agent to summarize your dashboards:
```yaml theme={null}
name: Weekly Analytics Report
on:
schedule:
- cron: '0 9 * * 1' # Monday 9 AM
workflow_dispatch:
jobs:
report:
runs-on: ubuntu-latest
steps:
- uses: cloudshipai/station-action@main
with:
agent: 'posthog-dashboard-reporter'
task: |
Generate a weekly analytics report:
1. List all dashboards
2. Summarize key metrics from each
3. Highlight any significant changes
bundle-id: '970fa728-4276-4443-9e51-35919b650d7a'
cloudship-api-key: ${{ secrets.CLOUDSHIP_API_KEY }}
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
POSTHOG_API_KEY: ${{ secrets.POSTHOG_API_KEY }}
```
### PR Code Review
Review pull requests automatically:
```yaml theme={null}
name: AI Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: cloudshipai/station-action@main
with:
agent: 'code-reviewer'
task: |
Review the changes in this PR. Focus on:
- Security vulnerabilities
- Performance issues
- Code quality and best practices
- Potential bugs
bundle-id: 'your-code-review-bundle-id'
cloudship-api-key: ${{ secrets.CLOUDSHIP_API_KEY }}
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
```
### Security Scan on Push
Scan for security issues on every push:
```yaml theme={null}
name: Security Scan
on:
push:
branches: [main]
jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: cloudshipai/station-action@main
with:
agent: 'security-scanner'
task: 'Scan the codebase for security vulnerabilities, exposed secrets, and dependency issues'
bundle-id: 'your-security-bundle-id'
cloudship-api-key: ${{ secrets.CLOUDSHIP_API_KEY }}
timeout: '600'
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
```
## Publishing Bundles to CloudShip
To use bundle-id mode, first publish your agents to CloudShip:
```bash theme={null}
# 1. Create agents in your local Station workspace
stn init
stn agent add --name "my-agent" --description "Does something useful"
# 2. Add MCP tools
stn mcp add --name "my-tools" --url "https://api.example.com/mcp"
# 3. Test locally
stn run "my-agent" --task "Test the agent"
# 4. Share to CloudShip
stn bundle share default
# Output shows your bundle ID:
# Bundle ID: abc123-def456-...
```
Store your bundle ID somewhere safe. You'll need it for the `bundle-id` input in your workflows.
## Build-Time Actions
Station also provides reusable actions for building bundles and Docker images.
### Build Bundle
Create distributable bundles from environments:
```yaml theme={null}
- uses: cloudshipai/station/.github/actions/build-bundle@main
id: bundle
with:
environment: 'production'
version: '1.0.0'
- run: echo "Bundle created at ${{ steps.bundle.outputs.bundle-path }}"
```
### Build Docker Image
Build and push Docker images:
```yaml theme={null}
- uses: cloudshipai/station/.github/actions/build-image@main
with:
source-type: 'environment'
environment: 'production'
image-name: 'my-org/station-production'
image-tag: 'latest'
push: 'true'
registry-username: ${{ github.actor }}
registry-password: ${{ secrets.GITHUB_TOKEN }}
```
### Setup Station CLI
Install Station CLI without running an agent:
```yaml theme={null}
- uses: cloudshipai/station/.github/actions/setup-station@main
with:
version: 'latest'
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
- run: stn --version
```
## Best Practices
Bundle-id mode keeps your repository clean - no Station configuration files to maintain. Agents are versioned separately in CloudShip.
Never hardcode API keys. Use GitHub secrets:
```yaml theme={null}
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
CLOUDSHIP_API_KEY: ${{ secrets.CLOUDSHIP_API_KEY }}
```
Complex tasks may need longer timeouts:
```yaml theme={null}
with:
timeout: '600' # 10 minutes
```
Add manual trigger for easy testing:
```yaml theme={null}
on:
workflow_dispatch:
push:
branches: [main]
```
## Troubleshooting
Ensure the agent name matches exactly (case-sensitive). List available agents:
```bash theme={null}
stn agent list
```
For bundle-id mode, verify:
* `cloudship-api-key` is set correctly
* Bundle ID is valid and not deleted
* Your CloudShip account has access to the bundle
Ensure required environment variables are passed:
```yaml theme={null}
env:
POSTHOG_API_KEY: ${{ secrets.POSTHOG_API_KEY }}
DATABASE_URL: ${{ secrets.DATABASE_URL }}
```
## Next Steps
* [Bundles](/station/bundles) - Learn more about packaging agents
* [GitOps Workflow](/station/gitops) - Version control your agents
* [Docker Deployment](/station/docker) - Container deployment options
# GitOps Workflow
Source: https://docs.cloudshipai.com/station/gitops
Version control your agents, MCP configs, and variables with Git
# GitOps Workflow
Station is designed for GitOps - version control your agent configurations, MCP templates, and variables just like infrastructure code.
## Why GitOps?
| Traditional | GitOps with Station |
| --------------------- | -------------------------- |
| Manual config changes | Version-controlled changes |
| No audit trail | Full Git history |
| Hard to rollback | Easy `git revert` |
| Single machine | Team collaboration |
| Config drift | Consistent state |
## Directory Structure
A typical Station GitOps repository:
```
my-station-config/
├── config.yaml # Station configuration
├── environments/
│ ├── production/
│ │ ├── agents/
│ │ │ ├── incident-coordinator.prompt
│ │ │ ├── logs-investigator.prompt
│ │ │ └── metrics-analyst.prompt
│ │ ├── template.json # MCP server configs
│ │ └── variables.yml # Secrets and config
│ │
│ ├── staging/
│ │ ├── agents/
│ │ ├── template.json
│ │ └── variables.yml
│ │
│ └── development/
│ ├── agents/
│ ├── template.json
│ └── variables.yml
│
└── reports/ # Generated performance reports
```
## Getting Started
### 1. Create a Git Repository
```bash theme={null}
mkdir my-station-config
cd my-station-config
git init
```
### 2. Initialize Station
```bash theme={null}
export STATION_WORKSPACE=$(pwd)
stn init --provider anthropic --ship
```
### 3. Commit Initial Configuration
```bash theme={null}
git add .
git commit -m "Initial Station configuration"
```
### 4. Push to Remote
```bash theme={null}
git remote add origin git@github.com:your-team/station-config.git
git push -u origin main
```
## Team Workflow
### Clone and Run
Team members can clone and run Station with your configuration:
```bash theme={null}
# Clone team repository
git clone git@github.com:your-team/station-config.git
cd station-config
# Run Station with this workspace
export STATION_WORKSPACE=$(pwd)
stn stdio
```
### Making Changes
1. **Create a branch:**
```bash theme={null}
git checkout -b add-cost-analyzer
```
2. **Make changes** (add agents, update configs)
3. **Test locally:**
```bash theme={null}
stn agent run cost-analyzer "Test task"
```
4. **Commit and push:**
```bash theme={null}
git add .
git commit -m "Add cost analyzer agent"
git push origin add-cost-analyzer
```
5. **Create Pull Request** for team review
### Code Review
Agent changes are reviewable like any code:
```diff theme={null}
# incident-coordinator.prompt
---
metadata:
name: "incident_coordinator"
+ description: "Enhanced incident response with severity classification"
model: gpt-4o-mini
-max_steps: 15
+max_steps: 20
agents:
- "logs_investigator"
- "metrics_investigator"
+ - "security_analyst"
---
```
## Configuration Files
### config.yaml
Global Station configuration:
```yaml theme={null}
# config.yaml
ai_provider: anthropic
ai_model: claude-sonnet-4-20250514
# Workspace can be set here or via STATION_WORKSPACE env var
workspace: /path/to/environments
# Optional: CloudShip integration
cloudship:
enabled: true
registration_key: "{{ .CLOUDSHIP_KEY }}"
name: "production-station"
```
### template.json
MCP server configurations with template variables:
```json theme={null}
{
"mcpServers": {
"aws": {
"command": "aws-mcp",
"env": {
"AWS_REGION": "{{ .AWS_REGION }}",
"AWS_PROFILE": "{{ .AWS_PROFILE }}"
}
},
"datadog": {
"command": "datadog-mcp",
"env": {
"DD_API_KEY": "{{ .DATADOG_API_KEY }}",
"DD_APP_KEY": "{{ .DATADOG_APP_KEY }}"
}
}
}
}
```
### variables.yml
Environment-specific values (keep secrets out of Git!):
```yaml theme={null}
# variables.yml - DO NOT COMMIT SECRETS
AWS_REGION: us-east-1
AWS_PROFILE: production
# DATADOG_API_KEY:
```
**Best practice:** Use environment variables for secrets:
```bash theme={null}
export DATADOG_API_KEY="your-secret-key"
export DATADOG_APP_KEY="your-app-key"
```
## Environment Management
### Multiple Environments
Station supports multiple environments for dev/staging/prod:
```
environments/
├── production/ # Production agents and configs
├── staging/ # Pre-production testing
└── development/ # Local development
```
### Switching Environments
```bash theme={null}
# Run with specific environment
stn --environment production agent run cost-analyzer "Analyze costs"
# Default environment
stn --environment development agent run cost-analyzer "Test analysis"
```
### Environment-Specific Configs
Each environment has its own:
* **agents/** - Agent definitions
* **template.json** - MCP server configs
* **variables.yml** - Environment-specific values
## CI/CD Integration
### GitHub Actions Example
```yaml theme={null}
# .github/workflows/validate.yml
name: Validate Station Config
on:
pull_request:
paths:
- 'environments/**'
- 'config.yaml'
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Station
run: |
curl -fsSL https://raw.githubusercontent.com/cloudshipai/station/main/install.sh | bash
- name: Validate Configuration
run: |
export STATION_WORKSPACE=$(pwd)
stn validate
- name: Lint Agent Prompts
run: |
stn agent lint --all
```
### Deploy on Merge
```yaml theme={null}
# .github/workflows/deploy.yml
name: Deploy Station
on:
push:
branches: [main]
paths:
- 'environments/production/**'
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Deploy to Fly.io
run: |
stn deploy station-prod --target fly
env:
FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
```
## Secrets Management
### Never Commit Secrets
Add to `.gitignore`:
```gitignore theme={null}
# Secrets
variables.yml
*.secret
.env
# But track the template
!variables.yml.example
```
### Use Environment Variables
```bash theme={null}
# Set secrets as environment variables
export OPENAI_API_KEY="sk-..."
export AWS_SECRET_ACCESS_KEY="..."
export DATADOG_API_KEY="..."
# Station resolves {{ .VAR }} from environment
stn serve
```
### Template for Team
Create a `variables.yml.example`:
```yaml theme={null}
# variables.yml.example - Copy to variables.yml and fill in values
AWS_REGION: us-east-1
AWS_PROFILE: "" # Your AWS profile name
# Set these as environment variables:
# OPENAI_API_KEY
# DATADOG_API_KEY
```
## Best Practices
1. **One repo per team/project** - Keep related agents together
2. **Use branches for changes** - Never commit directly to main
3. **Review agent changes** - Treat prompts like code
4. **Test before merging** - Run agents locally first
5. **Keep secrets out of Git** - Use environment variables
6. **Document your agents** - Use clear descriptions in metadata
7. **Version your prompts** - Git history shows evolution
## Rollback
### Revert a Change
```bash theme={null}
# Revert last commit
git revert HEAD
# Revert specific commit
git revert abc1234
# Push the revert
git push origin main
```
### Restore Previous Version
```bash theme={null}
# View history
git log --oneline environments/production/agents/
# Checkout specific version
git checkout abc1234 -- environments/production/agents/incident-coordinator.prompt
# Commit the restoration
git add .
git commit -m "Restore incident-coordinator to previous version"
```
## Next Steps
* [Bundles](/station/bundles/creating) - Package and share agents
* [Deployment](/station/deployment/production) - Deploy to production
* [CI/CD Integration](/station/ci-cd-integration) - Automated pipelines
# Installation
Source: https://docs.cloudshipai.com/station/installation
Install Station CLI on your system
## Quick Install
The fastest way to install Station is using our install script:
```bash theme={null}
curl -fsSL https://raw.githubusercontent.com/cloudshipai/station/main/install.sh | bash
```
This script:
1. Detects your platform (Linux/macOS/Windows) and architecture (amd64/arm64)
2. Downloads the latest release from GitHub
3. Installs the `stn` binary to `~/.local/bin/` or `/usr/local/bin/`
4. Adds the binary to your PATH if needed
## Manual Installation
### From GitHub Releases
Download the appropriate binary for your platform from [GitHub Releases](https://github.com/cloudshipai/station/releases):
```bash theme={null}
# Download
curl -LO https://github.com/cloudshipai/station/releases/latest/download/station_darwin_arm64.tar.gz
# Extract
tar -xzf station_darwin_arm64.tar.gz
# Install
mv stn ~/.local/bin/
chmod +x ~/.local/bin/stn
```
```bash theme={null}
# Download
curl -LO https://github.com/cloudshipai/station/releases/latest/download/station_darwin_amd64.tar.gz
# Extract
tar -xzf station_darwin_amd64.tar.gz
# Install
mv stn ~/.local/bin/
chmod +x ~/.local/bin/stn
```
```bash theme={null}
# Download
curl -LO https://github.com/cloudshipai/station/releases/latest/download/station_linux_amd64.tar.gz
# Extract
tar -xzf station_linux_amd64.tar.gz
# Install
mv stn ~/.local/bin/
chmod +x ~/.local/bin/stn
```
```bash theme={null}
# Download
curl -LO https://github.com/cloudshipai/station/releases/latest/download/station_linux_arm64.tar.gz
# Extract
tar -xzf station_linux_arm64.tar.gz
# Install
mv stn ~/.local/bin/
chmod +x ~/.local/bin/stn
```
### From Source
Build Station from source using Go 1.21+:
```bash theme={null}
# Clone the repository
git clone https://github.com/cloudshipai/station.git
cd station
# Build with UI embedded
make build-with-ui
# Install to PATH
mv bin/stn ~/.local/bin/
```
## Verify Installation
Check that Station is installed correctly:
```bash theme={null}
stn --version
```
You should see output like:
```
stn version v0.1.0
```
## PATH Configuration
If `stn` is not found after installation, add `~/.local/bin` to your PATH:
```bash theme={null}
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
```
```bash theme={null}
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc
```
```bash theme={null}
fish_add_path ~/.local/bin
```
## System Requirements
| Requirement | Minimum | Recommended |
| ---------------- | --------------------------- | --------------------- |
| **OS** | Linux, macOS, Windows (WSL) | Linux, macOS |
| **Architecture** | x64, ARM64 | ARM64 (Apple Silicon) |
| **RAM** | 512MB | 2GB |
| **Disk** | 100MB | 500MB |
| **Docker** | Optional | Required for `stn up` |
## Upgrading
To upgrade to the latest version:
```bash theme={null}
# Re-run the install script
curl -fsSL https://raw.githubusercontent.com/cloudshipai/station/main/install.sh | bash
# Or if using stn up
stn up --upgrade
```
## Uninstalling
To remove Station:
```bash theme={null}
# Remove binary
rm ~/.local/bin/stn
# Remove configuration (optional)
rm -rf ~/.config/station/
```
## Next Steps
Configure Station with your AI provider
# Lattice Architecture
Source: https://docs.cloudshipai.com/station/lattice-architecture
Technical deep-dive into Station Lattice internals
# Lattice Architecture
This document provides a technical deep-dive into Station Lattice's architecture, including message flows, NATS subjects, and internal components.
## System Components
```
┌────────────────────────────────────────────────────────────────────────┐
│ ORCHESTRATOR STATION │
├────────────────────────────────────────────────────────────────────────┤
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Registry │ │ Presence │ │ Work Store │ │
│ │ (JetStream) │ │ Manager │ │ (JetStream) │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │ │ │ │
│ └────────────────┼─────────────────┘ │
│ │ │
│ ┌────────────────┐ │
│ │ Embedded NATS │ │
│ │ + JetStream │ │
│ └────────────────┘ │
│ │ │
└───────────────────────────┼────────────────────────────────────────────┘
│
┌───────────────────┼───────────────────┐
│ │ │
▼ ▼ ▼
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ MEMBER STATION│ │ MEMBER STATION│ │ MEMBER STATION│
├───────────────┤ ├───────────────┤ ├───────────────┤
│ ┌───────────┐ │ │ ┌───────────┐ │ │ ┌───────────┐ │
│ │ Client │ │ │ │ Client │ │ │ │ Client │ │
│ └───────────┘ │ │ └───────────┘ │ │ └───────────┘ │
│ ┌───────────┐ │ │ ┌───────────┐ │ │ ┌───────────┐ │
│ │ Presence │ │ │ │ Presence │ │ │ │ Presence │ │
│ └───────────┘ │ │ └───────────┘ │ │ └───────────┘ │
│ ┌───────────┐ │ │ ┌───────────┐ │ │ ┌───────────┐ │
│ │ Executor │ │ │ │ Executor │ │ │ │ Executor │ │
│ │ Adapter │ │ │ │ Adapter │ │ │ │ Adapter │ │
│ └───────────┘ │ │ └───────────┘ │ │ └───────────┘ │
│ ┌───────────┐ │ │ ┌───────────┐ │ │ ┌───────────┐ │
│ │ Router │ │ │ │ Router │ │ │ │ Router │ │
│ └───────────┘ │ │ └───────────┘ │ │ └───────────┘ │
└───────────────┘ └───────────────┘ └───────────────┘
```
## Core Components
### Client (`internal/lattice/client.go`)
The NATS connection wrapper that handles:
* Connection lifecycle management
* Automatic reconnection with backoff
* TLS and NKey authentication
* Subscription management
```go theme={null}
type Client struct {
nc *nats.Conn
js nats.JetStreamContext
config *Config
stationID string
}
```
### Registry (`internal/lattice/registry.go`)
JetStream KV-backed registry for stations and agents:
| Bucket | Key Pattern | Value |
| ---------- | --------------------------- | --------------------- |
| `stations` | `{station_id}` | Station metadata JSON |
| `agents` | `{station_id}.{agent_name}` | Agent metadata JSON |
```go theme={null}
type Registry struct {
stationsBucket nats.KeyValue
agentsBucket nats.KeyValue
}
// Station metadata
type StationInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Status StationStatus `json:"status"`
Metadata map[string]string `json:"metadata"`
LastSeen time.Time `json:"last_seen"`
Version string `json:"version"`
}
// Agent metadata
type AgentInfo struct {
Name string `json:"name"`
StationID string `json:"station_id"`
Description string `json:"description"`
Capabilities []string `json:"capabilities"`
Tags map[string]string `json:"tags"`
Status AgentStatus `json:"status"`
}
```
### Presence (`internal/lattice/presence.go`)
Heartbeat system for station health monitoring:
```go theme={null}
type PresenceManager struct {
client *Client
registry *Registry
interval time.Duration
timeout time.Duration
}
// Heartbeat message
type Heartbeat struct {
StationID string `json:"station_id"`
Timestamp time.Time `json:"timestamp"`
AgentCount int `json:"agent_count"`
Load float64 `json:"load"`
}
```
### Router (`internal/lattice/router.go`)
Capability-based agent routing:
```go theme={null}
type Router struct {
registry *Registry
}
// Route request to best matching agent
func (r *Router) Route(capability string) (*AgentInfo, error)
// Route with preferences
func (r *Router) RouteWithPrefs(capability string, prefs RoutePrefs) (*AgentInfo, error)
type RoutePrefs struct {
PreferredStation string
RequiredTags map[string]string
ExcludeStations []string
}
```
### Invoker (`internal/lattice/invoker.go`)
Remote agent invocation via request-reply:
```go theme={null}
type Invoker struct {
client *Client
router *Router
}
// Invoke agent synchronously
func (i *Invoker) Invoke(ctx context.Context, req *InvokeRequest) (*InvokeResponse, error)
// Invoke agent asynchronously (returns work ID)
func (i *Invoker) InvokeAsync(ctx context.Context, req *InvokeRequest) (string, error)
```
### Work Store (`internal/lattice/work/store.go`)
JetStream-backed async work tracking:
```go theme={null}
type WorkStore struct {
js nats.JetStreamContext
stream string
kv nats.KeyValue
}
type WorkItem struct {
ID string `json:"id"`
AgentName string `json:"agent_name"`
StationID string `json:"station_id"`
Task string `json:"task"`
Status WorkStatus `json:"status"`
Progress int `json:"progress"`
Result string `json:"result"`
Error string `json:"error"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type WorkStatus string
const (
WorkStatusPending WorkStatus = "pending"
WorkStatusRunning WorkStatus = "running"
WorkStatusCompleted WorkStatus = "completed"
WorkStatusFailed WorkStatus = "failed"
WorkStatusCancelled WorkStatus = "cancelled"
)
```
## NATS Subject Conventions
### Core Subjects
| Subject | Type | Purpose |
| -------------------------------- | ---- | ---------------------- |
| `lattice.station.{id}.heartbeat` | Pub | Station heartbeat |
| `lattice.station.{id}.status` | Pub | Station status changes |
| `lattice.agent.register` | Pub | Agent registration |
| `lattice.agent.deregister` | Pub | Agent deregistration |
### Request-Reply Subjects
| Subject | Purpose |
| ---------------------------------- | --------------------------- |
| `lattice.invoke.{station}.{agent}` | Direct agent invocation |
| `lattice.invoke.capability.{cap}` | Capability-based invocation |
### Work Queue Subjects
| Subject | Purpose |
| ------------------------------- | -------------------------- |
| `lattice.work.assign.{station}` | Work assignment to station |
| `lattice.work.{id}.status` | Work status updates |
| `lattice.work.{id}.result` | Work completion result |
| `lattice.work.{id}.cancel` | Work cancellation request |
## Message Flows
### Station Registration
```
┌──────────┐ ┌──────────────┐ ┌──────────┐
│ Member │ │ NATS │ │ Orch. │
└────┬─────┘ └──────┬───────┘ └────┬─────┘
│ │ │
│ 1. Connect │ │
│────────────────────────────────>│ │
│ │ │
│ 2. Publish station info │ │
│ lattice.station.{id}.register │ │
│────────────────────────────────>│ ──────────────────────────────> │
│ │ │
│ │ 3. Store in KV │
│ │ <────────────────────────────── │
│ │ │
│ 4. Start heartbeat loop │ │
│ lattice.station.{id}.heartbeat│ │
│────────────────────────────────>│ ──────────────────────────────> │
│ │ │
│ 5. Register agents │ │
│ lattice.agent.register │ │
│────────────────────────────────>│ ──────────────────────────────> │
│ │ │
```
### Synchronous Invocation
```
┌──────────┐ ┌──────────┐ ┌──────────────┐ ┌──────────┐
│ Invoker │ │ Router │ │ NATS │ │ Target │
└────┬─────┘ └────┬─────┘ └──────┬───────┘ └────┬─────┘
│ │ │ │
│ 1. Invoke(cap) │ │ │
│───────────────>│ │ │
│ │ │ │
│ 2. Route │ │ │
│<───────────────│ │ │
│ (agent,station) │ │
│ │ │ │
│ 3. Request │ │
│ lattice.invoke.{station}.{agent}│ │
│──────────────────────────────────>│ │
│ │ 4. Deliver │
│ │─────────────────>│
│ │ │
│ │ 5. Execute agent │
│ │ │
│ │ 6. Reply │
│ │<─────────────────│
│ 7. Response │ │
│<──────────────────────────────────│ │
│ │ │
```
### Async Work Assignment
```
┌──────────┐ ┌───────────┐ ┌──────────────┐ ┌──────────┐
│ Invoker │ │WorkStore │ │ NATS │ │ Target │
└────┬─────┘ └─────┬─────┘ └──────┬───────┘ └────┬─────┘
│ │ │ │
│ 1. InvokeAsync │ │ │
│────────────────>│ │ │
│ │ │ │
│ 2. Create work │ │ │
│ item in KV │ │ │
│<────────────────│ │ │
│ (work_id) │ │ │
│ │ │ │
│ │ 3. Publish │ │
│ │ lattice.work.assign.{station} │
│ │─────────────────>│ │
│ │ │ 4. Deliver │
│ │ │─────────────────>│
│ │ │ │
│ │ │ 5. Execute │
│ │ │ (async) │
│ │ │ │
│ │ │ 6. Status update │
│ │ │ lattice.work.{id}.status
│ │ │<─────────────────│
│ │ 7. Update KV │ │
│ │<─────────────────│ │
│ │ │ │
│ │ │ 8. Result │
│ │ │ lattice.work.{id}.result
│ │ │<─────────────────│
│ │ 9. Store result │ │
│ │<─────────────────│ │
│ │ │ │
```
## State Machines
### Station Lifecycle
```
┌─────────────┐
│ Disconnected│
└──────┬──────┘
│ connect()
▼
┌─────────────┐
┌────>│ Connecting │
│ └──────┬──────┘
│ │ connected
│ ▼
│ ┌─────────────┐
│ │ Registering│
│ └──────┬──────┘
│ │ registered
│ ▼
│ ┌─────────────┐
│ │ Online │<────────┐
│ └──────┬──────┘ │
│ │ │
│ ┌───────┴───────┐ │
│ │ │ │
│ ▼ ▼ │
│ timeout reconnected │
│ │ │ │
│ ▼ └────────┘
│ ┌─────────────┐
│ │ Stale │
│ └──────┬──────┘
│ │ timeout
│ ▼
│ ┌─────────────┐
└─│ Offline │
└─────────────┘
```
### Work Item Lifecycle
```
┌─────────────┐
│ Pending │
└──────┬──────┘
│
┌────────────┼────────────┐
│ │ │
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Cancelled│ │ Running │ │ Failed │
└──────────┘ └────┬─────┘ └──────────┘
│
┌──────────┼──────────┐
│ │ │
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│Completed │ │ Failed │ │ Cancelled│
└──────────┘ └──────────┘ └──────────┘
```
## JetStream Configuration
### Streams
```go theme={null}
// Work stream configuration
&nats.StreamConfig{
Name: "LATTICE_WORK",
Subjects: []string{"lattice.work.>"},
Retention: nats.WorkQueuePolicy,
MaxAge: 24 * time.Hour,
MaxMsgs: 100000,
MaxBytes: 1 << 30, // 1GB
Replicas: 1, // Increase for HA
Storage: nats.FileStorage,
}
```
### KV Buckets
```go theme={null}
// Stations bucket
&nats.KeyValueConfig{
Bucket: "LATTICE_STATIONS",
TTL: 30 * time.Second, // Auto-expire stale stations
MaxBytes: 100 << 20, // 100MB
Replicas: 1,
}
// Agents bucket
&nats.KeyValueConfig{
Bucket: "LATTICE_AGENTS",
MaxBytes: 100 << 20,
Replicas: 1,
}
// Work items bucket
&nats.KeyValueConfig{
Bucket: "LATTICE_WORK_ITEMS",
TTL: 24 * time.Hour,
MaxBytes: 500 << 20, // 500MB
Replicas: 1,
}
```
## Error Handling
### Retry Policies
| Operation | Max Retries | Backoff |
| --------------- | ------------------ | -------------------- |
| NATS connect | Infinite | Exponential (1s-30s) |
| KV operations | 3 | Linear (100ms) |
| Invocations | 0 (caller decides) | N/A |
| Work assignment | 3 | Exponential (1s-10s) |
### Error Types
```go theme={null}
var (
ErrNotConnected = errors.New("not connected to lattice")
ErrStationNotFound = errors.New("station not found")
ErrAgentNotFound = errors.New("agent not found")
ErrAgentBusy = errors.New("agent is busy")
ErrInvocationTimeout = errors.New("invocation timed out")
ErrWorkNotFound = errors.New("work item not found")
ErrWorkCancelled = errors.New("work was cancelled")
)
```
## Performance Considerations
### Scaling Limits
| Component | Soft Limit | Hard Limit |
| ---------------------- | ---------- | ---------- |
| Stations per mesh | 100 | 1000 |
| Agents per station | 50 | 500 |
| Concurrent invocations | 1000 | 10000 |
| Work items (pending) | 10000 | 100000 |
| Message size | 1MB | 8MB |
### Optimization Tips
1. **Use capability routing** instead of direct station targeting when possible
2. **Batch heartbeats** if running many stations on same host
3. **Set appropriate timeouts** - don't use default 60s for fast operations
4. **Monitor JetStream storage** - purge old work items regularly
5. **Use async invocation** for long-running tasks (>5s)
# Lattice CLI Reference
Source: https://docs.cloudshipai.com/station/lattice-cli
Complete CLI reference for Station Lattice commands
# Lattice CLI Reference
Complete reference for all `stn lattice` commands.
## Overview
The `stn lattice` command group provides tools for managing and interacting with Station Lattice mesh networks.
```bash theme={null}
stn lattice [command] [flags]
```
## CLI Client Mode
You can interact with a running lattice from the CLI without starting a server using the `--nats` flag:
```bash theme={null}
# Connect to a lattice from CLI
stn lattice --nats nats://localhost:4222 status
stn lattice --nats nats://localhost:4222 agents
# With authentication token
stn lattice --nats "nats://my-token@orchestrator.example.com:4222" agents
# Execute an agent remotely
stn lattice --nats "nats://token@host:4222" agent exec my-agent "Task description"
```
This is useful for:
* Querying lattice status from scripts
* Executing agents from CI/CD pipelines
* Debugging without running a full station
## Commands
### `stn lattice status`
Display the current lattice connection status.
```bash theme={null}
stn lattice status [flags]
```
**Flags:**
| Flag | Description | Default |
| ------------ | ------------------------- | ------- |
| `--json` | Output in JSON format | `false` |
| `--watch` | Continuously watch status | `false` |
| `--interval` | Watch refresh interval | `2s` |
**Examples:**
```bash theme={null}
# Basic status
stn lattice status
# Output:
# Lattice Status: Connected
# Mode: member
# Station ID: sre-station-prod
# Orchestrator: nats://orchestrator.example.com:4222
# Connected Since: 2024-01-15 10:30:00 UTC
# Heartbeat: OK (last: 2s ago)
# Registered Agents: 5
# JSON output
stn lattice status --json
# Watch mode
stn lattice status --watch --interval 5s
```
***
### `stn lattice stations`
Manage stations in the lattice mesh.
#### `stn lattice stations list`
List all stations connected to the mesh.
```bash theme={null}
stn lattice stations list [flags]
```
**Flags:**
| Flag | Description | Default |
| -------- | ------------------------ | ------- |
| `--json` | Output in JSON format | `false` |
| `--all` | Include offline stations | `false` |
**Examples:**
```bash theme={null}
# List online stations
stn lattice stations list
# Output:
# STATION ID NAME STATUS AGENTS LAST SEEN
# orchestrator-main Main Orchestrator online 3 now
# sre-station-prod SRE Production online 5 2s ago
# security-station Security Scanner online 2 1s ago
# devops-ci DevOps CI/CD offline 4 5m ago
# Include offline stations
stn lattice stations list --all
# JSON output
stn lattice stations list --json
```
#### `stn lattice stations info`
Get detailed information about a specific station.
```bash theme={null}
stn lattice stations info [flags]
```
**Examples:**
```bash theme={null}
stn lattice stations info sre-station-prod
# Output:
# Station: sre-station-prod
# Name: SRE Production
# Status: online
# Connected Since: 2024-01-15 10:30:00 UTC
# Last Heartbeat: 2s ago
#
# Agents (5):
# - k8s-health-checker (capabilities: kubernetes, health-check)
# - log-analyzer (capabilities: logs, analysis)
# - incident-responder (capabilities: incidents, pagerduty)
# - metrics-collector (capabilities: prometheus, metrics)
# - alert-manager (capabilities: alerts, notifications)
#
# Metadata:
# environment: production
# region: us-east-1
# version: 1.2.3
```
***
### `stn lattice agents`
List all agents available in the mesh.
```bash theme={null}
stn lattice agents [flags]
```
**Flags:**
| Flag | Description | Default |
| -------------- | ------------------------------------- | ------- |
| `--discover` | Show detailed agent info with schema | `false` |
| `--capability` | Filter agents by capability | - |
| `--schema` | Show full schema for a specific agent | - |
**Examples:**
```bash theme={null}
# List all agents
stn lattice agents
# Output:
# Agents in Lattice (5 total)
# ============================================
# AGENT STATION LOCAL
# --------------------------------------------
# k8s-health-checker sre-station-prod
# log-analyzer sre-station-prod
# vuln-scanner security-station
# threat-analyzer security-station
# ci-runner devops-ci
# With CLI client mode
stn lattice --nats nats://host:4222 agents
# Filter by capability
stn lattice agents --capability kubernetes
# Show detailed info
stn lattice agents --discover
# Show full schema for an agent
stn lattice agents --schema k8s-health-checker
```
#### `stn lattice agents info`
Get detailed information about a specific agent.
```bash theme={null}
stn lattice agents info [flags]
```
**Flags:**
| Flag | Description | Default |
| ----------- | ------------------------------------------ | ------- |
| `--station` | Specify station if agent name is ambiguous | - |
**Examples:**
```bash theme={null}
stn lattice agents info k8s-health-checker
# Output:
# Agent: k8s-health-checker
# Station: sre-station-prod
# Status: available
#
# Description:
# Checks Kubernetes cluster health and reports issues
#
# Capabilities:
# - kubernetes
# - health-check
# - monitoring
#
# Tags:
# environment: production
# cluster: prod-east-1
#
# Recent Invocations:
# 2024-01-15 10:45:00 - success (1.2s)
# 2024-01-15 10:30:00 - success (0.8s)
# 2024-01-15 10:15:00 - success (1.1s)
```
***
### `stn lattice agent exec`
Execute an agent on a remote station.
```bash theme={null}
stn lattice agent exec [flags]
```
**Flags:**
| Flag | Description | Default |
| ----------- | ----------------------- | ---------- |
| `--station` | Target specific station | auto-route |
**Examples:**
```bash theme={null}
# Simple execution
stn lattice agent exec k8s-health-checker "Check pod health in production"
# Output:
# [routing to sre-station-prod]
#
# All 42 pods healthy in namespace production
# - web-frontend: 3/3 replicas ready
# - api-backend: 5/5 replicas ready
# - worker: 2/2 replicas ready
#
# Execution completed in 1.23s (via abc123-def456)
# With CLI client mode (no server required)
stn lattice --nats "nats://token@host:4222" agent exec echo-agent "Hello!"
# Target specific station
stn lattice agent exec log-analyzer "Analyze errors" --station sre-station-staging
# From a script
NATS_URL="nats://token@orchestrator:4222"
stn lattice --nats "$NATS_URL" agent exec math-agent "Calculate 25 * 17"
```
***
### `stn lattice route`
Find agents by capability (for debugging routing).
```bash theme={null}
stn lattice route [flags]
```
**Flags:**
| Flag | Description | Default |
| -------- | --------------------- | ------- |
| `--json` | Output in JSON format | `false` |
| `--all` | Show all matches | `false` |
**Examples:**
```bash theme={null}
# Find agents with kubernetes capability
stn lattice route kubernetes
# Output:
# Best match: k8s-health-checker (sre-station-prod)
#
# All matches:
# 1. k8s-health-checker (sre-station-prod) - score: 0.95
# 2. k8s-deployer (devops-ci) - score: 0.82
# 3. k8s-monitor (monitoring-station) - score: 0.78
# Show all matches
stn lattice route security --all
```
***
### `stn lattice work`
Manage async work items. Async work allows you to submit long-running tasks that execute in the background.
#### `stn lattice work assign`
Assign work to an agent asynchronously.
```bash theme={null}
stn lattice work assign [flags]
```
**Flags:**
| Flag | Description | Default |
| ----------- | -------------------------- | ---------- |
| `--station` | Assign to specific station | auto-route |
| `--timeout` | Work timeout | `5m` |
**Examples:**
```bash theme={null}
# Assign work
stn lattice work assign vuln-scanner "Full security scan"
# Output:
# Work assigned: work_abc123
# Agent: vuln-scanner
#
# Use 'stn lattice work await work_abc123' to wait for results
# With timeout
stn lattice work assign log-analyzer "Analyze last 24h logs" --timeout 30m
```
#### `stn lattice work await`
Wait for work to complete and return the result.
```bash theme={null}
stn lattice work await [flags]
```
**Examples:**
```bash theme={null}
stn lattice work await work_abc123
# Output:
# Waiting for work work_abc123...
#
# Status: completed
# Result: Scan complete. Found 3 vulnerabilities...
# Station: security-station
# Duration: 45.23s
```
#### `stn lattice work check`
Check work status without blocking.
```bash theme={null}
stn lattice work check [flags]
```
**Examples:**
```bash theme={null}
stn lattice work check work_abc123
# Output:
# Work ID: work_abc123
# Status: running
```
***
### `stn lattice dashboard`
Launch the interactive TUI dashboard.
```bash theme={null}
stn lattice dashboard [flags]
```
**Flags:**
| Flag | Description | Default |
| ----------- | -------------------------- | ------- |
| `--refresh` | Dashboard refresh interval | `2s` |
**Examples:**
```bash theme={null}
# Launch dashboard
stn lattice dashboard
# The dashboard shows:
# - Connected stations with health status
# - Available agents across the mesh
# - Active work items with progress
# - Recent invocations and their results
```
***
## Global Flags
These flags apply to all `stn lattice` commands:
| Flag | Description | Default |
| -------------------- | ----------------------------------------------------------------- | ------------------------------- |
| `--nats` | **NATS URL for CLI client mode** (e.g., `nats://token@host:4222`) | - |
| `--config` | Config file path | `~/.config/station/config.yaml` |
| `--enable-telemetry` | Enable OpenTelemetry tracing | `false` |
| `--otel-endpoint` | OpenTelemetry OTLP endpoint | `http://localhost:4318` |
The `--nats` flag enables CLI client mode, allowing you to interact with a lattice without running a station server.
Authentication tokens can be included in the URL: `nats://my-token@host:4222`
## Environment Variables
| Variable | Description |
| -------------------------- | -------------------------------------------------- |
| `NATS_AUTH_TOKEN` | Authentication token for NATS (can be used in URL) |
| `STN_LATTICE_STATION_NAME` | Station name in the mesh |
| `STN_LATTICE_TLS_CERT` | TLS certificate path |
| `STN_LATTICE_TLS_KEY` | TLS key path |
## Exit Codes
| Code | Meaning |
| ---- | ------------------- |
| `0` | Success |
| `1` | General error |
| `2` | Connection failed |
| `3` | Agent not found |
| `4` | Invocation timeout |
| `5` | Work item not found |
# Lattice Labs
Source: https://docs.cloudshipai.com/station/lattice-labs
Hands-on tutorials for Station Lattice
# Lattice Labs
Hands-on tutorials to learn Station Lattice step by step.
All lab materials are available in the Station repository under `examples/lattice-lab/`.
## Lab Overview
| Lab | Description | Duration |
| ------------------------------------------ | ------------------------------- | -------- |
| [Lab 1](#lab-1-local-docker-setup) | Local Docker setup with NATS | 10 min |
| [Lab 2](#lab-2-embedded-nats-orchestrator) | Embedded NATS orchestrator mode | 10 min |
| [Lab 3](#lab-3-multi-station-mesh) | Multi-station mesh network | 15 min |
| [Lab 4](#lab-4-authentication) | NATS authentication | 10 min |
| [Lab 5](#lab-5-async-work-queue) | Async work assignment | 10 min |
***
## Lab 1: Local Docker Setup
Start a NATS server with Docker and connect a station.
### Prerequisites
* Docker installed
* Station CLI (`stn`)
### Steps
```bash theme={null}
# 1. Start NATS with JetStream
docker run -d --name nats-lattice \
-p 4222:4222 -p 8222:8222 \
nats:latest -js
# 2. Verify NATS is running
curl http://localhost:8222/varz | jq '.server_name'
# 3. Start station with lattice
stn serve --lattice nats://localhost:4222 --workspace ./my-workspace
# 4. In another terminal, check status
stn lattice status
```
### Expected Output
```
Lattice Status: MEMBER
Orchestrator: nats://localhost:4222
Connection: Connected
Station ID: abc123-def456
Station Name: my-laptop
```
### Cleanup
```bash theme={null}
docker stop nats-lattice && docker rm nats-lattice
```
***
## Lab 2: Embedded NATS Orchestrator
Run a station as the orchestrator with embedded NATS.
### Steps
```bash theme={null}
# 1. Start orchestrator station
stn serve --orchestration --workspace ./orchestrator
# The orchestrator will:
# - Start embedded NATS on port 4222
# - Enable JetStream for persistence
# - Accept member connections
# 2. Verify embedded NATS
curl http://localhost:8222/varz | jq '.server_name'
# 3. Check lattice status
stn lattice status
# Expected output:
# Lattice Status: ORCHESTRATOR
# NATS URL: nats://0.0.0.0:4222
# Monitoring: http://0.0.0.0:8222
```
### Connect a Member
In another terminal:
```bash theme={null}
# Start a member station
stn serve --lattice nats://localhost:4222 --workspace ./member
# Check connected stations
stn lattice status
```
***
## Lab 3: Multi-Station Mesh
Create a mesh with multiple specialized stations.
### Architecture
```
┌──────────────────┐
│ Orchestrator │
│ (embedded NATS)│
└────────┬─────────┘
│
┌────────────────┼────────────────┐
│ │ │
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ SRE │ │ Security │ │ DevOps │
│ Station │ │ Station │ │ Station │
└──────────┘ └──────────┘ └──────────┘
```
### Steps
```bash theme={null}
# Terminal 1: Orchestrator
stn serve --orchestration --workspace ./orchestrator
# Terminal 2: SRE Station
stn serve --lattice nats://localhost:4222 --workspace ./sre-station
# Terminal 3: Security Station
stn serve --lattice nats://localhost:4222 --workspace ./security-station
# Terminal 4: DevOps Station
stn serve --lattice nats://localhost:4222 --workspace ./devops-station
```
### Verify Mesh
```bash theme={null}
# List all stations
stn lattice status
# List all agents across the mesh
stn lattice agents
# Execute agent on remote station
stn lattice agent exec k8s-health "Check pod status"
```
***
## Lab 4: Authentication
Secure your lattice with token authentication.
### Option 1: Token in NATS URL
```bash theme={null}
# Start NATS with auth token
docker run -d --name nats-auth \
-p 4222:4222 -p 8222:8222 \
nats:latest -js --auth my-secret-token
# Connect with token in URL
stn serve --lattice "nats://my-secret-token@localhost:4222" --workspace ./station
```
### Option 2: Embedded Orchestrator with Auth
```yaml theme={null}
# config.yaml
lattice:
orchestrator:
embedded_nats:
port: 4222
auth_token: my-secret-token
```
```bash theme={null}
# Start orchestrator
stn serve --orchestration --config config.yaml
# Members must include token
stn serve --lattice "nats://my-secret-token@orchestrator:4222"
```
### CLI Client with Auth
```bash theme={null}
# Query lattice with auth token
stn lattice --nats "nats://my-secret-token@localhost:4222" agents
# Execute agent
stn lattice --nats "nats://my-secret-token@localhost:4222" \
agent exec echo-agent "Hello!"
```
***
## Lab 5: Async Work Queue
Assign long-running tasks with progress tracking.
### Steps
```bash theme={null}
# 1. Start lattice (orchestrator mode for JetStream)
stn serve --orchestration --workspace ./station
# 2. Assign work asynchronously
stn lattice work assign log-analyzer "Analyze last 7 days of logs" --timeout 30m
# Output:
# Work assigned: work_abc123
# Agent: log-analyzer
#
# Use 'stn lattice work await work_abc123' to wait for results
# 3. Check status (non-blocking)
stn lattice work check work_abc123
# 4. Wait for completion
stn lattice work await work_abc123
```
### Real-Time Dashboard
```bash theme={null}
# Launch TUI dashboard
stn lattice dashboard
# Shows:
# - Active work items
# - Progress updates
# - Completed tasks
```
***
## Lab Agents
The `examples/lattice-lab/agents/` directory contains pre-built agents for testing:
| Agent | Purpose | Example Task |
| --------------- | -------------------- | ------------------------------- |
| `echo-agent` | Connectivity testing | `"Hello World"` |
| `math-agent` | Calculations | `"Calculate 25 * 17"` |
| `joke-agent` | Entertainment | `"Tell me a programming joke"` |
| `time-agent` | Time queries | `"What time is it?"` |
| `sysinfo-agent` | Status info | `"What is the station status?"` |
### Using Lab Agents
```bash theme={null}
# Copy agents to your workspace
mkdir -p ~/station/environments/default/agents
cp examples/lattice-lab/agents/*.prompt ~/station/environments/default/agents/
# Start station
stn serve --lattice nats://localhost:4222 --workspace ~/station
# Test agents
stn lattice agent exec echo-agent "Hello from the lab!"
stn lattice agent exec math-agent "What is 15 factorial?"
```
***
## E2E Local Test
Run a complete local test with Docker:
```bash theme={null}
cd examples/lattice-lab/e2e-local
# 1. Start NATS
docker compose up -d
# 2. Create .env from template
cp .env.example .env
# Edit .env with your OPENAI_API_KEY
# 3. Set up workspace
source .env
mkdir -p /tmp/e2e-lab/environments/default/agents
cp ../agents/*.prompt /tmp/e2e-lab/environments/default/agents/
# 4. Create config
cat > /tmp/e2e-config.yaml << EOF
workspace: /tmp/e2e-lab
ai_provider: openai
ai_model: gpt-4o-mini
encryption_key: "$(openssl rand -base64 32)"
lattice:
station_name: e2e-station
nats:
url: "nats://${NATS_AUTH_TOKEN}@localhost:14222"
EOF
# 5. Start station
export OPENAI_API_KEY=your-key
stn serve --config /tmp/e2e-config.yaml
# 6. Test (in another terminal)
source .env
stn lattice --nats "nats://${NATS_AUTH_TOKEN}@localhost:14222" agents
stn lattice --nats "nats://${NATS_AUTH_TOKEN}@localhost:14222" agent exec echo-agent "Hello E2E!"
# 7. Cleanup
docker compose down
```
***
## Troubleshooting
### "No responders available"
This usually means the target station isn't subscribed. Check:
```bash theme={null}
# Verify station is connected
curl http://localhost:8222/connz?subs=1 | jq '.connections[].subscriptions_list'
# Should see subscriptions like:
# lattice.station.{uuid}.agent.invoke
```
### Stale station registrations
If a station was restarted, old entries may remain:
```bash theme={null}
# List stations in registry
nats --server nats://localhost:4222 kv ls lattice-stations
# Delete stale entry
nats --server nats://localhost:4222 kv rm lattice-stations {old-uuid} -f
```
### Connection refused
```bash theme={null}
# Check NATS is running
docker ps | grep nats
curl http://localhost:8222/healthz
# Check firewall
nc -zv localhost 4222
```
***
## Next Steps
Deep dive into internals
Complete command reference
# Station Lattice
Source: https://docs.cloudshipai.com/station/lattice-overview
Multi-station mesh networking for distributed agent execution
# Station Lattice
Station Lattice enables multiple Station instances to form a mesh network, allowing agents to discover and invoke each other across stations. This creates a powerful distributed system where specialized agents can collaborate on complex tasks.
Station Lattice is designed for teams that need to distribute agent workloads across multiple machines, environments, or security boundaries.
## Key Features
Agents automatically register and discover each other across the mesh
Route requests to agents based on their declared capabilities
Invoke agents on remote stations with request-reply semantics
Assign long-running tasks with JetStream-backed tracking
## Architecture Overview
```
┌─────────────────────────────────────────────────────────────────┐
│ Orchestrator Station │
│ (embedded NATS on :4222) │
│ JetStream KV: stations, agents, work │
└─────────────────────────────────────────────────────────────────┘
│
┌─────────────────────┼─────────────────────┐
│ │ │
▼ ▼ ▼
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ SRE Station │ │ Security │ │ DevOps │
│ K8sHealth │ │ VulnScanner │ │ Deployer │
│ LogAnalyzer │ │ ThreatAnalyz │ │ CICDRunner │
└───────────────┘ └───────────────┘ └───────────────┘
```
## Operating Modes
| Mode | Flag | Description |
| ---------------- | -------------------------------------- | ----------------------------------------------- |
| **Standalone** | `stn serve` | Traditional single-station mode (no lattice) |
| **Orchestrator** | `stn serve --orchestration` | Runs embedded NATS server, coordinates the mesh |
| **Member** | `stn serve --lattice nats://host:4222` | Connects to an orchestrator's NATS server |
## Quick Start
### 1. Start an Orchestrator Station
```bash theme={null}
# Start with embedded NATS server
stn serve --orchestration --workspace ./orchestrator
# The orchestrator will:
# - Start embedded NATS on port 4222
# - Create JetStream KV buckets for registry
# - Begin accepting member connections
```
### 2. Start Member Stations
```bash theme={null}
# On another machine or terminal
stn serve --lattice nats://orchestrator-host:4222 --workspace ./member
# The member will:
# - Connect to orchestrator's NATS
# - Register its station and agents
# - Begin heartbeat presence
```
### 3. Verify the Mesh
```bash theme={null}
# List all connected stations
stn lattice stations list
# List all available agents across the mesh
stn lattice agents list
# Check mesh health
stn lattice status
```
## Use Cases
### Distributed SRE Team
Deploy specialized agents across your infrastructure:
* **Orchestrator** in your central management cluster
* **SRE Station** in production with K8s access
* **Security Station** in isolated security zone
* **DevOps Station** with CI/CD credentials
### Multi-Cloud Deployment
Connect stations across cloud providers:
```bash theme={null}
# AWS orchestrator
stn serve --orchestration --workspace ./aws-station
# GCP member
stn serve --lattice nats://aws-orchestrator:4222 --workspace ./gcp-station
# Azure member
stn serve --lattice nats://aws-orchestrator:4222 --workspace ./azure-station
```
### Development & Production Separation
Keep development agents separate from production:
```bash theme={null}
# Production orchestrator (locked down)
stn serve --orchestration --workspace ./prod --port 8080
# Dev member (connects for read-only monitoring)
stn serve --lattice nats://prod:4222 --workspace ./dev
```
## Next Steps
Detailed configuration options for lattice networking
Complete reference for lattice CLI commands
Technical details on NATS subjects, message flows, and internals
# Lattice Setup
Source: https://docs.cloudshipai.com/station/lattice-setup
Configuration guide for Station Lattice networking
# Lattice Setup & Configuration
This guide covers all configuration options for Station Lattice, including config file setup, environment variables, TLS encryption, and NKey authentication.
## Configuration Methods
Station Lattice can be configured through:
1. **CLI flags** (highest priority)
2. **Environment variables**
3. **Config file** (`config.yaml`)
### Config File
Add a `lattice` section to your `config.yaml`:
```yaml title="config.yaml" theme={null}
workspace: /path/to/workspace
ai_provider: openai
ai_model: gpt-4o-mini
# Lattice configuration
lattice:
# Mode: "orchestrator" or "member"
mode: orchestrator
# Station identity
station_id: sre-station-prod
station_name: SRE Production Station
# Orchestrator settings (when mode: orchestrator)
embedded_nats_port: 4222
embedded_nats_host: 0.0.0.0
# Member settings (when mode: member)
nats_urls:
- nats://orchestrator.example.com:4222
# Presence settings
heartbeat_interval: 5s
presence_timeout: 15s
# TLS settings (optional)
tls:
enabled: true
cert_file: /path/to/cert.pem
key_file: /path/to/key.pem
ca_file: /path/to/ca.pem
# NKey authentication (optional)
nkey:
seed_file: /path/to/nkey.seed
```
### Environment Variables
All lattice settings can be configured via environment variables:
| Variable | Description | Default |
| -------------------------------- | -------------------------- | -------------- |
| `STN_LATTICE_MODE` | `orchestrator` or `member` | - |
| `STN_LATTICE_STATION_ID` | Unique station identifier | auto-generated |
| `STN_LATTICE_STATION_NAME` | Human-readable name | hostname |
| `STN_LATTICE_NATS_URLS` | Comma-separated NATS URLs | - |
| `STN_LATTICE_NATS_PORT` | Embedded NATS port | `4222` |
| `STN_LATTICE_HEARTBEAT_INTERVAL` | Heartbeat frequency | `5s` |
| `STN_LATTICE_TLS_ENABLED` | Enable TLS | `false` |
| `STN_LATTICE_TLS_CERT` | TLS certificate path | - |
| `STN_LATTICE_TLS_KEY` | TLS key path | - |
| `STN_LATTICE_TLS_CA` | TLS CA certificate path | - |
| `STN_LATTICE_NKEY_SEED` | NKey seed file path | - |
### CLI Flags
```bash theme={null}
# Orchestrator mode
stn serve --orchestration \
--lattice-port 4222 \
--lattice-host 0.0.0.0
# Member mode
stn serve --lattice nats://host:4222 \
--station-id my-station \
--station-name "My Station"
```
## Orchestrator Configuration
### Basic Setup
```yaml title="orchestrator-config.yaml" theme={null}
workspace: /opt/station/orchestrator
lattice:
mode: orchestrator
station_id: orchestrator-main
station_name: Main Orchestrator
embedded_nats_port: 4222
embedded_nats_host: 0.0.0.0
```
### JetStream Storage
The orchestrator uses JetStream for persistent storage:
```yaml theme={null}
lattice:
mode: orchestrator
jetstream:
# Storage directory for JetStream data
store_dir: /var/lib/station/jetstream
# Max storage size (default: 1GB)
max_store: 1073741824
# Max memory (default: 256MB)
max_mem: 268435456
```
### Cluster Mode (High Availability)
For production deployments, run multiple orchestrators in cluster mode:
```yaml title="orchestrator-1.yaml" theme={null}
lattice:
mode: orchestrator
cluster:
enabled: true
name: station-cluster
# This node's route address
host: orchestrator-1.example.com
port: 6222
# Other cluster members
routes:
- nats://orchestrator-2.example.com:6222
- nats://orchestrator-3.example.com:6222
```
## Member Configuration
### Basic Setup
```yaml title="member-config.yaml" theme={null}
workspace: /opt/station/member
lattice:
mode: member
station_id: sre-station-east
station_name: SRE Station (US-East)
nats_urls:
- nats://orchestrator.example.com:4222
```
### Multiple NATS URLs (Failover)
```yaml theme={null}
lattice:
mode: member
nats_urls:
- nats://orchestrator-1.example.com:4222
- nats://orchestrator-2.example.com:4222
- nats://orchestrator-3.example.com:4222
```
### Reconnection Settings
```yaml theme={null}
lattice:
mode: member
nats_urls:
- nats://orchestrator.example.com:4222
reconnect:
# Max reconnection attempts (-1 for infinite)
max_attempts: -1
# Wait between reconnection attempts
wait: 2s
# Max wait time (with jitter)
max_wait: 30s
```
## Security Configuration
### TLS Encryption
Generate certificates for secure communication:
```bash theme={null}
# Generate CA
openssl genrsa -out ca.key 4096
openssl req -new -x509 -days 365 -key ca.key -out ca.pem \
-subj "/CN=Station Lattice CA"
# Generate server cert (for orchestrator)
openssl genrsa -out server.key 2048
openssl req -new -key server.key -out server.csr \
-subj "/CN=orchestrator.example.com"
openssl x509 -req -in server.csr -CA ca.pem -CAkey ca.key \
-CAcreateserial -out server.pem -days 365
# Generate client cert (for members)
openssl genrsa -out client.key 2048
openssl req -new -key client.key -out client.csr \
-subj "/CN=member-station"
openssl x509 -req -in client.csr -CA ca.pem -CAkey ca.key \
-CAcreateserial -out client.pem -days 365
```
Configure TLS on orchestrator:
```yaml title="orchestrator-config.yaml" theme={null}
lattice:
mode: orchestrator
tls:
enabled: true
cert_file: /etc/station/certs/server.pem
key_file: /etc/station/certs/server.key
ca_file: /etc/station/certs/ca.pem
# Require client certificates
verify_client: true
```
Configure TLS on member:
```yaml title="member-config.yaml" theme={null}
lattice:
mode: member
nats_urls:
- nats://orchestrator.example.com:4222
tls:
enabled: true
cert_file: /etc/station/certs/client.pem
key_file: /etc/station/certs/client.key
ca_file: /etc/station/certs/ca.pem
```
### NKey Authentication
NKeys provide secure, passwordless authentication using Ed25519 keys.
Generate NKey pairs:
```bash theme={null}
# Install nk tool
go install github.com/nats-io/nkeys/nk@latest
# Generate operator key (for orchestrator)
nk -gen operator -pubout > operator.pub
nk -gen operator > operator.seed
# Generate account key
nk -gen account -pubout > account.pub
nk -gen account > account.seed
# Generate user keys (for members)
nk -gen user -pubout > member1.pub
nk -gen user > member1.seed
```
Configure NKey on orchestrator:
```yaml title="orchestrator-config.yaml" theme={null}
lattice:
mode: orchestrator
nkey:
operator_seed: /etc/station/nkeys/operator.seed
# Allowed user public keys
authorized_users:
- UABC123... # member1.pub content
- UDEF456... # member2.pub content
```
Configure NKey on member:
```yaml title="member-config.yaml" theme={null}
lattice:
mode: member
nats_urls:
- nats://orchestrator.example.com:4222
nkey:
seed_file: /etc/station/nkeys/member1.seed
```
## Agent Configuration
### Declaring Capabilities
Agents can declare capabilities for routing:
```yaml title="agent.yaml" theme={null}
name: k8s-health-checker
description: Checks Kubernetes cluster health
# Capabilities for lattice routing
capabilities:
- kubernetes
- health-check
- monitoring
# Tags for filtering
tags:
environment: production
region: us-east-1
```
### Restricting Remote Access
Control which agents can be invoked remotely:
```yaml title="config.yaml" theme={null}
lattice:
mode: member
# Only expose these agents to the mesh
exposed_agents:
- k8s-health-checker
- log-analyzer
# Or use patterns
exposed_agent_patterns:
- "k8s-*"
- "*-analyzer"
```
## Monitoring
### Health Endpoints
The lattice exposes health information:
```bash theme={null}
# Check lattice status
curl http://localhost:8080/api/v1/lattice/status
# Response:
{
"mode": "member",
"connected": true,
"station_id": "sre-station-east",
"orchestrator": "nats://orchestrator.example.com:4222",
"uptime": "2h15m30s",
"agents_registered": 5
}
```
### Metrics
Lattice exposes Prometheus metrics:
```
# Station presence
station_lattice_heartbeats_total{station_id="sre-station"}
station_lattice_presence_status{station_id="sre-station"}
# Agent invocations
station_lattice_invocations_total{agent="k8s-health",status="success"}
station_lattice_invocation_duration_seconds{agent="k8s-health"}
# Work queue
station_lattice_work_items_total{status="pending"}
station_lattice_work_items_total{status="completed"}
station_lattice_work_duration_seconds{agent="log-analyzer"}
```
## Troubleshooting
### Connection Issues
```bash theme={null}
# Test NATS connectivity
nats server check nats://orchestrator.example.com:4222
# Check station logs
stn serve --lattice nats://host:4222 --log-level debug
# Verify TLS
openssl s_client -connect orchestrator.example.com:4222 \
-cert client.pem -key client.key -CAfile ca.pem
```
### Common Errors
| Error | Cause | Solution |
| --------------------------- | ---------------- | ------------------------------------ |
| `connection refused` | NATS not running | Start orchestrator first |
| `authorization violation` | Invalid NKey | Check seed file and authorized users |
| `certificate verify failed` | TLS mismatch | Verify CA chain matches |
| `station not found` | Not registered | Check heartbeat interval |
# MCP Tools
Source: https://docs.cloudshipai.com/station/mcp-tools
Give agents access to APIs, databases, and services
## What is MCP?
**Model Context Protocol (MCP)** is an open standard for connecting AI agents to external systems. Think of it as a universal adapter for your infrastructure.
MCP servers handle authentication and permissions. Agents never see your credentials directly.
## Why MCP?
| Approach | Security | Maintenance | Ecosystem |
| ---------------- | ------------ | ------------------ | ------------ |
| Direct API | Full access | Custom code | Limited |
| **MCP Protocol** | Fine-grained | Standard interface | 100+ servers |
## Architecture
```
Agent → Station MCP Client → MCP Server → External Service
↓
Validates permissions
```
**Key Benefits:**
* Agents only see results, never credentials
* Grant specific operations (read vs write)
* Same servers work with Claude Desktop, Cursor, and Station
## Configuring MCP Servers
Add servers to your environment's `template.json`:
```json theme={null}
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem@latest", "/workspace"]
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "{{GITHUB_TOKEN}}"
}
}
}
}
```
## Popular MCP Servers
### Filesystem
```json theme={null}
{
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem@latest", "/path/to/allow"]
}
}
```
### GitHub
```json theme={null}
{
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "{{GITHUB_TOKEN}}"
}
}
}
```
### PostgreSQL
```json theme={null}
{
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres", "{{DATABASE_URL}}"]
}
}
```
### AWS
```json theme={null}
{
"aws": {
"command": "uvx",
"args": ["mcp-server-aws"],
"env": {
"AWS_ACCESS_KEY_ID": "{{AWS_ACCESS_KEY_ID}}",
"AWS_SECRET_ACCESS_KEY": "{{AWS_SECRET_ACCESS_KEY}}",
"AWS_REGION": "us-east-1"
}
}
}
```
## Using Template Variables
Store secrets in `variables.yml`:
```yaml theme={null}
GITHUB_TOKEN: ghp_xxxxxxxxxxxx
DATABASE_URL: postgresql://user:pass@localhost/db
AWS_ACCESS_KEY_ID: AKIA...
AWS_SECRET_ACCESS_KEY: secret...
```
Reference in `template.json` with `{{VARIABLE_NAME}}`:
```json theme={null}
{
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "{{GITHUB_TOKEN}}"
}
}
```
## Discovering Tools
After configuring MCP servers:
```bash theme={null}
# List all available tools
stn mcp tools
# Sync tools (after config changes)
stn env sync
```
## Using Tools in Agents
Reference tools by name in your agent's `tools` array:
```yaml theme={null}
---
tools:
- "__read_file"
- "__write_file"
- "__search_files"
- "__github_create_issue"
---
```
Agents can only use tools explicitly listed in their `tools` array.
## Station MCP Tools
When you connect Station as an MCP server to your AI assistant (Claude Desktop, Cursor, etc.), Station provides **41 built-in tools** for managing agents:
### Agent Management (11 tools)
| Tool | Description |
| ---------------------- | ---------------------------------------- |
| `create_agent` | Create new agents with prompts and tools |
| `update_agent` | Modify agent configuration |
| `update_agent_prompt` | Update agent system prompt |
| `delete_agent` | Remove an agent |
| `list_agents` | List all agents (with filters) |
| `get_agent_details` | Get full agent configuration |
| `get_agent_schema` | Get agent's input schema |
| `add_tool` | Add MCP tool to agent |
| `remove_tool` | Remove tool from agent |
| `add_agent_as_tool` | Create multi-agent hierarchies |
| `remove_agent_as_tool` | Break agent hierarchy links |
### Agent Execution (4 tools)
| Tool | Description |
| -------------------- | ---------------------------- |
| `call_agent` | Execute an agent with task |
| `list_runs` | List agent execution history |
| `inspect_run` | Get detailed run information |
| `list_runs_by_model` | Filter runs by AI model |
### Evaluation & Testing (7 tools)
| Tool | Description |
| ------------------------- | ------------------------------------- |
| `generate_and_test_agent` | Generate test scenarios and run agent |
| `batch_execute_agents` | Run multiple agents in parallel |
| `evaluate_benchmark` | Run LLM-as-judge evaluation |
| `evaluate_dataset` | Evaluate entire dataset |
| `export_dataset` | Export runs for analysis |
| `list_benchmark_results` | List evaluation results |
| `get_benchmark_status` | Check evaluation status |
### Reports & Analytics (4 tools)
| Tool | Description |
| ----------------- | ---------------------------------- |
| `create_report` | Create team performance report |
| `generate_report` | Run benchmarks and generate report |
| `list_reports` | List all reports |
| `get_report` | Get report details |
### Environment Management (3 tools)
| Tool | Description |
| -------------------- | ---------------------- |
| `create_environment` | Create new environment |
| `delete_environment` | Delete environment |
| `list_environments` | List all environments |
### MCP Server Management (5 tools)
| Tool | Description |
| ------------------------------------ | --------------------------- |
| `add_mcp_server_to_environment` | Add MCP server config |
| `update_mcp_server_in_environment` | Update MCP server |
| `delete_mcp_server_from_environment` | Remove MCP server |
| `list_mcp_servers_for_environment` | List configured servers |
| `list_mcp_configs` | List all MCP configurations |
### Tool Discovery (2 tools)
| Tool | Description |
| ---------------- | ------------------------------- |
| `discover_tools` | Discover tools from MCP servers |
| `list_tools` | List available tools |
### Scheduling (3 tools)
| Tool | Description |
| ----------------- | ----------------------------------- |
| `set_schedule` | Schedule agent with cron expression |
| `remove_schedule` | Remove agent schedule |
| `get_schedule` | Get agent schedule details |
### Bundles (1 tool)
| Tool | Description |
| -------------------------------- | ----------------------------- |
| `create_bundle_from_environment` | Package environment as bundle |
### Faker System (1 tool)
| Tool | Description |
| ------------------------- | ---------------------------------- |
| `faker_create_standalone` | Create AI-powered mock data server |
To see all available tools in your AI assistant, just ask: "Show me all Station MCP tools available"
## Next Steps
Create agents that use these tools
Build teams with specialized tools
# Multi-Agent Teams
Source: https://docs.cloudshipai.com/station/multi-agent-teams
Build hierarchical agent teams for complex tasks
## Why Multi-Agent Teams?
**Single Agent Limitations:**
* Complex prompts become unwieldy (2000+ lines)
* Hard to test and maintain
* Generic responses for diverse tasks
**Multi-Agent Benefits:**
* **Specialization**: Each agent focuses on one domain
* **Coordination**: Coordinator delegates to specialists
* **Maintainability**: Small, focused prompts
* **Testability**: Test specialists independently
## Team Structure
```
Incident Coordinator (Orchestrator)
├── Kubernetes Expert
├── Log Analyzer
├── Metrics Analyzer
├── Database Troubleshooter
└── Remediation Executor
```
## How It Works
### 1. User Reports Issue
```
"API latency spiked from 200ms to 5s starting 10 minutes ago."
```
### 2. Coordinator Analyzes & Delegates
```yaml theme={null}
Coordinator:
- Analyzes: Performance degradation
- Delegates to: Metrics, Logs, K8s specialists
```
### 3. Specialists Execute
```yaml theme={null}
Metrics Analyzer:
- Queries Prometheus
- Finds: DB query time increased 10x
Log Analyzer:
- Searches application logs
- Finds: "connection timeout" errors
Kubernetes Expert:
- Checks pod status
- Finds: App pods restarting
```
### 4. Coordinator Synthesizes
```
ROOT CAUSE: Database connection pool exhausted
RECOMMENDATION: Scale DB connection pool
```
## Creating Teams
### Via MCP Tools
The easiest way to create multi-agent teams:
```
"Create an incident response team with a coordinator that delegates to
kubernetes, logs, metrics, and database specialists"
```
Station uses these MCP tools:
| Tool | Purpose |
| ---------------------- | --------------------------------------- |
| `create_agent` | Create coordinator or specialist agents |
| `add_agent_as_tool` | Link specialist to coordinator |
| `remove_agent_as_tool` | Unlink specialist from coordinator |
**Example conversation:**
```
You: Create a kubernetes-expert agent
Station: ✅ Created kubernetes-expert (ID: 12)
You: Create an incident-coordinator that uses kubernetes-expert
Station: ✅ Created incident-coordinator (ID: 13)
✅ Added kubernetes-expert as tool __agent_kubernetes_expert
```
### Via .prompt File
The coordinator agent calls specialist agents as tools:
```yaml theme={null}
---
metadata:
name: "Incident Coordinator"
description: "Orchestrates incident response"
model: gpt-5-mini
max_steps: 15
agents:
- "kubernetes_expert"
- "log_analyzer"
- "metrics_analyzer"
- "database_troubleshooter"
---
{{role "system"}}
You are an Incident Response Coordinator.
When investigating incidents:
1. Gather initial context from the report
2. Delegate to appropriate specialists
3. Synthesize findings into root cause
4. Recommend remediation steps
Available specialists:
- kubernetes_expert: Pod, deployment, service issues
- log_analyzer: Application and system logs
- metrics_analyzer: Prometheus/Grafana metrics
- database_troubleshooter: DB performance issues
{{role "user"}}
{{userInput}}
```
## Creating Specialists
Specialists are regular agents focused on one domain:
```yaml theme={null}
---
metadata:
name: "Kubernetes Expert"
description: "Diagnoses Kubernetes issues"
model: gpt-5-mini
max_steps: 8
tools:
- "__kubectl_get_pods"
- "__kubectl_describe"
- "__kubectl_logs"
---
{{role "system"}}
You are a Kubernetes expert. Diagnose pod, deployment, and service issues.
Focus on:
- Pod status and restarts
- Resource constraints
- Network policies
- Recent deployments
{{role "user"}}
{{userInput}}
```
## Agent-as-Tool Naming
When an agent is used as a tool, its name becomes:
```
__agent_{agent_name_snake_case}
```
Example: "Kubernetes Expert" → `__agent_kubernetes_expert`
## Best Practices
Each specialist should do one thing well. 5-8 tools max per specialist.
Coordinator prompts should clearly explain when to use each specialist.
Test each specialist before testing the full team.
Avoid coordinators calling other coordinators. Keep hierarchy flat.
## Next Steps
Orchestrate agents in durable pipelines with parallel execution
Test and score your agent teams
Package teams for distribution
# Outbound Notifications
Source: https://docs.cloudshipai.com/station/notifications
Send webhook notifications from your agents to external systems
## Overview
The notify tool allows agents to send **outbound** notifications via webhooks. Use it to alert users about task completion, errors, or important updates.
**Looking for inbound triggers?** To trigger agents FROM external systems (like PagerDuty or GitHub Actions), see [Event-Triggered Execution](/station/webhooks).
The notify tool is a native Station capability - no MCP server required. Configure it once, and any agent can send notifications.
## Configuration
Station can send notifications to **any HTTP POST endpoint** - ntfy.sh, Slack, Discord, custom webhooks, or any service that accepts POST requests.
Add the notify configuration to your `config.yaml`:
```yaml theme={null}
notify:
webhook_url: https://ntfy.sh/your-topic # Any POST endpoint
api_key: your-api-key # Optional Bearer token
timeout_seconds: 10 # Default: 10
format: ntfy # ntfy, json, or auto
```
### Configuration Options
| Field | Type | Default | Description |
| ----------------- | ------ | ------- | ------------------------------------------ |
| `webhook_url` | string | - | Any HTTP POST endpoint (required) |
| `api_key` | string | - | Bearer token for authentication (optional) |
| `timeout_seconds` | int | 10 | Request timeout |
| `format` | string | `auto` | Webhook format: `ntfy`, `json`, or `auto` |
### Formats
| Format | When to Use | Description |
| ------ | --------------------------- | ---------------------------------------------------------------------------- |
| `ntfy` | ntfy.sh or self-hosted ntfy | Sends message in body, metadata in HTTP headers (Title, Priority, Tags) |
| `json` | Slack, Discord, custom APIs | Sends full JSON payload with all fields |
| `auto` | Default | Auto-detects ntfy URLs (`ntfy.sh` or `/ntfy`), falls back to JSON for others |
Use `format: json` to send to **any webhook** that accepts POST requests with JSON body.
## Environment Variables
For containerized deployments, use environment variables:
```bash theme={null}
STN_NOTIFY_WEBHOOK_URL=https://your-webhook.com/endpoint
STN_NOTIFY_API_KEY=your-token
STN_NOTIFY_TIMEOUT=10
STN_NOTIFY_FORMAT=ntfy
```
## Enabling for Agents
### Via Frontmatter (.prompt file)
Add `notify: true` to your agent's frontmatter:
```yaml theme={null}
---
model: anthropic/claude-sonnet-4-20250514
notify: true
---
You are a monitoring agent. When you detect issues, use the notify tool to alert the user.
Use the notify tool with:
- message: Description of what happened
- title: Brief subject line
- priority: "high" for urgent issues
- tags: Use "warning" for alerts, "white_check_mark" for success
```
### Via MCP Tools
Enable notify when creating an agent:
```
"Create a monitoring agent with notify enabled"
```
The `create_agent` tool accepts a `notify` parameter:
```json theme={null}
{
"name": "alert-bot",
"description": "Sends alerts when issues detected",
"prompt": "You monitor systems and send notifications...",
"environment_id": "1",
"notify": true
}
```
Enable/disable on existing agents with `update_agent`:
```
"Enable notifications for the incident-coordinator agent"
```
```json theme={null}
{
"agent_id": "21",
"notify": true
}
```
The notify tool only appears for agents with `notify: true` AND a configured `notify.webhook_url` in Station config.
## Tool Parameters
When called, the notify tool accepts:
| Parameter | Type | Required | Description |
| ---------- | ------ | -------- | ----------------------------------------- |
| `message` | string | Yes | Notification content |
| `title` | string | No | Subject line |
| `priority` | string | No | `min`, `low`, `default`, `high`, `urgent` |
| `tags` | array | No | Emoji tags (e.g., `["warning", "robot"]`) |
## Webhook Formats
### ntfy Format
When `format: ntfy`, notifications are sent with headers:
```http theme={null}
POST /your-topic HTTP/1.1
Host: ntfy.sh
Authorization: Bearer your-api-key
Title: Alert Title
Priority: high
Tags: warning,robot
Your notification message here
```
### JSON Format
When `format: json`, notifications are sent as JSON:
```json theme={null}
{
"message": "Your notification message",
"title": "Alert Title",
"priority": "high",
"tags": ["warning", "robot"],
"timestamp": "2026-01-02T19:30:00Z"
}
```
## Examples
### ntfy.sh (Official)
```yaml theme={null}
notify:
webhook_url: https://ntfy.sh/my-alerts
api_key: tk_your_token_here
format: ntfy
```
### Self-Hosted ntfy
```yaml theme={null}
notify:
webhook_url: https://ntfy.mycompany.com/alerts
api_key: your-token
format: ntfy
```
### Generic Webhook (Slack, Discord, Custom)
```yaml theme={null}
notify:
webhook_url: https://hooks.slack.com/services/xxx/yyy/zzz
format: json
```
### Auto-Detection
```yaml theme={null}
notify:
webhook_url: https://ntfy.sh/topic
format: auto # Will use ntfy format
```
## Agent Examples
### Alert Agent
```yaml theme={null}
---
model: anthropic/claude-sonnet-4-20250514
notify: true
---
You are an alert agent. When asked to send alerts, use the notify tool immediately.
For urgent issues, use priority "high" and tags ["warning"].
For success notifications, use tags ["white_check_mark"].
```
### Monitoring Agent
```yaml theme={null}
---
model: gpt-4o-mini
notify: true
tools:
- "__check_system_health"
---
You monitor systems and send notifications when issues are detected.
After each health check:
1. If issues found: notify with priority "high" and tag "warning"
2. If all healthy: notify with tag "white_check_mark"
```
## Tracing
Notify tool calls are traced with OpenTelemetry:
| Attribute | Description |
| ----------------------- | ------------------------------------- |
| `notify.success` | Whether notification was sent |
| `notify.message_id` | ID returned by webhook (if available) |
| `notify.message_length` | Length of message |
| `notify.priority` | Priority level used |
## Troubleshooting
### Notification Not Sent
1. Check `webhook_url` is accessible
2. Verify `api_key` if endpoint requires authentication
3. Check Station logs for error messages
### Wrong Format
If self-hosted ntfy isn't detected, explicitly set `format: ntfy`:
```yaml theme={null}
notify:
webhook_url: https://notifications.internal/alerts
format: ntfy # Force ntfy format
```
### Testing
Test your webhook directly:
```bash theme={null}
curl -X POST https://ntfy.sh/your-topic \
-H "Authorization: Bearer your-token" \
-H "Title: Test" \
-d "Test message"
```
## Notifications vs Webhooks
| Feature | Notify (this page) | Webhooks |
| ------------- | ------------------------- | ------------------------ |
| Direction | Station → External | External → Station |
| Purpose | Send alerts/notifications | Trigger agent execution |
| Use case | Agent alerts user | PagerDuty triggers agent |
| Configuration | `notify:` in config.yaml | `STN_WEBHOOK_API_KEY` |
See [Event-Triggered Execution](/station/webhooks) for inbound triggers.
## Next Steps
* [Webhooks](/station/webhooks) - Trigger agents from external systems
* [Scheduling](/station/scheduling) - Cron-based execution
* [Observability](/station/observability) - Monitor notifications
# Observability & Tracing
Source: https://docs.cloudshipai.com/station/observability
OpenTelemetry integration for complete execution visibility
# Observability & Tracing
Station includes built-in OpenTelemetry (OTEL) support for complete execution observability. Every agent execution, LLM call, and tool invocation is automatically traced.
## What Gets Traced
| Component | Details Captured |
| ----------------------- | -------------------------------------------------------- |
| **Agent Executions** | Complete timeline from start to finish |
| **LLM Calls** | Every OpenAI/Anthropic/Gemini API call with latency |
| **MCP Tool Usage** | Individual tool calls to AWS, databases, etc. |
| **Database Operations** | Query performance and data access patterns |
| **GenKit Spans** | Dotprompt execution, generation flow, model interactions |
## Quick Start with Jaeger
The fastest way to get tracing running locally:
```bash theme={null}
# Start Jaeger
stn jaeger up
# Jaeger UI available at http://localhost:16686
```
Station automatically detects Jaeger and sends traces to `http://localhost:4318`.
### Example Trace
```
incident_coordinator (18.2s)
├─ assess_severity (0.5s)
├─ delegate_logs_investigator (4.1s)
│ └─ __get_logs (3.2s)
├─ delegate_metrics_investigator (3.8s)
│ └─ __query_time_series (2.9s)
├─ delegate_change_detective (2.4s)
│ └─ __get_recent_deployments (1.8s)
└─ synthesize_findings (1.2s)
```
## Configuration
### Environment Variable (Recommended)
```bash theme={null}
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
stn serve
```
### Config File
```yaml theme={null}
# config.yaml
otel_endpoint: "http://localhost:4318"
```
### MCP Client Configuration
When connecting MCP clients, include the OTEL endpoint:
```json theme={null}
{
"mcpServers": {
"station": {
"command": "stn",
"args": ["stdio"],
"env": {
"OTEL_EXPORTER_OTLP_ENDPOINT": "http://localhost:4318"
}
}
}
}
```
Or with Claude Code CLI:
```bash theme={null}
claude mcp add station -e OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 --scope user -- stn stdio
```
## Tracing Backends
Station works with any OpenTelemetry-compatible backend.
### Jaeger (Local Development)
```bash theme={null}
# Built-in command
stn jaeger up
# Or manual Docker
docker run -d --name jaeger \
-p 16686:16686 \
-p 4318:4318 \
-e COLLECTOR_OTLP_ENABLED=true \
jaegertracing/all-in-one:latest
```
**UI:** [http://localhost:16686](http://localhost:16686)
### Grafana Tempo
```yaml theme={null}
# docker-compose.yml
services:
tempo:
image: grafana/tempo:latest
command: ["-config.file=/etc/tempo.yaml"]
volumes:
- ./tempo.yaml:/etc/tempo.yaml
ports:
- "4318:4318" # OTLP HTTP
- "3200:3200" # Tempo API
grafana:
image: grafana/grafana:latest
ports:
- "3000:3000"
environment:
- GF_AUTH_ANONYMOUS_ENABLED=true
```
```bash theme={null}
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
```
### Datadog APM
```bash theme={null}
# Install Datadog Agent with OTLP support
DD_API_KEY= DD_SITE="datadoghq.com" \
DD_OTLP_CONFIG_RECEIVER_PROTOCOLS_HTTP_ENDPOINT="0.0.0.0:4318" \
bash -c "$(curl -L https://install.datadoghq.com/scripts/install_script_agent7.sh)"
# Configure Station
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
```
### Honeycomb
```bash theme={null}
export OTEL_EXPORTER_OTLP_ENDPOINT=https://api.honeycomb.io
export OTEL_EXPORTER_OTLP_HEADERS="x-honeycomb-team=your-api-key"
```
### AWS X-Ray
```bash theme={null}
# Run AWS OTEL Collector
docker run -d \
-p 4318:4318 \
-e AWS_REGION=us-east-1 \
amazon/aws-otel-collector:latest
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
```
### New Relic
```bash theme={null}
export OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.nr-data.net:4318
export OTEL_EXPORTER_OTLP_HEADERS="api-key=your-license-key"
```
### Azure Monitor
```bash theme={null}
# Use Azure Monitor OpenTelemetry Exporter
export APPLICATIONINSIGHTS_CONNECTION_STRING="InstrumentationKey=..."
export OTEL_EXPORTER_OTLP_ENDPOINT=https://dc.services.visualstudio.com/v2/track
```
## Span Details
Station captures rich span information:
### Agent Execution Span
```json theme={null}
{
"name": "agent.execute",
"attributes": {
"agent.id": "21",
"agent.name": "incident_coordinator",
"agent.environment": "production",
"task": "Investigate API timeout",
"model": "gpt-4o-mini",
"max_steps": 20
}
}
```
### LLM Call Span
```json theme={null}
{
"name": "llm.generate",
"attributes": {
"model": "gpt-4o-mini",
"provider": "openai",
"input_tokens": 1250,
"output_tokens": 380,
"latency_ms": 1240
}
}
```
### Tool Call Span
```json theme={null}
{
"name": "tool.call",
"attributes": {
"tool.name": "__get_logs",
"tool.server": "datadog",
"duration_ms": 320,
"success": true
}
}
```
## Viewing Traces
### Jaeger UI
1. Open [http://localhost:16686](http://localhost:16686)
2. Select "station" from the Service dropdown
3. Click "Find Traces"
4. Click on a trace to see the full execution timeline
### Filtering Traces
In Jaeger, use tags to filter:
```
agent.name=incident_coordinator
model=gpt-4o-mini
error=true
```
## Production Setup
### High-Volume Environments
For production, use sampling to reduce trace volume:
```bash theme={null}
export OTEL_TRACES_SAMPLER=parentbased_traceidratio
export OTEL_TRACES_SAMPLER_ARG=0.1 # Sample 10% of traces
```
### Secure Endpoints
```bash theme={null}
# TLS endpoint
export OTEL_EXPORTER_OTLP_ENDPOINT=https://collector.example.com:4318
export OTEL_EXPORTER_OTLP_CERTIFICATE=/path/to/ca.crt
# With authentication
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-token"
```
### Docker Deployment
```yaml theme={null}
# docker-compose.yml
services:
station:
image: ghcr.io/cloudshipai/station:latest
environment:
- OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger:4318
depends_on:
- jaeger
jaeger:
image: jaegertracing/all-in-one:latest
ports:
- "16686:16686"
environment:
- COLLECTOR_OTLP_ENABLED=true
```
## Troubleshooting
### No Traces Appearing
1. **Check endpoint connectivity:**
```bash theme={null}
curl -v http://localhost:4318/v1/traces
# Should return 405 Method Not Allowed (POST required)
```
2. **Verify environment variable:**
```bash theme={null}
echo $OTEL_EXPORTER_OTLP_ENDPOINT
```
3. **Check Station logs:**
```bash theme={null}
stn logs | grep -i otel
```
### Traces Missing Tool Calls
Ensure MCP servers are configured with tracing:
```json theme={null}
{
"mcpServers": {
"my-server": {
"command": "my-mcp-server",
"env": {
"OTEL_EXPORTER_OTLP_ENDPOINT": "http://localhost:4318"
}
}
}
}
```
### High Latency in Traces
If traces show high latency:
1. Check network connectivity to tracing backend
2. Consider async export: traces are sent asynchronously by default
3. For high-volume, use sampling (see Production Setup)
## Next Steps
* [Deployment Monitoring](/station/deployment/monitoring) - Metrics and alerting
* [Scheduling](/station/scheduling) - Automated agent runs
* [CloudShip Integration](/station/cloudship) - Centralized observability
# OpenAPI MCP Servers
Source: https://docs.cloudshipai.com/station/openapi-mcp
Convert OpenAPI specifications to MCP servers automatically
# OpenAPI MCP Servers
:::caution\[Experimental]
OpenAPI to MCP conversion is currently in beta. The API may change.
:::
Station can automatically convert OpenAPI/Swagger specifications into MCP servers, making any REST API instantly available as agent tools.
## How It Works
```
OpenAPI Spec ──stn openapi-runtime──> MCP Server ──> Agent Tools
│ │
└── Paths become tools ──────────────┘
```
Station reads your OpenAPI spec and exposes each endpoint as an MCP tool.
## Quick Start
### 1. Add OpenAPI Spec to Bundle
```json theme={null}
{
"name": "My API Tools",
"description": "Tools from my REST API",
"mcpServers": {
"my-api": {
"command": "stn",
"args": [
"openapi-runtime",
"--spec",
"environments/{{ .ENVIRONMENT_NAME }}/my-api.openapi.json"
]
}
},
"metadata": {
"openapiSpec": "my-api.openapi.json",
"variables": {
"API_BASE_URL": {
"description": "Base URL for the API",
"default": "https://api.example.com"
}
}
}
}
```
### 2. Use Template Variables
Your OpenAPI spec can use template variables:
```json theme={null}
{
"openapi": "3.0.0",
"info": {
"title": "My API",
"version": "1.0.0"
},
"servers": [
{
"url": "{{ .API_BASE_URL }}",
"description": "API endpoint"
}
],
"paths": {
"/users": {
"get": {
"operationId": "listUsers",
"summary": "List all users"
}
}
}
}
```
### 3. Assign to Agent
```yaml theme={null}
---
metadata:
name: "api-manager"
tools:
- "__listUsers" # From OpenAPI spec
- "__createUser"
- "__getUserById"
---
```
## Station Admin Example
Create an agent that manages Station itself using the Station API:
### OpenAPI Spec
```json theme={null}
{
"openapi": "3.0.0",
"info": {
"title": "Station Management API",
"version": "1.0.0"
},
"servers": [
{
"url": "{{ .STATION_API_URL }}",
"description": "Station API endpoint"
}
],
"paths": {
"/api/v1/environments": {
"get": {
"operationId": "listEnvironments",
"summary": "List all environments"
}
},
"/api/v1/agents": {
"get": {
"operationId": "listAgents",
"summary": "List all agents"
},
"post": {
"operationId": "createAgent",
"summary": "Create a new agent"
}
},
"/api/v1/agents/{id}": {
"get": {
"operationId": "getAgent",
"summary": "Get agent by ID"
}
},
"/api/v1/agents/{id}/execute": {
"post": {
"operationId": "executeAgent",
"summary": "Execute an agent"
}
}
}
}
```
### Agent Definition
```yaml theme={null}
---
metadata:
name: "station-admin"
description: "Manages Station environments, agents, and MCP servers"
model: gpt-4o-mini
max_steps: 10
tools:
- "__listEnvironments"
- "__listAgents"
- "__getAgent"
- "__createAgent"
- "__executeAgent"
---
{{role "system"}}
You are a Station administrator. Use the Station API tools to:
- List and inspect environments and agents
- Create new agents from user requirements
- Execute agents and monitor their runs
{{role "user"}}
{{userInput}}
```
### Usage
```bash theme={null}
stn agent run station-admin "Show me all environments and their agents"
```
## Features
### Automatic Tool Generation
Each OpenAPI path becomes an MCP tool:
| OpenAPI | MCP Tool |
| -------------------- | -------------------------------- |
| `GET /users` | `__listUsers` (from operationId) |
| `POST /users` | `__createUser` |
| `GET /users/{id}` | `__getUserById` |
| `DELETE /users/{id}` | `__deleteUser` |
### Template Variable Resolution
Variables in `{{ .VAR }}` format are resolved from:
1. `variables.yml` in the environment
2. Environment variables
3. Default values in metadata
### Authentication Support
```json theme={null}
{
"securityDefinitions": {
"bearerAuth": {
"type": "http",
"scheme": "bearer"
}
},
"security": [
{"bearerAuth": []}
]
}
```
Configure via variables:
```yaml theme={null}
# variables.yml
API_AUTH_TOKEN: "{{ .API_AUTH_TOKEN }}"
```
### Smart Tool Sync
Station detects OpenAPI spec changes and refreshes tools automatically.
## Configuration
### Bundle Manifest
```json theme={null}
{
"name": "API Integration Bundle",
"mcpServers": {
"my-api": {
"command": "stn",
"args": [
"openapi-runtime",
"--spec", "my-api.openapi.json",
"--base-url", "{{ .API_BASE_URL }}"
],
"env": {
"API_TOKEN": "{{ .API_TOKEN }}"
}
}
},
"metadata": {
"openapiSpec": "my-api.openapi.json",
"variables": {
"API_BASE_URL": {
"description": "API base URL",
"required": true
},
"API_TOKEN": {
"description": "API authentication token",
"secret": true
}
}
}
}
```
### Runtime Options
```bash theme={null}
stn openapi-runtime \
--spec path/to/spec.json \
--base-url https://api.example.com \
--header "Authorization: Bearer $TOKEN" \
--timeout 30
```
## Supported Features
| OpenAPI Feature | Support |
| ----------------- | ----------- |
| OpenAPI 3.0 | ✅ Full |
| OpenAPI 3.1 | ✅ Full |
| Swagger 2.0 | ✅ Converted |
| JSON specs | ✅ |
| YAML specs | ✅ |
| \$ref resolution | ✅ |
| allOf/oneOf/anyOf | ✅ |
| Bearer auth | ✅ |
| API key auth | ✅ |
| OAuth2 | ⚠️ Partial |
## Best Practices
1. **Use operationId** - Explicit IDs make cleaner tool names
2. **Write good summaries** - Used as tool descriptions
3. **Define schemas** - Better type information for agents
4. **Use template variables** - Keep credentials out of specs
5. **Version your specs** - Track API changes in Git
## Limitations
* **No webhooks** - Only request/response patterns
* **No streaming** - Standard HTTP only
* **Limited OAuth** - Manual token management required
* **Schema complexity** - Very complex schemas may simplify
## Troubleshooting
### Tool Not Found
```
Error: tool __myOperation not found
```
**Check:**
1. `operationId` is defined in spec
2. Spec file path is correct
3. Run `stn tools list` to see available tools
### Authentication Errors
```
Error: 401 Unauthorized
```
**Check:**
1. Token is set in variables.yml or environment
2. Security scheme matches your auth method
3. Token hasn't expired
### Schema Validation Errors
```
Error: invalid request body
```
**Check:**
1. Request schema matches API expectations
2. Required fields are provided
3. Types match (string vs number)
## Next Steps
* [MCP Tools](/station/mcp/tools) - All available tools
* [Bundles](/station/bundles/creating) - Package with OpenAPI specs
* [Fakers](/station/fakers) - Mock your APIs for testing
# Coding Backends
Source: https://docs.cloudshipai.com/station/opencode
Enable AI coding capabilities with OpenCode or Claude Code
Station integrates with AI coding assistants to provide powerful coding capabilities. Unlike sandbox execution which runs in isolated containers, coding backends work directly on your local filesystem with full IDE-like features.
## Supported Backends
| Backend | Transport | Description |
| --------------- | -------------- | ----------------------------------------------------------------------------------------------------- |
| `opencode` | HTTP | [OpenCode](https://github.com/sst/opencode) server |
| `opencode-cli` | CLI subprocess | OpenCode CLI binary |
| `opencode-nats` | NATS messaging | OpenCode via NATS for distributed setups |
| `claudecode` | CLI subprocess | [Claude Code](https://docs.anthropic.com/en/docs/claude-code) CLI (Anthropic's official coding agent) |
## Coding Backends vs Sandbox
**Local development** with full filesystem access. AI reads, writes, and refactors code on your machine.
**Isolated containers** for safe code execution. Code runs in ephemeral Docker containers.
| Feature | Coding Backends | Sandbox |
| ------------ | ------------------------------------- | --------------------------------- |
| Filesystem | Direct local access | Container isolated |
| Use case | Code development, refactoring | Script execution, data processing |
| Persistence | Changes persist on disk | Ephemeral (container destroyed) |
| Tools | `coding_open`, `code`, `coding_close` | `sandbox_run`, `sandbox_exec` |
| Requirements | OpenCode or Claude Code CLI | Docker |
## How It Works
OpenCode backend creates **coding sessions** that give agents access to your local filesystem:
```
┌─────────────────────────────────────────────────────────────┐
│ YOUR MACHINE │
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Station │─────▶│ OpenCode │─────▶│ Filesystem │ │
│ │ Agent │ │ Server │ │ /my/code │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │ │ │
│ │ 1. coding_open │ │
│ │───────────────────▶│ Creates session │
│ │ │ │
│ │ 2. code │ │
│ │───────────────────▶│ AI writes/edits files │
│ │ │ │
│ │ 3. coding_close │ │
│ │───────────────────▶│ Ends session │
│ │
└─────────────────────────────────────────────────────────────┘
```
1. **Session Creation**: Agent calls `coding_open` with a workspace path
2. **Code Operations**: Agent sends tasks via `code` tool - OpenCode's AI reads, writes, and modifies files
3. **Session End**: Agent calls `coding_close` to clean up
## Quick Start
### 1. Install OpenCode
```bash theme={null}
# macOS
brew install opencode-ai/tap/opencode
# Linux (via curl)
curl -fsSL https://opencode.ai/install.sh | sh
# Or build from source
go install github.com/sst/opencode@latest
```
### 2. Start OpenCode Server
```bash theme={null}
# Start OpenCode (binds to localhost:4096 by default)
opencode
# Or specify a different port
opencode --port 4000
```
For container mode (`stn up`), you must bind to all interfaces:
```bash theme={null}
opencode --hostname 0.0.0.0
```
See [Container Mode](#container-mode-stn-up) for details.
### 3. Configure Station
Add OpenCode URL to your Station config:
```yaml theme={null}
# ~/.config/station/config.yaml
coding:
opencode:
url: http://localhost:4096
```
### 4. Create an Agent with Coding Backend
```yaml theme={null}
---
metadata:
name: "Code Assistant"
description: "AI coding assistant with local filesystem access"
model: openai/gpt-4o
coding:
enabled: true
backend: opencode
---
You are an expert software engineer. Use your coding tools to:
- Read and understand existing code
- Write new files and functions
- Refactor and improve code quality
- Fix bugs and implement features
When given a task, open a coding session, complete the work, then close the session.
```
### 5. Run the Agent
```bash theme={null}
stn agent run "Code Assistant" "Create a Python CLI tool that converts CSV to JSON"
```
## Coding Tools
When `coding.enabled: true` and `coding.backend: opencode`, agents receive these tools:
| Tool | Description |
| --------------- | ----------------------------------------------------- |
| `coding_open` | Start a coding session in a workspace directory |
| `code` | Send coding tasks to OpenCode (read, write, refactor) |
| `coding_close` | End the coding session |
| `coding_commit` | Commit changes with a message (if in git repo) |
| `coding_push` | Push commits to remote (if in git repo) |
| `coding_branch` | Create and/or switch to a git branch |
### Tool Reference
Start a new coding session or continue an existing one.
| Parameter | Type | Required | Description |
| --------------------- | ------ | -------- | ---------------------------------- |
| `workspace_path` | string | No | Directory to work in |
| `repo_url` | string | No | Git repository to clone |
| `branch` | string | No | Branch to checkout after cloning |
| `existing_session_id` | string | No | Continue an existing session by ID |
| `title` | string | No | Friendly name for the session |
| `scope` | string | No | `agent` (default) or `workflow` |
```json theme={null}
{
"workspace_path": "/home/user/my-project"
}
```
To continue an existing session:
```json theme={null}
{
"existing_session_id": "ses_47b42f435ffeOJLjZKhPMk0Adu",
"workspace_path": "/home/user/my-project"
}
```
Returns session ID for subsequent operations.
Execute a coding task. OpenCode's AI will read, write, or modify files as needed.
| Parameter | Type | Required | Description |
| --------- | ------ | -------- | ----------------------------- |
| `task` | string | Yes | What to do (natural language) |
```json theme={null}
{
"task": "Add error handling to the parse_config function in config.py"
}
```
End the current coding session.
No parameters required. Call when done with coding tasks.
Commit changes to git.
| Parameter | Type | Required | Description |
| --------- | ------ | -------- | -------------- |
| `message` | string | Yes | Commit message |
```json theme={null}
{
"message": "Add error handling to config parser"
}
```
Push commits to remote repository.
No parameters required. Pushes current branch to origin.
Create and/or switch to a git branch.
| Parameter | Type | Required | Description |
| ------------ | ------- | -------- | ----------------------------------------------------- |
| `session_id` | string | Yes | The coding session ID |
| `branch` | string | Yes | Branch name to create/switch to |
| `create` | boolean | No | Create the branch if it doesn't exist (default: true) |
```json theme={null}
{
"session_id": "abc123",
"branch": "feature/add-logging",
"create": true
}
```
Returns branch operation result:
```json theme={null}
{
"success": true,
"branch": "feature/add-logging",
"created": true,
"switched_to": true,
"previous_branch": "main"
}
```
## Backend Options
Station supports three backend options for OpenCode integration:
| Backend | Transport | Use Case |
| --------------- | -------------- | ----------------------------------------------- |
| `opencode` | HTTP | Local development, same machine |
| `opencode-nats` | NATS | Containers, distributed setups, remote OpenCode |
| `opencode-cli` | CLI subprocess | CI/CD, GitHub Actions, no server required |
The backend is configured at the **Station level** (`config.yaml`), not per-agent. All agents with `coding.enabled: true` use the same backend. This keeps agent definitions portable across environments.
### HTTP Backend (`opencode`)
Direct HTTP communication with OpenCode. Best for local development where OpenCode runs on the same machine.
```
Station Agent → HTTP → OpenCode Server → Filesystem
```
### NATS Backend (`opencode-nats`)
Uses NATS messaging for communication. Best for containerized or distributed setups where OpenCode runs remotely or in a container with the Station plugin.
```
Station Agent → NATS → Station Plugin → OpenCode → Filesystem
```
The NATS backend enables:
* Running OpenCode in a separate container
* Decoupled architecture (Station and OpenCode can restart independently)
* Multiple Station instances sharing one OpenCode
### CLI Backend (`opencode-cli`)
Spawns `opencode run` as a subprocess for each task. No server required - OpenCode bootstraps itself on a random port for each execution.
```
Station Agent → spawn process → opencode run --format json "task" → Filesystem
```
The CLI backend is ideal for:
* **CI/CD pipelines** (GitHub Actions, GitLab CI)
* **Serverless environments** where you can't run a persistent server
* **Simple setups** without infrastructure dependencies
* **Session continuation** across multiple agent runs
## Configuration Reference
### HTTP Backend Config
```yaml theme={null}
# ~/.config/station/config.yaml
coding:
backend: opencode # HTTP backend
opencode:
url: http://localhost:4096 # OpenCode server URL
max_attempts: 3
task_timeout_min: 10
```
### NATS Backend Config
```yaml theme={null}
# ~/.config/station/config.yaml
coding:
backend: opencode-nats # NATS backend
nats:
url: nats://localhost:4222 # NATS server URL
# creds_file: /path/to/creds # Optional: NATS credentials
max_attempts: 3
task_timeout_min: 10
```
When using `opencode-nats`, ensure the OpenCode container has the Station plugin installed and is connected to the same NATS server. See [OpenCode Container](/station/opencode-container) for setup instructions.
### CLI Backend Config
```yaml theme={null}
# ~/.config/station/config.yaml
coding:
backend: opencode-cli # CLI subprocess backend
cli:
binary_path: opencode # Path to opencode binary (default: "opencode")
timeout_sec: 300 # Task timeout in seconds (default: 300)
workspace_base_path: /tmp/station-coding
cleanup_policy: on_session_end # on_session_end | on_success | manual
```
The CLI backend requires `opencode` to be installed and available in your PATH. No server needs to be running - each task spawns a fresh OpenCode process.
### Claude Code Backend Config
[Claude Code](https://docs.anthropic.com/en/docs/claude-code) is Anthropic's official AI coding agent. It uses your Claude Max/Pro subscription or API key.
```yaml theme={null}
# ~/.config/station/config.yaml
coding:
backend: claudecode # Claude Code CLI backend
claudecode:
binary_path: claude # Path to claude CLI (default: "claude")
timeout_sec: 300 # Task timeout in seconds (default: 300)
model: sonnet # Model: sonnet, opus, haiku (optional)
max_turns: 10 # Max agentic turns (default: 10)
allowed_tools: # Whitelist specific tools (optional)
- Read
- Write
- Edit
- Bash
- Glob
- Grep
disallowed_tools: [] # Blacklist tools (optional)
workspace_base_path: /tmp/station-coding
cleanup_policy: on_session_end
```
1. **Install Claude Code CLI**: [https://docs.anthropic.com/en/docs/claude-code](https://docs.anthropic.com/en/docs/claude-code)
2. **Authenticate**: Run `claude login` for Max/Pro, or set `ANTHROPIC_API_KEY`
```bash theme={null}
# Verify installation
claude --version
# Authenticate (for Max/Pro subscribers)
claude login
```
Claude Code CLI manages its own authentication, **separate from Station**:
| Auth Method | Setup |
| -------------- | -------------------------------------------- |
| Claude Max/Pro | Run `claude login` in terminal |
| API Key | Set `ANTHROPIC_API_KEY` environment variable |
Station's OAuth tokens (from `stn auth anthropic login`) are used for Station's orchestration layer, NOT for Claude Code. This separation allows using different accounts for orchestration vs coding.
```bash theme={null}
# 1. Ensure claude CLI is authenticated
claude --version
claude login # if needed
# 2. Configure Station
cat >> ~/.config/station/config.yaml << 'EOF'
coding:
backend: claudecode
claudecode:
timeout_sec: 300
max_turns: 10
EOF
# 3. Create a coding agent
stn agent create coder \
--description "Coding assistant using Claude Code" \
--prompt "You are a coding assistant. Use coding tools to accomplish tasks." \
--coding '{"enabled":true}' \
--max-steps 10
# 4. Run it
stn agent run coder "Create a hello.py that prints Hello World" --tail
```
Claude Code runs with `--dangerously-skip-permissions` for non-interactive use. Ensure workspace directories are appropriately secured.
### Private Repository Authentication
To work with private repositories, configure git credentials in your Station config:
```yaml theme={null}
# ~/.config/station/config.yaml
coding:
backend: opencode-cli # or any backend
git:
# Option 1: Reference an environment variable (recommended)
token_env: GITHUB_TOKEN
# Option 2: Direct token (supports env expansion)
# token: ${GITHUB_TOKEN}
# Optional: Custom git identity for commits
user_name: "My Bot"
user_email: "bot@example.com"
```
Create a Personal Access Token with `repo` scope:
1. Go to **GitHub Settings → Developer Settings → Personal Access Tokens**
2. Generate a token with `repo` (full control of private repositories)
3. Set it as an environment variable:
```bash theme={null}
export GITHUB_TOKEN=ghp_xxxxxxxxxxxx
```
For organization repos, use a GitHub App token:
```bash theme={null}
# Generate installation token via GitHub API or gh CLI
export GITHUB_TOKEN=$(gh auth token)
```
Create a Project Access Token or Personal Access Token:
```bash theme={null}
export GITHUB_TOKEN=glpat-xxxxxxxxxxxx # GitLab uses same injection method
```
**Security Notes:**
* Never commit tokens to config files - use `token_env` to reference environment variables
* Tokens are automatically redacted from logs and error messages
* In CI/CD, use secrets management (GitHub Secrets, Vault, etc.)
**Example: Clone and work on a private repo**
```yaml theme={null}
# Agent prompt
---
coding:
enabled: true
---
Clone the private repository and add a README:
1. coding_open with repo_url="https://github.com/myorg/private-repo"
2. code with instruction="Create a comprehensive README.md"
3. coding_commit with message="Add README"
4. coding_push
5. coding_close
```
The git token is automatically injected into HTTPS URLs during clone/push operations.
### When to Use Each Backend
| Scenario | Recommended Backend | Reason |
| ------------------------------------------- | ------------------------------ | ----------------------------------------- |
| Claude Max/Pro subscriber | `claudecode` | Use your subscription, minimal setup |
| Prefer Anthropic's official tooling | `claudecode` | First-party Claude integration |
| Local development, OpenCode on same machine | `opencode` (HTTP) | Simplest setup, direct communication |
| Docker/container deployments | `opencode-nats` | Cross-container networking works reliably |
| Long-running tasks (>60s) | `opencode-nats` | Avoids MCP timeout issues |
| Multiple Station instances | `opencode-nats` | Shared OpenCode server |
| CI/CD pipelines (GitHub Actions) | `opencode-cli` or `claudecode` | No server required, self-bootstrapping |
| Serverless / ephemeral environments | `opencode-cli` or `claudecode` | Zero infrastructure dependencies |
| Session continuation across runs | `opencode-cli` | Built-in session ID tracking |
| Quick prototyping | `opencode` (HTTP) | Zero additional infrastructure |
**HTTP Backend (OpenCode):**
```
Station → HTTP Request → OpenCode → Response
(synchronous, ~60s timeout)
```
**NATS Backend (OpenCode):**
```
Station → NATS Publish → Station Plugin → OpenCode → NATS Reply
(asynchronous, configurable timeout)
```
**CLI Backend (Claude Code):**
```
Station → spawn process → claude -p "task" --print → Response
(subprocess, configurable timeout)
```
The NATS backend decouples Station from OpenCode, allowing:
* Independent restarts
* Multiple consumers
* Better timeout handling
| Feature | Claude Code | OpenCode HTTP | OpenCode CLI |
| -------------- | ------------------ | ------------- | -------------- |
| Setup | `claude login` | Start server | Install binary |
| Auth | Max/Pro or API key | API key | API key |
| Latency | Low (local) | Medium (HTTP) | Low (local) |
| Multi-tenant | No | Yes | No |
| Session Resume | Yes (`--resume`) | Yes | Yes |
| Streaming | Yes | Yes | Yes |
| OTEL Tracing | Yes | Yes | Yes |
## Long-Running Tasks and Timeouts
MCP (Model Context Protocol) has a **default timeout of \~60 seconds**. Complex coding tasks like project scaffolding, large refactors, or multi-file changes may exceed this limit.
### Understanding the Timeout
When Station executes agent tools via MCP, each tool call has a timeout. If OpenCode takes longer than 60 seconds to complete a task, the MCP call will fail with a timeout error.
**Tasks that commonly timeout:**
* Generating entire project structures (scaffolding)
* Large codebase refactors
* Complex multi-file changes
* Tasks requiring many LLM calls (iterative refinement)
**Tasks that typically complete quickly:**
* Single file edits
* Adding/modifying functions
* Code review and analysis
* Simple bug fixes
### Solutions for Long-Running Tasks
Instead of one large task, use multiple smaller ones:
```yaml theme={null}
# ❌ Might timeout
task: "Create a full REST API with authentication, CRUD endpoints, and database models"
# ✅ Better approach
tasks:
- "Create the database models for User and Post"
- "Add authentication middleware"
- "Create CRUD endpoints for User"
- "Create CRUD endpoints for Post"
```
Design your agents to work incrementally.
The NATS backend handles long-running tasks better:
```yaml theme={null}
# config.yaml
coding:
backend: opencode-nats
task_timeout_min: 15 # 15 minutes
nats:
url: nats://localhost:4222
```
The `task_timeout_min` setting controls how long to wait for OpenCode responses.
For very long tasks, use async agent execution:
```bash theme={null}
# Start task async
stn agent call "Code Assistant" \
--task "Refactor the entire codebase to TypeScript" \
--async
# Check status
stn runs list
stn runs get
```
Async execution is not bound by MCP timeouts.
### Timeout Configuration
| Setting | Location | Default | Description |
| ------------------ | ---------------- | ------- | ------------------------------------- |
| `task_timeout_min` | `config.yaml` | 10 | Minutes to wait for OpenCode response |
| `max_attempts` | `config.yaml` | 3 | Retry attempts on failure |
| MCP timeout | Protocol default | \~60s | Cannot be changed easily |
```yaml theme={null}
# config.yaml
coding:
backend: opencode-nats
max_attempts: 3
task_timeout_min: 15 # Increase for complex tasks
```
The `task_timeout_min` setting only affects the NATS backend. For HTTP backend, you're constrained by the MCP protocol timeout.
## Session Continuation (CLI Backend)
The CLI backend supports **session continuation** - allowing multiple agent runs to share the same OpenCode context. This is useful for:
* Multi-step workflows where each step builds on previous work
* Interactive development with human-in-the-loop review
* CI/CD pipelines that need to maintain state across jobs
### How It Works
1. **First run** creates a new session (title = your task message)
2. **Subsequent runs** use `--coding-session ` to continue by title
3. OpenCode maintains conversation history, file context, and tool state
```
Run 1: "Create feature branch for user-auth"
↓ session title: "Create feature branch for user-auth"
Run 2: --coding-session "user-auth" → finds session by title
↓ context preserved
Run 3: --coding-session "user-auth" → same session
↓ context preserved
Run 4: --coding-session "user-auth" → commit and push
```
### Using Session Continuation
Pass a session name or ID to continue from a previous run:
```bash theme={null}
# First run - creates new session (title = first message)
stn agent run "Code Assistant" "Create a new feature branch for user-auth"
# Session title: "Create a new feature branch for user-auth"
# Second run - continue by name (partial match works!)
stn agent run "Code Assistant" "Implement the login endpoint" \
--coding-session "user-auth"
# Or use any part of the title
stn agent run "Code Assistant" "Add unit tests for login" \
--coding-session "feature branch"
# Or use the exact session ID
stn agent run "Code Assistant" "Final cleanup" \
--coding-session "ses_47b42f435ffeOJLjZKhPMk0Adu"
```
The `--coding-session` flag accepts:
* **Session name** - Searches titles (case-insensitive, partial match)
* **Session ID** - Direct lookup (starts with `ses_`)
Run `opencode session list` to see all sessions with their titles.
The `coding_open` tool also accepts a session name or ID:
```json theme={null}
{
"existing_session_id": "user-auth",
"workspace_path": "/path/to/project"
}
```
Or with the full ID:
```json theme={null}
{
"existing_session_id": "ses_47b42f435ffeOJLjZKhPMk0Adu",
"workspace_path": "/path/to/project"
}
```
Use session continuation in multi-job workflows:
```yaml theme={null}
jobs:
implement:
runs-on: ubuntu-latest
outputs:
session_id: ${{ steps.implement.outputs.session_id }}
steps:
- uses: actions/checkout@v4
- name: Install Station & OpenCode
run: |
# Install station and opencode
curl -fsSL https://station.dev/install.sh | sh
curl -fsSL https://opencode.ai/install.sh | sh
- name: Implement Feature
id: implement
run: |
OUTPUT=$(stn agent run "Developer" "Implement the requested feature" 2>&1)
SESSION_ID=$(echo "$OUTPUT" | grep -oP 'Session ID: \K[^\s]+')
echo "session_id=$SESSION_ID" >> $GITHUB_OUTPUT
test:
needs: implement
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Add Tests
run: |
stn agent run "Developer" "Add tests for the new feature" \
--coding-session "${{ needs.implement.outputs.session_id }}"
```
### Listing Sessions
You don't need to remember session IDs - just use part of the session title. But if you want to see all sessions:
```bash theme={null}
# List all sessions with titles
opencode session list
# Output:
# Session ID Title Updated
# ───────────────────────────────────────────────────────────────────────────
# ses_47b8a7be0ffe... Create feature branch for user-auth 12:28 AM
# ses_483ea4a0bffe... Fix login validation bug 12:26 AM
```
Then continue any session by name:
```bash theme={null}
stn agent run "Code Assistant" "continue the work" --coding-session "user-auth"
```
### Environment Variables
| Variable | Description |
| ------------------ | --------------------------------------------- |
| `STN_OPENCODE_URL` | Override OpenCode HTTP URL |
| `NATS_URL` | Override NATS URL for `opencode-nats` backend |
### Agent Frontmatter
```yaml theme={null}
---
model: openai/gpt-4o
coding:
enabled: true # Enable coding tools for this agent
workspace_path: /path # Optional: default workspace
---
```
The agent frontmatter only controls whether coding tools are **enabled** for that agent. The backend transport (HTTP vs NATS) is determined by Station's global config. This makes agents portable - the same agent definition works whether Station uses HTTP or NATS backend.
### Agent Prompt Template
When creating agents that use coding tools, you must use the `{{userInput}}` template variable to pass the user's task to the `code` tool. Without this, the agent won't correctly forward the task.
```yaml theme={null}
---
metadata:
name: code-assistant
description: AI coding assistant
model: anthropic/claude-sonnet-4-5-20250929
coding:
enabled: true
---
Execute this coding task: {{userInput}}
Steps:
1. Call coding_open with workspace_path="/path/to/project"
2. Call code with instruction="{{userInput}}"
3. Call coding_close
```
The `{{userInput}}` variable is populated by Station with the user's task message. If you don't reference it in your prompt, the agent won't know what task to execute and may ask for clarification or pass incorrect instructions to the code tool.
## Container Mode (stn up)
When running Station in container mode via `stn up`, special configuration is needed for OpenCode connectivity.
### The Problem
By default, OpenCode binds to `127.0.0.1:4096` which is only accessible from localhost. Docker containers cannot reach `127.0.0.1` on the host.
### The Solution
Start OpenCode with `--hostname 0.0.0.0` to listen on all interfaces:
```bash theme={null}
# Required for container mode
opencode --hostname 0.0.0.0
```
Station's `stn up` command automatically rewrites the config:
```yaml theme={null}
# Your config (host)
coding:
opencode:
url: http://localhost:4096
# Rewritten config (in container)
coding:
opencode:
url: http://host.docker.internal:4096
```
### Verify Connectivity
```bash theme={null}
# Check OpenCode is accessible from container
docker exec station-server curl http://host.docker.internal:4096/global/health
# Should return: {"healthy":true}
```
### Architecture
```
┌─────────────────────────────────────────────────────────────┐
│ HOST MACHINE │
│ │
│ ┌─────────────────┐ ┌─────────────────────────────┐ │
│ │ OpenCode │◀──────│ station-server container │ │
│ │ 0.0.0.0:4096 │ │ coding.opencode.url: │ │
│ │ (--hostname │ │ host.docker.internal:4096 │ │
│ │ 0.0.0.0) │ │ │ │
│ └─────────────────┘ └─────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Local Files │ ◀── Files created/modified here │
│ │ /my/project │ │
│ └─────────────────┘ │
└─────────────────────────────────────────────────────────────┘
```
Files created by OpenCode persist on the host machine, not in the container. This is the key difference from sandbox mode.
## Example Workflows
### Simple File Creation
```bash theme={null}
stn agent run "Code Assistant" "Create hello.py with a hello world function"
```
Agent workflow:
1. `coding_open({"workspace_path": "/tmp/workspace"})`
2. `code({"task": "Create hello.py with a hello world function"})`
3. `coding_close()`
Result: `/tmp/workspace/hello.py` created on your filesystem.
### Code Refactoring
```bash theme={null}
stn agent run "Code Assistant" "Refactor the database module to use connection pooling"
```
Agent workflow:
1. `coding_open({"workspace_path": "/home/user/my-app"})`
2. `code({"task": "Read the current database.py implementation"})`
3. `code({"task": "Refactor to use connection pooling with a pool size of 10"})`
4. `coding_commit({"message": "Refactor: add database connection pooling"})`
5. `coding_close()`
### Full Development Cycle
```yaml theme={null}
---
metadata:
name: "Feature Developer"
description: "Implements features end-to-end"
model: openai/gpt-4o
coding:
enabled: true
backend: opencode
---
You are a senior developer. When given a feature request:
1. Open a coding session in the project directory
2. Read existing code to understand the codebase
3. Implement the feature following existing patterns
4. Write tests for the new functionality
5. Commit changes with a descriptive message
6. Push to the remote branch
7. Close the session
Always follow the project's coding style and conventions.
```
## Troubleshooting
### OpenCode Not Responding
```bash theme={null}
# Check if OpenCode is running
curl http://localhost:4096/global/health
# Check which port OpenCode is using
lsof -i :4096
# Restart OpenCode
pkill opencode && opencode --hostname 0.0.0.0
```
### Container Can't Reach OpenCode
```bash theme={null}
# Verify OpenCode is bound to 0.0.0.0
netstat -tlnp | grep 4096
# Should show 0.0.0.0:4096, not 127.0.0.1:4096
# If bound to 127.0.0.1, restart with:
opencode --hostname 0.0.0.0
```
### Session Errors
If you see "no active session" errors:
* Ensure `coding_open` was called first
* Check OpenCode logs for connection issues
* Verify workspace path exists and is accessible
## Next Steps
Run OpenCode in Docker with OAuth
Run code in isolated containers
Create custom agents
Multi-step agent orchestration
# OpenCode Container
Source: https://docs.cloudshipai.com/station/opencode-container
Run OpenCode in Docker for isolated AI coding environments
The OpenCode Container provides a pre-configured Docker image for running [OpenCode](https://github.com/sst/opencode) as a coding backend for Station agents. It enables AI-powered code generation in isolated, reproducible environments.
## Why Use the Container?
Run OpenCode in a container without affecting your local system. Perfect for CI/CD and testing.
Comes with Bun runtime, Git, and Station plugin pre-installed.
Use Claude Max subscription via OAuth instead of API keys.
Built-in Station plugin for NATS-based task dispatch.
## Quick Start with Station CLI
The easiest way to run OpenCode in a container is using the Station CLI. This manages Docker Compose for you and uses your existing Anthropic OAuth credentials.
```bash theme={null}
stn opencode up
```
This starts OpenCode on port **4099** (to avoid conflicts with native OpenCode on 4096).
```yaml theme={null}
# ~/.config/station/config.yaml
coding:
backend: opencode
opencode:
url: http://localhost:4099
```
```bash theme={null}
stn agent run coder "Create a hello.py file"
```
### Management Commands
```bash theme={null}
stn opencode up # Start the sandbox
stn opencode down # Stop (preserves workspace data)
stn opencode status # Check if running + health
stn opencode logs -f # Follow container logs
stn opencode clean # Remove all data and start fresh
```
### Custom Port
```bash theme={null}
# Use a different port
OPENCODE_PORT=4100 stn opencode up
```
### With NATS (CloudShip Orchestration)
```bash theme={null}
# Start observability stack (includes NATS)
stn jaeger up
# Start OpenCode connected to NATS
NATS_URL=nats://localhost:4222 stn opencode up
```
The Station CLI method uses `ghcr.io/cloudshipai/opencode-station:latest` which includes the Station NATS plugin pre-installed.
***
## Manual Docker Setup
If you prefer manual Docker control, use the steps below.
### 1. Pull the Image
```bash theme={null}
docker pull ghcr.io/sst/opencode:latest
```
### 2. Run with API Key
```bash theme={null}
docker run -d \
-p 4096:4096 \
-e ANTHROPIC_API_KEY=$ANTHROPIC_API_KEY \
ghcr.io/sst/opencode:latest \
opencode serve --hostname 0.0.0.0 --port 4096
```
### 3. Test the Connection
```bash theme={null}
curl http://localhost:4096/global/health
# {"healthy":true}
```
## Authentication Options
### Option 1: API Keys
Pass API keys as environment variables:
```bash theme={null}
docker run -d \
-p 4096:4096 \
-e ANTHROPIC_API_KEY=sk-ant-xxx \
-e OPENAI_API_KEY=sk-xxx \
ghcr.io/sst/opencode:latest \
opencode serve --hostname 0.0.0.0
```
### Option 2: OAuth (Claude Max)
For Claude Max subscribers, use OAuth authentication instead of API keys:
Run `opencode auth login` on your host machine to generate OAuth credentials:
```bash theme={null}
opencode auth login
# Opens browser for Anthropic OAuth
# Saves credentials to ~/.local/share/opencode/auth.json
```
Mount only the `auth.json` file (read-only) into the container:
```bash theme={null}
docker run -d \
-p 4096:4096 \
-v ~/.local/share/opencode/auth.json:/root/.local/share/opencode/auth.json:ro \
ghcr.io/sst/opencode:latest \
opencode serve --hostname 0.0.0.0
```
Mount only `auth.json`, not the entire `~/.local/share/opencode` directory. OpenCode needs to write to its storage subdirectory.
## Docker Compose
### Basic Setup
```yaml theme={null}
version: '3.8'
services:
opencode:
image: ghcr.io/sst/opencode:latest
command: ["opencode", "serve", "--hostname", "0.0.0.0", "--port", "4096"]
ports:
- "4096:4096"
environment:
- ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
volumes:
- opencode-workspaces:/workspaces
working_dir: /workspaces
volumes:
opencode-workspaces:
```
### With OAuth (Claude Max)
```yaml theme={null}
version: '3.8'
services:
opencode:
image: ghcr.io/sst/opencode:latest
command: ["opencode", "serve", "--hostname", "0.0.0.0", "--port", "4096"]
ports:
- "4096:4096"
volumes:
- opencode-workspaces:/workspaces
- ${HOME}/.local/share/opencode/auth.json:/root/.local/share/opencode/auth.json:ro
working_dir: /workspaces
volumes:
opencode-workspaces:
```
### Full Stack with NATS
For Station integration with NATS-based task dispatch:
```yaml theme={null}
version: '3.8'
services:
nats:
image: nats:2.10-alpine
command: ["--jetstream", "--store_dir=/data"]
ports:
- "4222:4222"
- "8222:8222"
volumes:
- nats-data:/data
opencode:
build:
context: ./opencode-plugin
dockerfile: Dockerfile.opencode
environment:
- NATS_URL=nats://nats:4222
- OPENCODE_WORKSPACE_DIR=/workspaces
volumes:
- opencode-workspaces:/workspaces
- ${HOME}/.local/share/opencode/auth.json:/root/.local/share/opencode/auth.json:ro
depends_on:
- nats
ports:
- "4096:4096"
working_dir: /workspaces
volumes:
nats-data:
opencode-workspaces:
```
## Configuration
### OpenCode Config File
Create a custom `opencode.json` for the container:
```json theme={null}
{
"$schema": "https://opencode.ai/config.json",
"model": "anthropic/claude-sonnet-4-20250514"
}
```
Mount it into the container:
```bash theme={null}
docker run -d \
-p 4096:4096 \
-v ./opencode.json:/root/.config/opencode/opencode.json:ro \
-v ~/.local/share/opencode/auth.json:/root/.local/share/opencode/auth.json:ro \
ghcr.io/sst/opencode:latest \
opencode serve --hostname 0.0.0.0
```
### Available Models
| Model | Provider | ID |
| --------------- | --------- | ------------------------------------ |
| Claude Opus 4.5 | Anthropic | `anthropic/claude-opus-4-5-20251101` |
| Claude Sonnet 4 | Anthropic | `anthropic/claude-sonnet-4-20250514` |
| GPT-4o | OpenAI | `openai/gpt-4o` |
| GPT-4o Mini | OpenAI | `openai/gpt-4o-mini` |
### Environment Variables
| Variable | Description |
| ------------------------ | -------------------------------------- |
| `ANTHROPIC_API_KEY` | Anthropic API key (if not using OAuth) |
| `OPENAI_API_KEY` | OpenAI API key |
| `GEMINI_API_KEY` | Google Gemini API key |
| `NATS_URL` | NATS server URL for Station plugin |
| `OPENCODE_WORKSPACE_DIR` | Default workspace directory |
## Building Custom Image
For Station integration with the NATS plugin:
### Dockerfile
```dockerfile theme={null}
FROM ghcr.io/sst/opencode:latest
# Install Bun runtime for plugins and git for workspace operations
RUN apk add --no-cache curl unzip bash git \
&& curl -fsSL https://bun.sh/install | bash \
&& ln -s /root/.bun/bin/bun /usr/local/bin/bun \
&& ln -s /root/.bun/bin/bunx /usr/local/bin/bunx
# Create plugin and config directories
RUN mkdir -p /root/.config/opencode/plugin \
&& mkdir -p /root/.opencode
# Copy the Station plugin
COPY dist/index.js /root/.config/opencode/plugin/station-plugin.js
# Copy OpenCode config
COPY opencode.json /root/.config/opencode/opencode.json
# Copy entrypoint
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
WORKDIR /workspaces
ENTRYPOINT ["/entrypoint.sh"]
```
### Entrypoint Script
```bash theme={null}
#!/bin/bash
set -e
echo "=== OpenCode Container ==="
echo "NATS_URL: ${NATS_URL:-not set}"
echo "OPENCODE_WORKSPACE_DIR: ${OPENCODE_WORKSPACE_DIR:-/workspaces}"
echo "=== Starting OpenCode server ==="
exec opencode serve --port 4096 --hostname 0.0.0.0 --print-logs
```
### Build and Run
```bash theme={null}
# Build the image
docker build -t my-opencode:latest .
# Run with OAuth
docker run -d \
-p 4096:4096 \
-v ~/.local/share/opencode/auth.json:/root/.local/share/opencode/auth.json:ro \
my-opencode:latest
```
## Using with Station
Station can connect to the OpenCode container via two backends:
### Option 1: HTTP Backend (Direct)
Station calls OpenCode's HTTP API directly. Simple setup, good for local development.
```yaml theme={null}
# ~/.config/station/config.yaml
coding:
backend: opencode
opencode:
url: http://localhost:4096
```
### Option 2: NATS Backend (Plugin-based)
Station publishes tasks to NATS, the Station plugin in the container receives them and executes via OpenCode. Better for distributed setups.
```yaml theme={null}
# ~/.config/station/config.yaml
coding:
backend: opencode-nats
nats:
url: nats://localhost:4222
```
Station includes an **embedded NATS server** that starts automatically. No separate NATS installation needed.
**How it works:**
1. Station starts embedded NATS on port 4222
2. OpenCode container connects via `host.docker.internal`
3. Tasks flow: Station → NATS → Station Plugin → OpenCode
```yaml theme={null}
# docker-compose.yaml
services:
opencode:
image: ghcr.io/sst/opencode:latest
environment:
- NATS_URL=nats://host.docker.internal:4222
extra_hosts:
- "host.docker.internal:host-gateway" # Required for Linux
volumes:
- ./workspaces:/workspaces
```
The `extra_hosts` configuration is only needed on Linux. macOS and Windows Docker Desktop include `host.docker.internal` by default.
**Verify connectivity:**
```bash theme={null}
# Check embedded NATS is running on host
netstat -tlnp | grep 4222
# Test from container
docker exec opencode curl -s http://host.docker.internal:4222 || echo "NATS responding"
```
**Embedded NATS environment variables (on Station host):**
| Variable | Default | Description |
| ------------------------ | ------- | ------------------------- |
| `WORKFLOW_NATS_PORT` | `4222` | Change embedded NATS port |
| `WORKFLOW_NATS_EMBEDDED` | Auto | Force `true` or `false` |
See [Configuration](/station/configuration#workflow-and-embedded-nats) for full details.
Use a separate NATS container for production deployments or when you need JetStream persistence:
```yaml theme={null}
# docker-compose.yaml
version: '3.8'
services:
nats:
image: nats:2.10-alpine
command: ["--jetstream", "--store_dir=/data"]
ports:
- "4222:4222"
- "8222:8222" # Monitoring
volumes:
- nats-data:/data
opencode:
image: ghcr.io/sst/opencode:latest
environment:
- NATS_URL=nats://nats:4222
depends_on:
- nats
volumes:
- ./workspaces:/workspaces
volumes:
nats-data:
```
**Configure Station to use external NATS:**
```bash theme={null}
# This disables embedded NATS automatically
WORKFLOW_NATS_URL=nats://localhost:4222 stn serve
```
Or in `config.yaml`:
```yaml theme={null}
coding:
backend: opencode-nats
nats:
url: nats://localhost:4222
```
### Create a Coding Agent
The agent definition is the same regardless of backend - just enable coding:
```yaml theme={null}
---
metadata:
name: "Code Assistant"
description: "AI coding with OpenCode container"
model: openai/gpt-4o
coding:
enabled: true
---
You are a coding assistant. Use your coding tools to:
- Read and understand existing code
- Write new files and functions
- Refactor and improve code quality
When given a task, open a coding session, complete the work, then close the session.
```
Notice the agent doesn't specify `backend: opencode` or `backend: opencode-nats`. The backend is determined by Station's config, making agents portable across different deployments.
### Run the Agent
```bash theme={null}
stn agent run "Code Assistant" "Create a Python function that calculates fibonacci numbers"
```
## Testing
### Health Check
```bash theme={null}
curl http://localhost:4096/global/health
```
### Create Session
```bash theme={null}
curl -X POST http://localhost:4096/session \
-H "Content-Type: application/json" \
-d '{"path":"/workspaces/test"}'
```
### Send Message
```bash theme={null}
SESSION_ID="ses_xxx" # from create session response
curl -X POST "http://localhost:4096/session/${SESSION_ID}/message" \
-H "Content-Type: application/json" \
-d '{"parts":[{"type":"text","text":"Create a hello.py file"}]}'
```
## Troubleshooting
### OAuth Token Not Working
```bash theme={null}
# Check if auth.json exists in container
docker exec cat /root/.local/share/opencode/auth.json
# Should show OAuth token structure:
# {"type":"oauth","token":"...","expiresAt":...}
```
Re-run `opencode auth login` on your host to refresh the token, then restart the container.
### Read-Only Filesystem Error
If you see `EROFS: read-only file system` errors:
```
Error: EROFS: read-only file system, open '/root/.local/share/opencode/storage/...'
```
**Cause**: You mounted the entire `~/.local/share/opencode` directory as read-only.
**Fix**: Mount only `auth.json`:
```bash theme={null}
# Wrong
-v ~/.local/share/opencode:/root/.local/share/opencode:ro
# Correct
-v ~/.local/share/opencode/auth.json:/root/.local/share/opencode/auth.json:ro
```
### Empty Response from API
If API calls return `200 OK` but with empty body:
1. Check container logs: `docker logs `
2. Verify model is configured in `opencode.json`
3. Ensure API key or OAuth credentials are valid
### Container Can't Reach NATS
```bash theme={null}
# Verify NATS is running
curl http://localhost:8222/healthz
# Check container can resolve NATS hostname
docker exec ping nats
# Verify NATS_URL environment variable
docker exec printenv | grep NATS
```
## Next Steps
Configure Station to use OpenCode
Deploy Station with Docker
Run code in isolated containers
Multi-step agent orchestration
# OpenCode Plugin
Source: https://docs.cloudshipai.com/station/opencode-plugin
Use Station with OpenCode via the official skill plugin
Station provides an [OpenCode skill plugin](https://www.npmjs.com/package/@cloudshipai/station-skill) that teaches OpenCode how to use the Station CLI effectively.
## What's Included
| Component | Description |
| ------------------ | ------------------------------------------------------ |
| **station** | Core CLI reference - commands, agent format, workflows |
| **station-config** | Configuration deep-dive - all config options explained |
Unlike Claude Code, OpenCode doesn't have an MCP integration or slash commands. The plugin provides **skills only** - comprehensive guides that teach OpenCode how to work with Station.
## Quick Start
### Install the Plugin
```bash theme={null}
bunx @cloudshipai/station-skill install
```
This installs the Station skills to your OpenCode configuration.
### Verify Installation
After installation, the skills are available in OpenCode:
```
# Load the Station skill
/skill station
# Now ask questions or give commands
Create an agent that analyzes CloudWatch logs
```
## Prerequisites
Before using the plugin:
1. **Station CLI installed**: See [Installation](/station/installation)
2. **Station initialized**: Run `stn init` to set up your workspace
3. **OpenCode installed**: [OpenCode installation guide](https://github.com/sst/opencode)
```bash theme={null}
# Verify Station
stn --version
# Initialize Station
stn init
# Verify OpenCode
opencode --version
```
## Available Skills
### station
The core Station skill - load it with `/skill station`.
Covers:
* **Agent Management**: Create, run, list, update, delete agents
* **Dotprompt Format**: YAML frontmatter + Handlebars templates
* **MCP Tools**: Station's 55+ MCP tools for external integrations
* **Workflows**: State machine orchestration patterns
* **Environments**: Separate dev/staging/prod configurations
* **Bundles**: Package and distribute agent collections
### station-config
Configuration deep-dive - load it with `/skill station-config`.
Covers:
* **Global Config**: `~/.config/station/config.yaml` structure
* **AI Providers**: OpenAI, Anthropic, Azure, Ollama setup
* **Coding Backends**: OpenCode, Claude Code integration
* **CloudShip Platform**: Registration and management
* **OAuth**: Provider authentication flows
* **Environment Variables**: All supported env vars
## Usage Examples
### Creating an Agent
```
/skill station
Create a Station agent called "Log Analyzer" that:
- Uses Claude 3.5 Sonnet
- Has access to file reading tools
- Analyzes log files for errors and patterns
```
### Building a Workflow
```
/skill station
Create a Station workflow that:
1. Receives an alert from PagerDuty
2. Investigates the issue automatically
3. Requires human approval before remediation
4. Documents the resolution
```
### Configuration Help
```
/skill station-config
How do I configure Station to use Azure OpenAI instead of OpenAI directly?
```
## Skills vs MCP Tools
| Feature | OpenCode Plugin | Claude Code Plugin |
| -------------- | ---------------- | ------------------ |
| Skills | Yes (2 skills) | Yes (2 skills) |
| MCP Tools | No | Yes (55+ tools) |
| Slash Commands | No | Yes (4 commands) |
| Installation | `bunx` one-liner | Plugin marketplace |
OpenCode's plugin provides **skills only**. For MCP tool integration, use the Station CLI directly:
```bash theme={null}
# Run agents via CLI
stn agent run "My Agent" "task description"
# List agents
stn agent list
# Execute workflows
stn workflow run "My Workflow" --input '{"key": "value"}'
```
## Troubleshooting
### Skills Not Loading
1. Verify installation succeeded:
```bash theme={null}
bunx @cloudshipai/station-skill install
```
2. Check OpenCode skill directory:
```bash theme={null}
ls ~/.config/opencode/skills/
# Should show station.md and station-config.md
```
3. Restart OpenCode after installation
### Station Commands Failing
1. Verify Station is installed:
```bash theme={null}
stn --version
```
2. Verify Station is initialized:
```bash theme={null}
stn env list
```
3. Check AI provider is configured:
```bash theme={null}
stn provider status
```
## Manual Installation
If the automated installer doesn't work, you can manually copy the skills:
```bash theme={null}
# Clone the Station repo
git clone https://github.com/cloudshipai/station.git
# Copy skills to OpenCode
mkdir -p ~/.config/opencode/skills
cp station/station-skill/skills/*.md ~/.config/opencode/skills/
```
## Next Steps
Create custom AI agents
Multi-step orchestration
Package and distribute agents
Full MCP integration for Claude Code
# Station Overview
Source: https://docs.cloudshipai.com/station/overview
Lightweight runtime for deployable AI sub-agents
## What is Station?
Station is a secure, self-hosted platform for managing AI agents with MCP (Model Context Protocol) tool integration. It provides:
* **AI Agent Runtime**: Execute agents with any AI provider (OpenAI, Gemini, Anthropic, Ollama)
* **MCP Server**: Expose agents as MCP tools for AI editors like Claude Desktop and Cursor
* **Management UI**: Web-based interface for configuration and monitoring
* **Bundle System**: Package and distribute agent configurations
## Architecture
```mermaid theme={null}
graph TB
subgraph "Station"
API[REST API :8585]
MCP[MCP Server :8586]
SSH[SSH Admin :2222]
DB[(SQLite)]
end
subgraph "External"
AI[AI Provider]
Tools[MCP Tools]
Editor[AI Editor]
end
API --> DB
MCP --> DB
SSH --> DB
API --> AI
MCP --> Tools
Editor --> MCP
```
## Key Concepts
### Environments
Station organizes configurations into **environments** (e.g., `default`, `production`, `development`). Each environment has its own:
* Agents
* MCP server configurations
* Variables
```
~/.config/station/
├── config.yaml # Global settings
├── station.db # SQLite database
└── environments/
├── default/
│ ├── template.json # MCP servers config
│ ├── variables.yml # Environment variables
│ └── agents/
│ └── my-agent.prompt
└── production/
└── ...
```
### Agents
Agents are defined as `.prompt` files using dotprompt format:
```yaml theme={null}
---
name: code-reviewer
description: Reviews code for best practices
model: openai/gpt-4o
tools:
- filesystem_read
- github_pr_comments
---
You are an expert code reviewer. Analyze the provided code and suggest improvements.
```
### MCP Servers
MCP servers provide tools to your agents. Configure them in `template.json`:
```json theme={null}
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/workspace"]
}
}
}
```
### Bundles
Bundles package complete environment configurations for easy distribution:
```bash theme={null}
# Create a bundle from your environment
stn bundle create default --output my-bundle.tar.gz
# Install a bundle from CloudShip
stn bundle install my-environment
```
## Running Modes
| Mode | Command | Use Case |
| ---------- | ----------- | ------------------------------------ |
| **Server** | `stn serve` | Local development, direct API access |
| **Docker** | `stn up` | Isolated deployment, CI/CD |
| **stdio** | `stn stdio` | Direct MCP integration with editors |
## Next Steps
Install Station on your system
Complete the initial setup process
# Sandbox Execution
Source: https://docs.cloudshipai.com/station/sandbox
Run code in isolated Linux containers
Station provides sandboxed environments for agents to execute code safely. Two modes are available depending on your use case.
## Sandbox Modes
**Ephemeral containers** for quick calculations and data processing. Each call runs in a fresh container.
**Persistent Linux sandbox** for iterative development. Full shell access, package installation, and file persistence across calls.
| Feature | Compute Mode | Code Mode |
| --------- | ----------------------------- | ------------------------------------ |
| Lifecycle | Fresh container per call | Persistent per workflow |
| Use case | Calculations, transformations | Development, compilation |
| Tool | `sandbox_run` | `sandbox_open`, `sandbox_exec`, etc. |
| Files | Via `files` param only | Full filesystem access |
## Enabling Sandbox
### Via MCP Tools
```
"Create a data-processor agent with Python sandbox enabled"
```
The `create_agent` and `update_agent` tools accept sandbox configuration:
```json theme={null}
{
"name": "data-processor",
"description": "Process data with Python",
"prompt": "You process data. Use sandbox_run to execute Python code.",
"environment_id": "1",
"sandbox": "{\"runtime\": \"python\", \"pip_packages\": [\"pandas\"]}"
}
```
**Enable Code Mode:**
```json theme={null}
{
"agent_id": "42",
"sandbox": "{\"mode\": \"code\", \"session\": \"workflow\"}"
}
```
**Disable sandbox:**
```json theme={null}
{
"agent_id": "42",
"sandbox": "{}"
}
```
### Via Frontmatter (.prompt file)
Add `sandbox:` to your agent's frontmatter:
```yaml theme={null}
---
model: openai/gpt-4o
metadata:
name: "Data Processor"
sandbox: python
---
Process data using Python. Use sandbox_run to execute code.
```
The agent receives a `sandbox_run` tool for executing code:
```json theme={null}
{
"code": "print(sum(range(1, 101)))",
"runtime": "python"
}
```
### Code Mode
Enable persistent Linux sandbox with `mode: code`:
```yaml theme={null}
---
model: openai/gpt-4o
metadata:
name: "Developer Agent"
sandbox:
mode: code
session: workflow
---
You have access to a full Linux sandbox. Install packages,
compile code, and run any shell commands.
```
## Code Mode Tools
When `mode: code` is enabled, agents receive these tools:
| Tool | Description |
| ------------------- | ------------------------------- |
| `sandbox_open` | Get or create a sandbox session |
| `sandbox_exec` | Execute any shell command |
| `sandbox_fs_write` | Write files to the sandbox |
| `sandbox_fs_read` | Read files from the sandbox |
| `sandbox_fs_list` | List directory contents |
| `sandbox_fs_delete` | Delete files or directories |
| `sandbox_close` | Close the session (optional) |
### Example: Full Development Workflow
```bash theme={null}
# Open sandbox (ubuntu:22.04)
sandbox_open({})
# Install dependencies
sandbox_exec({"command": "apt-get update && apt-get install -y build-essential curl"})
# Write source code
sandbox_fs_write({
"path": "main.c",
"content": "#include \nint main() { printf(\"Hello!\\n\"); return 0; }"
})
# Compile and run
sandbox_exec({"command": "gcc -o main main.c && ./main"})
# Output: Hello!
# Install Python packages
sandbox_exec({"command": "pip install pandas numpy"})
# Run Python script
sandbox_fs_write({
"path": "analyze.py",
"content": "import pandas as pd\nprint(pd.__version__)"
})
sandbox_exec({"command": "python analyze.py"})
```
## Configuration Reference
### Compute Mode
```yaml theme={null}
sandbox:
runtime: python # python, node, or bash
image: "python:3.11-slim" # optional: custom image
timeout_seconds: 120 # execution timeout
allow_network: false # network access
pip_packages: # pre-install packages
- pandas
- requests
```
### Code Mode
```yaml theme={null}
sandbox:
mode: code
session: workflow # workflow or agent
runtime: linux # linux, python, node, or custom image
timeout_seconds: 300 # per-command timeout
limits:
max_file_size_bytes: 10485760 # 10MB
max_files: 100
```
### Runtime Images
| Runtime | Docker Image |
| ----------------- | ------------------ |
| `linux` (default) | `ubuntu:22.04` |
| `python` | `python:3.11-slim` |
| `node` | `node:20-slim` |
| Custom | Any Docker image |
## Session Scoping (Code Mode)
Sessions can be scoped to share containers:
Container shared across all agents in a workflow:
```yaml theme={null}
sandbox:
mode: code
session: workflow
```
```
Workflow: build-and-test
├── Agent 1: writes code → sandbox_fs_write
├── Agent 2: runs tests → sandbox_exec (files still there!)
└── Complete → container destroyed
```
Fresh container per agent run:
```yaml theme={null}
sandbox:
mode: code
session: agent
```
## Deployment Requirements
Requires Dagger (auto-managed):
```bash theme={null}
# Docker socket access
docker run -v /var/run/docker.sock:/var/run/docker.sock ...
```
Requires Docker:
```bash theme={null}
# Docker must be available
export DOCKER_HOST=unix:///var/run/docker.sock
# Or remote Docker
export DOCKER_HOST=tcp://docker-host:2375
```
## Fly Machines Backend
When running Station on Fly.io, use the Fly Machines backend instead of Docker (Fly's Firecracker VMs don't support Docker-in-Docker).
### Configuration
```yaml theme={null}
sandbox:
enabled: true
backend: fly_machines
fly_machines:
org_slug: your-org # Or use FLY_ORG env var
region: ord # Fly.io region
image: python:3.11-slim # Container image
memory_mb: 256
cpu_kind: shared
cpus: 1
```
Required environment variables:
* `FLY_API_TOKEN` - Your Fly.io API token
* `FLY_ORG` - Organization slug (if not in config)
### Custom Images
Create a Dockerfile with your required tools:
```dockerfile theme={null}
FROM python:3.11-slim
RUN apt-get update && apt-get install -y git curl unzip && rm -rf /var/lib/apt/lists/*
# Install Terraform
RUN curl -fsSL https://releases.hashicorp.com/terraform/1.7.0/terraform_1.7.0_linux_amd64.zip -o /tmp/tf.zip \
&& unzip /tmp/tf.zip -d /usr/local/bin/ && rm /tmp/tf.zip
# Install kubectl
RUN curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl" \
&& install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl && rm kubectl
WORKDIR /workspace
```
Build and push:
```bash theme={null}
docker build -t yourusername/station-sandbox:latest .
docker push yourusername/station-sandbox:latest
```
Then configure:
```yaml theme={null}
sandbox:
fly_machines:
image: yourusername/station-sandbox:latest
```
### Private Registry Authentication
For private images, add registry credentials:
```yaml theme={null}
sandbox:
fly_machines:
image: ghcr.io/your-org/station-sandbox:latest
registry_auth:
username: your-username
password: ${GITHUB_TOKEN}
server_address: ghcr.io
```
```yaml theme={null}
registry_auth:
username: your-github-username
password: ${GITHUB_TOKEN} # PAT with read:packages
server_address: ghcr.io
```
```yaml theme={null}
registry_auth:
username: your-dockerhub-username
password: ${DOCKER_TOKEN}
server_address: docker.io
```
```yaml theme={null}
registry_auth:
username: AWS
password: ${ECR_TOKEN} # aws ecr get-login-password
server_address: 123456789.dkr.ecr.us-east-1.amazonaws.com
```
## Environment Variable Injection
Inject secrets and configuration into sandbox containers using the `STN_CODE_` prefix. This is essential for CLI tools like Terraform, AWS CLI, kubectl, etc.
### How It Works
Environment variables on the Station host with the `STN_CODE_` prefix are automatically injected into sandbox containers with the prefix stripped:
```bash theme={null}
# Set on Station host (or in Fly secrets):
export STN_CODE_AWS_ACCESS_KEY_ID="AKIAXXXXXXXXXXXX"
export STN_CODE_AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/K7MDENG..."
export STN_CODE_AWS_DEFAULT_REGION="us-east-1"
export STN_CODE_TERRAFORM_TOKEN="tf-xxxxxxxxxxxxxxxx"
# Inside sandbox container, agents see:
AWS_ACCESS_KEY_ID="AKIAXXXXXXXXXXXX"
AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/K7MDENG..."
AWS_DEFAULT_REGION="us-east-1"
TERRAFORM_TOKEN="tf-xxxxxxxxxxxxxxxx"
```
### Setting Variables
```bash theme={null}
# Set secrets on your Fly app
fly secrets set \
STN_CODE_AWS_ACCESS_KEY_ID="AKIAXXXX" \
STN_CODE_AWS_SECRET_ACCESS_KEY="secret" \
STN_CODE_TERRAFORM_TOKEN="tf-xxx" \
--app your-station-app
```
```bash theme={null}
docker run -d \
-e STN_CODE_AWS_ACCESS_KEY_ID="AKIAXXXX" \
-e STN_CODE_AWS_SECRET_ACCESS_KEY="secret" \
-e STN_CODE_TERRAFORM_TOKEN="tf-xxx" \
your-station-image
```
```bash theme={null}
# In your shell or .env file
export STN_CODE_AWS_ACCESS_KEY_ID="AKIAXXXX"
export STN_CODE_AWS_SECRET_ACCESS_KEY="secret"
# Then start Station
stn serve
```
### Common Use Cases
| Tool | Environment Variables |
| ------------ | --------------------------------------------------------------------------------------------- |
| AWS CLI | `STN_CODE_AWS_ACCESS_KEY_ID`, `STN_CODE_AWS_SECRET_ACCESS_KEY`, `STN_CODE_AWS_DEFAULT_REGION` |
| Terraform | `STN_CODE_TF_TOKEN_app_terraform_io`, `STN_CODE_AWS_*` |
| kubectl | `STN_CODE_KUBECONFIG` (base64 encoded) |
| GitHub CLI | `STN_CODE_GITHUB_TOKEN` |
| Google Cloud | `STN_CODE_GOOGLE_APPLICATION_CREDENTIALS` |
### Example: Terraform Agent
```yaml theme={null}
---
model: openai/gpt-4o
metadata:
name: "Terraform Agent"
sandbox:
mode: code
session: workflow
image: hashicorp/terraform:latest
---
You can run Terraform commands. The AWS credentials and Terraform token
are pre-configured in the environment.
Example workflow:
1. sandbox_open({})
2. sandbox_fs_write({"path": "main.tf", "content": "..."})
3. sandbox_exec({"command": "terraform init"})
4. sandbox_exec({"command": "terraform plan"})
```
Never hardcode secrets in agent prompts or workflow definitions. Always use `STN_CODE_*` environment variables.
## Session Persistence (Fly Machines)
When running on Fly.io, sandbox sessions are persisted to NATS KV store. This enables sessions to survive Station restarts.
### How It Works
```
Station Start
│
▼
┌─────────────────────────────────────┐
│ NATS KV Store (sessions bucket) │
│ ┌─────────────────────────────┐ │
│ │ fly_abc123 → Machine ID │ │
│ │ fly_def456 → Machine ID │ │
│ └─────────────────────────────┘ │
└─────────────────────────────────────┘
│
▼
SessionManager loads from KV
│
▼
Fly Machines still running ✓
```
### Benefits
| Scenario | Without Persistence | With NATS KV |
| -------------------- | ------------------------------ | ------------------ |
| Station restart | Sessions lost, orphan machines | Sessions recovered |
| Workflow continues | Fails (session not found) | Works seamlessly |
| Multi-step workflows | Must complete before restart | Can span restarts |
### Configuration
Session persistence is automatic when using Fly Machines backend. No additional configuration required.
```yaml theme={null}
sandbox:
enabled: true
backend: fly_machines
# Session persistence enabled automatically
```
### Session Recovery
On Station startup, existing Fly Machines are automatically recovered:
```
[INFO] Session store: Initialized with NATS KV (bucket: sandbox_sessions)
[INFO] Recovered 3 sandbox sessions from NATS KV
```
Sessions are keyed by workflow run ID for workflow-scoped sessions, ensuring the same sandbox is reused across workflow steps even after Station restarts.
## Security
Both modes provide isolation:
* Unprivileged containers (no `--privileged`)
* No Docker socket access from within sandbox
* Network disabled by default
* Resource limits enforced
* Timeout protection
Enable `allow_network: true` only when necessary. Network access allows the sandbox to reach external services.
## File Staging
Stage files between your local system and sandbox containers via NATS Object Store.
File staging solves the challenge of getting large files into sandboxes without passing content through LLM context (which is slow, expensive, and size-limited).
### How It Works
```
Local Files ────▶ NATS Object Store ────▶ Sandbox Container
upload stage_file
◀────────────────────
download publish_file
```
### File Staging Tools
When Code Mode is enabled, agents get two additional tools:
| Tool | Description |
| ---------------------- | ---------------------------------------- |
| `sandbox_stage_file` | Fetch file from store → write to sandbox |
| `sandbox_publish_file` | Read from sandbox → upload to store |
### Example Workflow
```bash theme={null}
# 1. Upload input file
$ stn files upload data.csv
Uploaded: files/f_01JGXYZ123ABC (2.4 MB)
# 2. Run workflow with file reference
$ stn workflow run csv-pipeline --input '{"input_file": "files/f_01JGXYZ123ABC"}'
# 3. Agent stages file into sandbox
sandbox_stage_file({
"sandbox_id": "ses_abc123",
"file_key": "files/f_01JGXYZ123ABC",
"destination": "input/data.csv"
})
# 4. Agent processes file
sandbox_exec({"cmd": ["python", "transform.py", "input/data.csv", "output/result.csv"]})
# 5. Agent publishes output
sandbox_publish_file({
"sandbox_id": "ses_abc123",
"source": "output/result.csv"
})
# Returns: {"file_key": "files/f_01JGDEF456XYZ"}
# 6. Download result
$ stn files download f_01JGDEF456XYZ -o result.csv
```
### Tool Reference
Fetch a file from NATS Object Store and write it to the sandbox.
| Parameter | Type | Required | Description |
| ------------- | ------ | -------- | --------------------------------- |
| `sandbox_id` | string | Yes | Session ID from `sandbox_open` |
| `file_key` | string | Yes | File key (e.g., `files/f_abc123`) |
| `destination` | string | Yes | Path relative to `/workspace` |
```json theme={null}
{
"sandbox_id": "ses_abc123",
"file_key": "files/f_01JGXYZ123ABC",
"destination": "input/data.csv"
}
```
Read a file from the sandbox and upload to NATS Object Store.
| Parameter | Type | Required | Description |
| ------------ | ------ | -------- | -------------------------------------- |
| `sandbox_id` | string | Yes | Session ID from `sandbox_open` |
| `source` | string | Yes | Path relative to `/workspace` |
| `file_key` | string | No | Custom key (auto-generated if omitted) |
```json theme={null}
{
"sandbox_id": "ses_abc123",
"source": "output/result.csv"
}
```
### File Key Conventions
| Pattern | Description | Lifecycle |
| ------------------------- | ----------------- | ----------------------- |
| `files/{file_id}` | User uploads | Permanent until deleted |
| `runs/{run_id}/output/*` | Workflow outputs | Auto-cleanup after TTL |
| `sessions/{session_id}/*` | Session artifacts | Cleanup with session |
See the full `stn files` CLI reference for upload, download, list, and delete commands.
## Next Steps
Create agents that use sandbox
Multi-step agent orchestration
# Agent Scheduling
Source: https://docs.cloudshipai.com/station/scheduling
Run agents automatically on a schedule using cron expressions
# Agent Scheduling
Station supports cron-based scheduling for automated agent execution. Run health checks, cost analysis, compliance audits, or any other task on a regular schedule.
## Quick Start
### Via MCP Tools
```
"Schedule the cost-analyzer agent to run daily at 9 AM"
```
Station will use the `set_schedule` MCP tool to configure the schedule.
### Via CLI
```bash theme={null}
# Set a daily schedule
stn agent schedule cost-analyzer --cron "0 0 9 * * *"
# View schedule
stn agent schedule cost-analyzer --show
# Remove schedule
stn agent schedule cost-analyzer --remove
```
### Via .prompt File
```yaml theme={null}
---
metadata:
name: "cost-analyzer"
description: "Daily AWS cost analysis"
schedule:
cron: "0 0 9 * * *" # Daily at 9 AM
task: "Analyze yesterday's AWS costs and identify anomalies"
variables:
region: "us-east-1"
threshold: "100"
---
{{role "system"}}
You analyze AWS costs and identify spending anomalies.
```
## Cron Expression Format
Station uses **6-field cron expressions** with second precision:
```
┌──────────── second (0-59)
│ ┌────────── minute (0-59)
│ │ ┌──────── hour (0-23)
│ │ │ ┌────── day of month (1-31)
│ │ │ │ ┌──── month (1-12)
│ │ │ │ │ ┌── day of week (0-6, 0=Sunday)
│ │ │ │ │ │
* * * * * *
```
### Common Patterns
| Schedule | Cron Expression | Description |
| ----------------- | ---------------- | ---------------------------- |
| Every 5 minutes | `0 */5 * * * *` | Run at 0, 5, 10... minutes |
| Every hour | `0 0 * * * *` | Run at the top of every hour |
| Daily at 9 AM | `0 0 9 * * *` | Run once daily |
| Daily at midnight | `0 0 0 * * *` | Run at 00:00 |
| Weekly on Monday | `0 0 0 * * 1` | Run Monday at midnight |
| Weekdays at 8 AM | `0 0 8 * * 1-5` | Mon-Fri at 8 AM |
| Monthly on 1st | `0 0 0 1 * *` | First day of month |
| Every 30 seconds | `*/30 * * * * *` | Twice per minute |
## Configuration Methods
### 1. MCP Tools (Recommended)
Use natural language in your AI assistant:
```
"Set a schedule for incident-checker to run every 5 minutes"
"Schedule the compliance-auditor to run weekly on Mondays at midnight"
"Remove the schedule from cost-analyzer"
```
**Available tools:**
* `set_schedule` - Create or update a schedule
* `get_schedule` - View current schedule
* `remove_schedule` - Delete a schedule
### 2. Declarative (.prompt file)
Add a `schedule` block to your agent's `.prompt` file:
```yaml theme={null}
---
metadata:
name: "system-health-checker"
schedule:
cron: "0 */5 * * * *"
task: "Check system health metrics"
enabled: true
variables:
alert_threshold: "90"
---
```
**Schedule fields:**
| Field | Required | Description |
| ----------- | -------- | ------------------------------ |
| `cron` | Yes | 6-field cron expression |
| `task` | Yes | Task/prompt to run |
| `enabled` | No | Enable/disable (default: true) |
| `variables` | No | Input variables for the run |
### 3. CLI
```bash theme={null}
# Set schedule with task
stn agent schedule my-agent \
--cron "0 0 9 * * *" \
--task "Perform daily analysis"
# Set schedule with variables
stn agent schedule my-agent \
--cron "0 0 9 * * *" \
--task "Analyze region" \
--var region=us-east-1 \
--var threshold=100
# View current schedule
stn agent schedule my-agent --show
# Disable without removing
stn agent schedule my-agent --disable
# Re-enable
stn agent schedule my-agent --enable
# Remove completely
stn agent schedule my-agent --remove
```
## Schedule Variables
Pass variables to scheduled runs:
### In .prompt file
```yaml theme={null}
schedule:
cron: "0 0 9 * * *"
task: "Analyze costs for {{region}}"
variables:
region: "us-east-1"
account_id: "123456789"
```
### Via MCP tool
```json theme={null}
{
"agent_id": "21",
"cron_schedule": "0 0 9 * * *",
"schedule_variables": {
"region": "us-east-1",
"threshold": "100"
}
}
```
Variables are available in the agent's prompt as `{{variable_name}}`.
## Viewing Scheduled Runs
### List Scheduled Agents
```bash theme={null}
stn agent list --scheduled
```
### View Run History
```bash theme={null}
# List recent runs for a scheduled agent
stn runs list --agent cost-analyzer --limit 10
# Inspect a specific run
stn runs inspect 123
```
### Via MCP
```
"Show me the last 10 runs of cost-analyzer"
"List all scheduled agents"
```
## Examples
### Daily Cost Analysis
```yaml theme={null}
---
metadata:
name: "cost-analyzer"
schedule:
cron: "0 0 9 * * *"
task: "Analyze yesterday's AWS costs, identify any spending anomalies, and send a summary"
variables:
lookback_days: "1"
---
```
### Continuous Health Monitoring
```yaml theme={null}
---
metadata:
name: "health-monitor"
schedule:
cron: "0 */5 * * * *"
task: "Check all production services and alert if any are unhealthy"
---
```
### Weekly Compliance Audit
```yaml theme={null}
---
metadata:
name: "compliance-auditor"
schedule:
cron: "0 0 0 * * 1"
task: "Run full SOC2 compliance audit on AWS infrastructure"
---
```
### Business Hours Monitoring
```yaml theme={null}
---
metadata:
name: "business-monitor"
schedule:
cron: "0 0 8-18 * * 1-5"
task: "Check customer-facing services during business hours"
---
```
## Timezone
Schedules run in the **server's local timezone** by default.
To verify:
```bash theme={null}
date +%Z # Shows current timezone
```
For UTC-based scheduling, ensure your server is set to UTC:
```bash theme={null}
export TZ=UTC
stn serve
```
## Error Handling
### Failed Scheduled Runs
* Failed runs are logged with error details
* Subsequent scheduled runs continue normally
* Use `stn runs list --status error` to find failures
### Retry Behavior
Scheduled runs do **not** automatically retry on failure. Each scheduled execution is independent.
For critical tasks, consider:
1. Building retry logic into the agent
2. Using a shorter interval with idempotent tasks
3. Setting up alerting via webhooks
## Monitoring Schedules
### Web UI
View scheduled agents at `http://localhost:8585/agents` - scheduled agents show a clock icon.
### Logs
```bash theme={null}
# View scheduler logs
stn logs | grep -i schedule
# View specific agent runs
stn logs | grep "cost-analyzer"
```
### Metrics
With observability enabled, scheduled runs appear as traces in Jaeger:
1. Open Jaeger UI ([http://localhost:16686](http://localhost:16686))
2. Filter by `scheduled=true` tag
3. View execution timeline
## Best Practices
1. **Use descriptive task prompts** - The scheduled task should be self-contained
2. **Set appropriate intervals** - Don't schedule more frequently than needed
3. **Include error handling** - Agents should handle failures gracefully
4. **Monitor run history** - Check for failed runs regularly
5. **Use variables for flexibility** - Make schedules configurable
## Next Steps
* [Webhooks](/station/webhooks) - Trigger agents from external events
* [Observability](/station/observability) - Monitor scheduled runs
* [Agent Configuration](/station/agents/config) - Full agent setup
# Running Station
Source: https://docs.cloudshipai.com/station/serve
Start and manage the Station server
## Running Modes
Station can run in three different modes:
| Mode | Command | Best For |
| ---------- | ----------- | -------------------------------- |
| **Server** | `stn serve` | Local development, direct access |
| **Docker** | `stn up` | Isolated deployment, CI/CD |
| **stdio** | `stn stdio` | Direct MCP integration |
## Server Mode
Start Station directly on your machine:
```bash theme={null}
stn serve
```
This starts all Station services:
| Service | Default Port | Description |
| --------- | ------------ | ------------------------------------- |
| API/UI | 8585 | REST API and Web management interface |
| MCP | 8586 | Model Context Protocol server |
| Agent MCP | 8587 | OAuth-protected dynamic agent MCP |
| SSH | 2222 | SSH admin interface |
### Custom Ports
```bash theme={null}
stn serve --api-port 9000 --mcp-port 9001 --ssh-port 2223
```
### With Telemetry
```bash theme={null}
# Start Jaeger first
stn jaeger up
# Start Station with telemetry enabled
stn serve --enable-telemetry
```
View traces at [http://localhost:16686](http://localhost:16686)
## Docker Mode
Start Station in an isolated Docker container:
```bash theme={null}
stn up
```
### What `stn up` Does
1. **Builds/pulls** the Station container image
2. **Creates** Docker volume for configuration persistence
3. **Mounts** your current directory as `/workspace`
4. **Starts** the container with all services
5. **Updates** `.mcp.json` for Claude Desktop integration
### With Bundle
Install a CloudShip bundle on startup:
```bash theme={null}
stn up --bundle e26b414a-f076-4135-927f-810bc1dc892a
```
### With Custom Workspace
```bash theme={null}
stn up --workspace ~/projects/my-project
```
### Development Mode
Enable Genkit Developer UI for debugging:
```bash theme={null}
stn up --develop
```
Access Genkit UI at [http://localhost:4000](http://localhost:4000)
### Stopping
```bash theme={null}
# Stop container (data preserved)
stn down
# Stop and delete all data
stn down --remove-volume
```
## stdio Mode
For direct MCP integration with AI editors:
```bash theme={null}
stn stdio
```
This mode:
* Runs MCP server over stdin/stdout
* Used by Claude Desktop, Cursor, etc.
* No network ports exposed
### Claude Desktop Integration
Add to your Claude Desktop config:
```json theme={null}
{
"mcpServers": {
"station": {
"command": "stn",
"args": ["stdio"]
}
}
}
```
## Telemetry
Station supports OpenTelemetry for distributed tracing.
### Quick Setup
```bash theme={null}
# Start Jaeger
stn jaeger up
# Verify it's running
stn jaeger status
# Start Station with telemetry
stn serve --enable-telemetry
```
### Manual Configuration
Set in `config.yaml`:
```yaml theme={null}
telemetry_enabled: true
otel_endpoint: http://localhost:4318
```
Or via environment:
```bash theme={null}
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
export OTEL_SERVICE_NAME=station
stn serve
```
### Viewing Traces
Open Jaeger UI at [http://localhost:16686](http://localhost:16686) and search for service `station`.
## Health Checks
Check if Station is running:
```bash theme={null}
stn status
```
Or via API:
```bash theme={null}
curl http://localhost:8585/api/v1/health
```
## Logs
View server logs:
```bash theme={null}
# For stn up (Docker mode)
stn logs
# Follow logs
stn logs --follow
```
## Auto-Sync on Startup
When Station starts, it automatically syncs configurations from file-based configs:
```
📁 Syncing environment: default
✓ Loaded 3 MCP servers from template.json
✓ Loaded 2 agents from agents/*.prompt
✓ Synced 15 tools
```
To skip auto-sync:
```bash theme={null}
stn serve --skip-sync
```
# Event-Triggered Execution
Source: https://docs.cloudshipai.com/station/webhooks
Trigger agent execution from external systems via HTTP webhooks
# Event-Triggered Execution
Trigger agent execution from external systems via HTTP webhook. Perfect for integrating with CI/CD pipelines, alerting systems, or any automation that can make HTTP requests.
## Endpoint
```
POST http://localhost:8587/execute
```
Port 8587 is the Dynamic Agent MCP server, which also serves the webhook endpoint.
## Request Format
```bash theme={null}
# Trigger by agent name
curl -X POST http://localhost:8587/execute \
-H "Content-Type: application/json" \
-d '{"agent_name": "incident_coordinator", "task": "Investigate the API timeout alert"}'
# Trigger by agent ID
curl -X POST http://localhost:8587/execute \
-H "Content-Type: application/json" \
-d '{"agent_id": 21, "task": "Check system health"}'
```
### Request Parameters
| Field | Type | Required | Description |
| ------------ | ------- | -------------- | -------------------------------- |
| `agent_name` | string | One of name/id | Agent name to execute |
| `agent_id` | integer | One of name/id | Agent ID to execute |
| `task` | string | Yes | Task/prompt for the agent |
| `variables` | object | No | Variables for template rendering |
### With Variables
```bash theme={null}
curl -X POST http://localhost:8587/execute \
-H "Content-Type: application/json" \
-d '{
"agent_name": "cost_analyzer",
"task": "Analyze costs for project",
"variables": {"project_id": "prod-123", "region": "us-east-1"}
}'
```
## Response
### Success (202 Accepted)
```json theme={null}
{
"run_id": 120,
"agent_id": 21,
"agent_name": "incident_coordinator",
"status": "running",
"message": "Agent execution started"
}
```
### Error (400/401/404)
```json theme={null}
{
"error": "agent not found",
"message": "No agent with name 'unknown_agent'"
}
```
## Authentication
### Local Mode (Default)
No authentication required when running locally.
### Production
Set a static API key:
```bash theme={null}
export STN_WEBHOOK_API_KEY="your-secret-key"
```
Include in requests:
```bash theme={null}
curl -X POST http://localhost:8587/execute \
-H "Authorization: Bearer your-secret-key" \
-H "Content-Type: application/json" \
-d '{"agent_name": "my-agent", "task": "Do something"}'
```
### CloudShip OAuth
When CloudShip OAuth is enabled, webhook requests use the same OAuth flow as MCP clients.
## Integration Examples
### PagerDuty
Auto-investigate when alerts fire:
```bash theme={null}
curl -X POST https://your-station:8587/execute \
-H "Authorization: Bearer $STN_WEBHOOK_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"agent_name": "incident_coordinator",
"task": "PagerDuty alert: High CPU usage on payment-service"
}'
```
### GitHub Actions
Trigger analysis on deployment:
```yaml theme={null}
# .github/workflows/deploy.yml
- name: Run deployment analyzer
run: |
curl -X POST ${{ secrets.STATION_URL }}/execute \
-H "Authorization: Bearer ${{ secrets.STATION_API_KEY }}" \
-H "Content-Type: application/json" \
-d '{
"agent_name": "deployment_analyzer",
"task": "Analyze deployment ${{ github.sha }}",
"variables": {
"commit": "${{ github.sha }}",
"branch": "${{ github.ref_name }}"
}
}'
```
### Datadog Monitor
Trigger from Datadog webhook:
```json theme={null}
{
"agent_name": "metrics_investigator",
"task": "Investigate alert: {{alertTitle}} - {{alertScope}}",
"variables": {
"alert_id": "{{alertId}}",
"severity": "{{alertPriority}}"
}
}
```
### Slack Slash Command
Create a Slack app that posts to your Station:
```bash theme={null}
# Slack sends: /investigate high memory on api-gateway
curl -X POST https://your-station:8587/execute \
-H "Authorization: Bearer $API_KEY" \
-d '{
"agent_name": "incident_coordinator",
"task": "high memory on api-gateway"
}'
```
### Prometheus Alertmanager
Configure alertmanager webhook:
```yaml theme={null}
# alertmanager.yml
receivers:
- name: 'station'
webhook_configs:
- url: 'https://your-station:8587/execute'
http_config:
bearer_token: 'your-api-key'
send_resolved: true
```
## Configuration
### Enable/Disable
```bash theme={null}
# Enable webhook (default: true)
export STN_WEBHOOK_ENABLED=true
# Disable webhook
export STN_WEBHOOK_ENABLED=false
```
### API Key
```bash theme={null}
# Set static API key for authentication
export STN_WEBHOOK_API_KEY="your-secret-key"
```
### In config.yaml
```yaml theme={null}
# config.yaml
webhook:
enabled: true
api_key: "{{ .STN_WEBHOOK_API_KEY }}"
```
## Checking Run Status
After triggering, use the `run_id` to check status:
```bash theme={null}
# Via API
curl http://localhost:8585/api/v1/runs/120
# Via CLI
stn runs inspect 120
# Via MCP tool
"Inspect run 120"
```
## Async Execution
Webhook triggers are **asynchronous** - the response returns immediately with a `run_id`. The agent executes in the background.
To wait for completion, poll the run status:
```bash theme={null}
# Poll until complete
while true; do
status=$(curl -s http://localhost:8585/api/v1/runs/120 | jq -r '.status')
if [ "$status" = "completed" ] || [ "$status" = "error" ]; then
break
fi
sleep 2
done
```
## Security Considerations
1. **Always use API keys in production** - Never expose unauthenticated webhooks
2. **Use HTTPS** - Encrypt webhook traffic
3. **Validate sources** - Consider IP allowlisting for known sources
4. **Rate limiting** - Station doesn't rate limit by default; use a reverse proxy
5. **Audit logs** - All webhook executions are logged with source info
## Troubleshooting
### Connection Refused
```
Error: connection refused
```
**Check:**
1. Station is running: `stn status`
2. Port 8587 is accessible
3. Firewall allows inbound connections
### 401 Unauthorized
```
Error: 401 Unauthorized
```
**Check:**
1. `STN_WEBHOOK_API_KEY` is set on Station
2. Request includes `Authorization: Bearer ` header
3. Key matches exactly
### Agent Not Found
```
Error: agent not found
```
**Check:**
1. Agent name is correct (case-sensitive)
2. Agent exists: `stn agent list`
3. Agent is enabled
### Run Fails
Check run details:
```bash theme={null}
stn runs inspect
```
Common issues:
* Agent prompt errors
* MCP tool failures
* Timeout exceeded
## Comparison: Webhooks vs Notify
| Feature | Webhooks (this page) | Notify Tool |
| --------- | -------------------------------- | ----------------------- |
| Direction | External → Station | Station → External |
| Purpose | Trigger agents | Send notifications |
| Endpoint | `POST /execute` | Configured webhook URL |
| Example | PagerDuty triggers investigation | Agent sends Slack alert |
See [Notifications](/station/notifications) for outbound notifications.
## Next Steps
* [Notifications](/station/notifications) - Outbound notifications from agents
* [Scheduling](/station/scheduling) - Cron-based execution
* [Observability](/station/observability) - Monitor webhook executions
# Workflows
Source: https://docs.cloudshipai.com/station/workflows
Orchestrate multi-step AI agent tasks with conditional branching, parallel execution, and human approval gates
## Overview
Station's workflow engine enables you to chain agents together into durable, multi-step automated procedures. Workflows support:
* **Parallel execution** - Run multiple agents concurrently
* **Conditional routing** - Branch based on agent outputs
* **Human approval gates** - Block until human approves
* **Data transformation** - Reshape data between steps
* **Loop iteration** - Process arrays with concurrency control
```
┌─────────────────────────────────────────────────────────────────────┐
│ WORKFLOW EXECUTION │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ [Workflow Input] │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ parallel-step │ ← Run 3 agents concurrently │
│ └────────┬────────┘ │
│ ┌─────┼─────┐ │
│ ▼ ▼ ▼ │
│ [agent] [agent] [agent] │
│ │ │ │ │
│ └─────┼─────┘ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ synthesize │ ← Combine results │
│ └────────┬────────┘ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ switch │ ← Route based on severity │
│ └────────┬────────┘ │
│ ┌─────┴─────┐ │
│ ▼ ▼ │
│ [approval] [report] │
│ │ │ │
│ └─────┬─────┘ │
│ ▼ │
│ [Workflow Output] │
│ │
└─────────────────────────────────────────────────────────────────────┘
```
## Quick Start
Create `~/.config/station/environments/default/workflows/my-workflow.workflow.yaml`:
```yaml theme={null}
id: hello-workflow
name: "Hello Workflow"
version: "1.0.0"
description: "A simple workflow example"
start: greet
states:
- id: greet
type: inject
data:
message: "Hello from Station!"
output:
greeting: "$.data"
transition: analyze
- id: analyze
type: agent
agent: my-analyzer # Your agent name
input:
text: "$.greeting.message"
output:
analysis: "$.result"
end: true
```
```bash theme={null}
stn sync # Load the workflow
stn workflow run hello-workflow --wait # Execute it
```
```bash theme={null}
stn workflow runs hello-workflow # List runs
stn workflow runs --steps # View step details
```
## State Types
Workflows are composed of states. Each state has a type that determines its behavior.
Execute a Station agent by name
```yaml theme={null}
type: agent
agent: my-agent
```
Insert static data into context
```yaml theme={null}
type: inject
data: { key: "value" }
```
Conditional branching
```yaml theme={null}
type: switch
conditions:
- if: "expr"
next: state
```
Reshape data with Starlark
```yaml theme={null}
type: transform
expression: |
{ "key": value }
```
Run branches concurrently
```yaml theme={null}
type: parallel
branches:
- id: branch1
states: [...]
```
Iterate over arrays
```yaml theme={null}
type: foreach
itemsPath: "$.items"
maxConcurrency: 5
```
### Agent State
Execute an AI agent and capture its output.
```yaml theme={null}
- id: analyze-logs
name: "Analyze Logs"
type: agent
agent: log-analyzer # Agent name (must exist)
input:
userInput: "${service_name}" # Template variable (recommended)
variables:
time_range: 60 # Static value passed to agent
output:
log_analysis: "$.result" # Store full result
severity: "$.result.severity" # Store specific field
timeout: 2m
transition: next-step
```
#### Agent Input Patterns
When passing data to agent steps, use **template variables** (`${var}`) for the task/userInput field:
```yaml theme={null}
- id: process-data
type: agent
agent: my-agent
input:
userInput: "${query}" # Template variable - WORKS!
```
```yaml theme={null}
- id: process-data
type: agent
agent: my-agent
task: "${query}" # Direct task field - WORKS!
```
```yaml theme={null}
- id: process-data
type: agent
agent: my-agent
input:
userInput: "Analyze this service"
variables:
service_name: "$.input.service" # JSONPath OK in variables
environment: "production" # Static values
```
**JSONPath (`$.path`) does NOT work in `input.task` or `input.userInput` fields** - only template variables (`${var}`) are resolved. JSONPath works correctly in:
* `output` mappings
* `input.variables`
* `dataPath` in switch states
**Workaround**: Always use template variables like `${my_var}` instead of `$.my_var` for task/userInput fields.
#### Multi-Step Data Flow
Pass data between workflow steps using output mappings and template variables:
```yaml theme={null}
states:
# Step 1: Get user data
- id: get-user
type: agent
agent: user-lookup
input:
userInput: "Get email for user ${user_id}"
output:
user_email: "$.response" # Store response at $.user_email
transition: send-notification
# Step 2: Use Step 1's output
- id: send-notification
type: agent
agent: notifier
input:
userInput: "Send alert to ${user_email}" # Uses Step 1 output!
end: true
```
| Syntax | Where It Works | Example |
| -------- | ------------------------------------ | ---------------------------------- |
| `${var}` | task, userInput, anywhere | `"Process ${query}"` |
| `$.path` | output mappings, variables, dataPath | `output: { result: "$.response" }` |
### Switch State
Route execution based on conditions using Starlark expressions.
**Always use `hasattr()` for safe field access.** Agent outputs may not include all expected fields.
```yaml theme={null}
- id: check-severity
type: switch
dataPath: "$.analysis_result"
conditions:
# ALWAYS use hasattr() to check field existence
- if: "hasattr(analysis_result, 'severity') and analysis_result.severity == 'critical'"
next: escalate
- if: "hasattr(analysis_result, 'rollback_needed') and analysis_result.rollback_needed"
next: request-approval
defaultNext: complete
```
**Built-in Functions:**
| Function | Description | Example |
| -------------------------------- | ---------------------- | ----------------------------- |
| `hasattr(obj, "field")` | Check if field exists | `hasattr(result, "error")` |
| `getattr(obj, "field", default)` | Get field with default | `getattr(result, "count", 0)` |
| `len(collection)` | Get length | `len(pods) > 0` |
### Transform State
Reshape data using Starlark expressions. Use `getattr()` for safe access with defaults.
```yaml theme={null}
- id: build-report
type: transform
expression: |
# All context variables available as globals
# Use getattr for safe access with defaults
report = {
"service": getattr(input, "service_name", "unknown"),
"root_cause": getattr(analysis, "root_cause", {}),
"actions": getattr(analysis, "recommended_actions", []),
"severity": getattr(analysis, "severity", "unknown")
}
# Last expression is the output
report
output:
final_report: "$.result"
end: true
```
### Parallel State
Execute multiple branches concurrently and wait for all to complete.
```yaml theme={null}
- id: gather-data
type: parallel
branches:
- id: check-k8s
start: k8s-step
states:
- id: k8s-step
type: agent
agent: k8s-investigator
input:
namespace: "$.input.namespace"
output:
k8s_data: "$.result"
end: true
- id: check-logs
start: logs-step
states:
- id: logs-step
type: agent
agent: log-analyzer
input:
service: "$.input.service"
output:
log_data: "$.result"
end: true
output:
all_data: "$.branches"
transition: synthesize
```
### Foreach State
Iterate over an array with optional concurrency.
```yaml theme={null}
- id: check-all-services
type: foreach
itemsPath: "$.input.services" # Path to array
itemName: "service" # Variable name for current item
maxConcurrency: 5 # Run up to 5 in parallel
iterator:
start: check-service
states:
- id: check-service
type: agent
agent: health-checker
input:
name: "$.service.name"
namespace: "$.service.namespace"
output:
health: "$.result"
end: true
output:
all_results: "$.iterations"
transition: summarize
```
### Human Approval State
Block workflow until a human approves or rejects.
```yaml theme={null}
- id: request-approval
type: human_approval
approval_title: "Production Deployment"
message: |
**Service:** {{input.service_name}}
**Changes:** {{build_result.changelog}}
Do you approve this deployment?
approvers:
- oncall-sre
- platform-leads
timeout: 30m
transition: deploy
```
## Complete Example
Here's a full incident RCA workflow that demonstrates parallel execution, conditional routing, and human approval:
```yaml theme={null}
id: incident-rca
name: "Incident Root Cause Analysis"
version: "1.0.0"
description: "Parallel investigation with synthesis and approval"
inputSchema:
type: object
properties:
service_name:
type: string
required:
- service_name
start: parallel-investigation
states:
# Step 1: Gather data in parallel
- id: parallel-investigation
type: parallel
branches:
- id: k8s-branch
start: check-k8s
states:
- id: check-k8s
type: agent
agent: k8s-investigator
input:
service: "$.input.service_name"
output:
k8s_data: "$.result"
timeout: 2m
end: true
- id: logs-branch
start: check-logs
states:
- id: check-logs
type: agent
agent: log-analyzer
input:
service: "$.input.service_name"
output:
log_data: "$.result"
timeout: 2m
end: true
output:
investigation: "$.branches"
transition: synthesize
# Step 2: Synthesize findings
- id: synthesize
type: agent
agent: rca-synthesizer
input:
k8s_data: "$.investigation.k8s_branch.k8s_data"
log_data: "$.investigation.logs_branch.log_data"
output:
rca_result: "$.result"
timeout: 2m
transition: check-rollback
# Step 3: Route based on analysis
- id: check-rollback
type: switch
dataPath: "$.rca_result"
conditions:
- if: "hasattr(rca_result, 'rollback_recommended') and rca_result.rollback_recommended == True"
next: request-approval
defaultNext: generate-report
# Step 4: Human approval (if rollback needed)
- id: request-approval
type: human_approval
message: |
**Root Cause Analysis Complete**
Service: {{input.service_name}}
Cause: {{rca_result.root_cause.description}}
Rollback recommended to: {{rca_result.rollback_target}}
Do you approve?
timeout: 30m
transition: generate-report
# Step 5: Build final output
- id: generate-report
type: transform
expression: |
{
"service": getattr(input, "service_name", "unknown"),
"root_cause": getattr(rca_result, "root_cause", {}),
"actions": getattr(rca_result, "recommended_actions", []),
"rollback_needed": getattr(rca_result, "rollback_recommended", False)
}
output:
final_report: "$.result"
end: true
```
## MCP Integration
Workflows are available through Station's MCP server. When authoring workflows via MCP tools, **always read the DSL reference first**:
```
station://docs/workflow-dsl
```
This resource contains the complete DSL specification, all state types, and Starlark expression reference.
### Available Tools
| Tool | Description |
| -------------------- | ---------------------------------------------- |
| `create_workflow` | Create a new workflow definition |
| `update_workflow` | Update existing workflow (creates new version) |
| `validate_workflow` | Validate definition without saving |
| `start_workflow_run` | Start a new workflow run |
| `get_workflow_run` | Get run status and details |
## Best Practices
Agent outputs may not include all expected fields. Always check existence:
```yaml theme={null}
# BAD - will fail if field missing
- if: "result.rollback == True"
# GOOD - checks existence first
- if: "hasattr(result, 'rollback') and result.rollback == True"
```
Prevent workflows from hanging indefinitely:
```yaml theme={null}
- id: long-analysis
type: agent
agent: deep-analyzer
timeout: 5m # Always set a timeout
```
Makes debugging much easier:
```yaml theme={null}
# BAD
- id: step1
# GOOD
- id: gather-pod-metrics
```
Handle unexpected values gracefully:
```yaml theme={null}
- id: route
type: switch
conditions:
- if: "..."
next: known-path
defaultNext: fallback-path # Always include
```
## Troubleshooting
The agent didn't output the expected field. Use `hasattr()`:
```yaml theme={null}
if: "hasattr(result, 'field') and result.field == 'value'"
```
Check NATS is running and workflow consumer started:
```bash theme={null}
stn status
# Look for "Workflow consumer started" in logs
```
Check Starlark syntax:
* Use `=` for assignment, `==` for comparison
* Strings need quotes: `"value"` not `value`
* Dict syntax: `{"key": value}`
## REST API Reference
Station exposes a REST API for programmatic workflow management.
### Workflow Definitions
| Method | Endpoint | Description |
| -------- | ----------------------------------- | ------------------------------------- |
| `POST` | `/api/v1/workflows` | Create a new workflow |
| `GET` | `/api/v1/workflows` | List all workflows |
| `GET` | `/api/v1/workflows/:id` | Get workflow by ID |
| `PUT` | `/api/v1/workflows/:id` | Update workflow (creates new version) |
| `DELETE` | `/api/v1/workflows/:id` | Disable workflow |
| `POST` | `/api/v1/workflows/validate` | Validate definition without saving |
| `GET` | `/api/v1/workflows/:id/versions` | List all versions |
| `GET` | `/api/v1/workflows/:id/versions/:v` | Get specific version |
**Create Workflow Request:**
```json theme={null}
{
"workflowId": "incident-rca",
"name": "Incident Root Cause Analysis",
"description": "Parallel investigation with synthesis",
"definition": {
"id": "incident-rca",
"start": "investigate",
"states": [...]
}
}
```
### Workflow Runs
| Method | Endpoint | Description |
| ------ | ---------------------------------- | --------------------------------------------- |
| `POST` | `/api/v1/workflow-runs` | Start a new run |
| `GET` | `/api/v1/workflow-runs` | List runs (filter by `workflow_id`, `status`) |
| `GET` | `/api/v1/workflow-runs/:id` | Get run status and output |
| `GET` | `/api/v1/workflow-runs/:id/stream` | SSE stream of run updates |
| `GET` | `/api/v1/workflow-runs/:id/steps` | List completed steps |
| `POST` | `/api/v1/workflow-runs/:id/pause` | Pause execution |
| `POST` | `/api/v1/workflow-runs/:id/resume` | Resume paused run |
| `POST` | `/api/v1/workflow-runs/:id/cancel` | Cancel run |
**Start Run Request:**
```json theme={null}
{
"workflowId": "incident-rca",
"input": {
"service_name": "payment-service",
"namespace": "production"
}
}
```
### Approvals
| Method | Endpoint | Description |
| ------ | ---------------------------------------- | ----------------------------- |
| `GET` | `/api/v1/workflow-approvals` | List pending approvals |
| `GET` | `/api/v1/workflow-approvals/:id` | Get approval details |
| `POST` | `/api/v1/workflow-approvals/:id/approve` | Approve with optional comment |
| `POST` | `/api/v1/workflow-approvals/:id/reject` | Reject with reason |
**Approve Request:**
```json theme={null}
{
"comment": "Reviewed and approved for production rollout"
}
```
**Reject Request:**
```json theme={null}
{
"reason": "Risk too high - needs additional review"
}
```
Set `X-Approver-ID` header to identify the approver. Defaults to `api-user` if not provided.