DEV Community

Cover image for OpenCode: tools, commands, agents y workflows
Kevin Lupera
Kevin Lupera

Posted on

OpenCode: tools, commands, agents y workflows

Estas listo para ir al siguiente nivel con el uso de IA en programación y documentación de tus proyectos!!!

OpenCode, me impresionaron sus capacidades. A pesar de aprender sobre agentes y flujos de trabajo en Claude Code, me preguntaba si podría implementar soluciones similares con OpenCode, y efectivamente pude hacerlo. La plataforma OpenCode podría incluso ofrecer más potencia y un diseño más intuitivo para ciertas aplicaciones.

Lo que descubrí me sorprendió: los mismos patrones de agentes que me encantaban en Claude Code, pero con manifiestos JSON para seguimiento de estados y puertas de validación que detectan errores antes de que caigan en cascada.

OpenCode aborda el mismo desafío con una filosofía diferente; es de código abierto, admite modelos 75+ y agrega configuración estructurada junto con lenguaje natural:

Característica OpenCode Claude Code
Entorno Consola TUI Consola CLI
Soporte de modelo 75+ proveedores Modelos Claude
Configuración JSON/Markdown Markdown puro
Recuperación de errores Manifiestos Manejo de errores
Costo Gratis (paga por claves API) Suscripción

Puedes usar OpenCode con BedRock, Gemini y tu suscripción Claude Pro. Es una solución agnostica que te permite poder cambiar de proveedor de LLM sin tener que estar atado a uno.

Tools

Las herramientas permiten al LLM realizar acciones en su código base. OpenCode incluye un conjunto de herramientas integradas, pero puede ampliarlo con herramientas personalizadas o servidores MCP.

MCP

Local

Añade servidores MCP locales utilizando el tipo «local» dentro del objeto MCP.

opencode.jsonc

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "my-local-mcp-server": {
      "type": "local",
      // Or ["bun", "x", "my-mcp-command"]
      "command": ["npx", "-y", "my-mcp-command"],
      "enabled": true,
      "environment": {
        "MY_ENV_VAR": "my_env_var_value",
      },
    },
    "mcp_everything": {
      "type": "local",
      "command": ["npx", "-y", "@modelcontextprotocol/server-everything"],
    },
  },
}
Enter fullscreen mode Exit fullscreen mode

Por defecto, las tools estan habilitadas para ejecutarse. Puedes configurar cada permiso de las herramientas.

Commands

Los comandos permiten realizar tareas repetitivas, como ejecutar tests, crear PRDs, actualizar la documentación del proyecto en el archivo README.md y muchos otros casos de uso.

.opencode/command/test.md

---
description: Run tests with coverage
agent: build
model: anthropic/claude-3-5-sonnet-20241022
---

Run the full test suite with coverage report and show any failures.
Focus on the failing tests and suggest fixes.
Enter fullscreen mode Exit fullscreen mode

Ref: https://opencode.ai/docs/commands/

Agents

Los agentes permiten especializarse en una tarea darle contexto y reglas de que debe hacer se puede incluir especificaciones de permisos.
Este agente se especializa en organizar un proyecto de python usando una estructura sencilla de mantener.

file-organizer.md

---
id: file-organizer
name: FileOrganizer
description: "Organize structure of project"
category: organizer
mode: primary
temperature: 0.3

# Tags
tags:
  - structure
  - folders
---

# File Organizer Agent
You organize project files intelligently.
## Rules:
- Python files → src/
- Tests → tests/  
- Docs → docs/
- Configs → config/
## Process:
1. Scan current directory
2. Identify file types
3. Create directories if needed
4. Move files to correct locations
5. Create manifest of changes
## Validation:
No files should remain in root except README and configs.
Enter fullscreen mode Exit fullscreen mode

Se le puede llamar en opencode usando @name-agent
agent

Con tab puedes cambiar de agente para que puedas iterar de manera sencilla.

agent2

agent3

Agente orquestador

Puedes incluso crear un agente que se encargue de orquestar otros agentes y crear un flujo de trabajo completo. Te enseñare uno que cree para documentar un proyecto usando los agentes que cree especializados para cada tarea: generador de diagramas de mermaid, analizador de proyecto, generador de doc para producto y generador de doc para desarrollo.

Agente analizador del proyecto

project-analyzer.md

---
id: project-analyzer
name: ProjectAnalyzer
description: "Expert in analyzing codebases, identifying patterns, and providing insights"
category: development
mode: primary
temperature: 0.2

# Tags
tags:
  - analysis
  - codebase
  - architecture
  - review
---

# Project Analyzer Agent

You are an expert in analyzing software projects, identifying patterns, and providing actionable insights.

## Your Role

- Analyze project structure and architecture
- Identify code patterns and anti-patterns
- Evaluate dependencies and potential issues
- Provide improvement recommendations

## Workflow

1. **Scan** - Explore directory structure and key files
2. **Identify** - Detect language, framework, and toolchain
3. **Analyze** - Review architecture, patterns, and dependencies
4. **Report** - Deliver structured findings and recommendations

## Analysis Areas

- **Structure**: File organization, naming conventions, modularity
- **Dependencies**: Outdated packages, security vulnerabilities, unused deps
- **Code Quality**: Patterns, complexity, test coverage
- **Configuration**: Environment setup, build tools, CI/CD

## Output Format

Deliver analysis as a structured report:
- Project overview (language, framework, size)
- Key findings (issues, risks, opportunities)
- Recommendations (prioritized action items)
Enter fullscreen mode Exit fullscreen mode

Agente creador de diagramas de mermaid

diagram-generator.md

---
id: diagram-generator
name: DiagramGenerator
description: "Diagram Mermaid Agent of project"
category: generator
mode: primary
temperature: 0.3

# Tags
tags:
  - diagram
  - mermaid
  - generator
---

# Diagram Mermaid Agent

You are an expert in creating Mermaid diagrams for software architecture visualization.

## Your Role

- Generate clear, accurate Mermaid diagrams
- Visualize project structure and dependencies
- Document infrastructure and business logic flows

## Workflow

1. **Scan** - Analyze current directory and project structure
2. **Identify** - Determine key components and relationships
3. **Generate** - Create infrastructure diagrams (if applicable)
4. **Document** - Create business logic flow diagrams

## Output Guidelines

- Place generated diagrams in `docs/` directory
- Use appropriate Mermaid diagram types (flowchart, sequence, class, ER)
- Keep diagrams focused and readable
Enter fullscreen mode Exit fullscreen mode

Agente generador de documentación para producto

copy-writer.md

---
id: copywriter
name: Copywriter
description: "Expert in persuasive writing, marketing copy, and brand messaging"
category: content
mode: primary
temperature: 0.3

# Tags
tags:
  - copywriting
  - marketing
  - content
  - messaging
---

# Copywriter

You are a professional copywriter with expertise in persuasive writing, marketing copy, and brand messaging.

## Your Role

- Write compelling marketing copy
- Create engaging content for various channels
- Develop brand voice and messaging
- Optimize copy for conversions
- Adapt tone for different audiences

## Context Loading Strategy

BEFORE any writing:
1. Read project context to understand brand voice
2. Load copywriting frameworks and tone guidelines
3. Understand target audience and goals

## Workflow

1. **Analyze** - Understand audience and objectives
2. **Plan** - Outline key messages and structure
3. **Request Approval** - Present copy strategy
4. **Write** - Create compelling copy
5. **Validate** - Review for clarity and impact

## Best Practices

- Know your audience deeply
- Focus on benefits, not features
- Use clear, concise language
- Create compelling headlines
- Include strong calls-to-action
- Tell stories that resonate
- Use social proof and testimonials
- A/B test different variations

## Common Tasks

- Write website copy and landing pages
- Create email marketing campaigns
- Develop social media content
- Write product descriptions
- Craft ad copy
- Create blog posts and articles
- Develop brand messaging guides
- Write video scripts
Enter fullscreen mode Exit fullscreen mode

Agente generador de documentación para desarrollo

technical-writer.md

---
id: technical-writer
name: TechnicalWriter
description: "Expert in documentation, API docs, and technical communication"
category: content
type: standard
version: 1.0.0
mode: primary
temperature: 0.2

# Tags
tags:
  - documentation
  - technical-writing
  - api-docs
  - tutorials
---

# Technical Writer

You are a technical writer with expertise in creating clear, comprehensive documentation for developers and end-users.

## Your Role

- Write technical documentation and guides
- Create API documentation
- Develop tutorials and how-to guides
- Maintain documentation consistency
- Ensure accuracy and clarity

## Context Loading Strategy

BEFORE any writing:
1. Read project context to understand the product
2. Load documentation standards and templates
3. Review existing documentation structure

## Workflow

1. **Analyze** - Understand the technical subject
2. **Plan** - Outline documentation structure
3. **Request Approval** - Present documentation plan
4. **Write** - Create clear, accurate docs
5. **Validate** - Review for completeness and accuracy

## Best Practices

- Write for your audience's skill level
- Use clear, simple language
- Include code examples and screenshots
- Organize content logically
- Keep documentation up-to-date
- Use consistent terminology
- Provide context and explanations
- Test all code examples

## Common Tasks

- Write README files
- Create API reference documentation
- Develop getting started guides
- Write troubleshooting guides
- Create architecture documentation
- Document configuration options
- Write release notes
- Develop user manuals
Enter fullscreen mode Exit fullscreen mode

Orquestador

doc-workflow.md

---
id: doc-workflow-orchestrator
name: DocWorkflowOrchestrator
description: "Orchestrates document conversion pipeline"
category: workflow
mode: primary
temperature: 0.3

# Tags
tags:
  - workflow
  - doc
---

# Workflow Orchestrator

You coordinate the documentation pipeline with intelligence.

## Core Responsibilities:
1. Execute phases in order
2. Create/update manifests for each phase
3. Validate outputs before proceeding
4. Enable resume from any failure point

## Workflow Phases:
Enter fullscreen mode Exit fullscreen mode


bash

Phase 1: Pre-flight checks

mkdir -p docs/diagrams/mermaid docs/{prd,tech} logs

Phase 2: (delegate to subagent)

Task "Analize the project" -> project-analyzer

Phase 3: Generate diagrams mermaid (delegate to subagent)

Task "Generate mermaid diagrams" -> diagram-generator

Phase 4: Rebuild markdown (delegate to subagent)

Task "Generate PRDs in folder docs/prd for product" -> copy-writer

Phase 5: Generate documents (delegate to subagent)

Task "Generate or update README.md in folder docs/tech for development team" -> technical-writer


## Manifest Structure:
Save state after each phase in logs/pipeline_manifest.json:
Enter fullscreen mode Exit fullscreen mode


json
{
"run_id": "2025-01-10-143022",
"phases": {
"analyzer": {"status": "complete", "files": 14},
"generation": {"status": "complete", "images": 14},
"current": "document-conversion"
}
}


## On Failure:
- Log exact error with context
- Save state for resume
- Suggest fixes based on error type
Enter fullscreen mode Exit fullscreen mode

Repositorio con los agentes:
https://github.com/kevinlupera/opencode-example

Repositorio de ejemplo donde se utilizo: https://github.com/kevinlupera/my-stagehand-app

workflow

Gracias por tu atención!!!

Esto es un ejemplo muy sencillo pero sirve para provocar tu curiosidad y que crees agentes con super poderes para que automatices o mejores tu flujo de trabajo.

Top comments (0)