Repository avatar
AI Tools
v1.3.2
active

cmd_op

io.github.karlmoriaty/cmd_op

The Office suite for AI agents: create, read, and edit Word, Excel, PowerPoint from one binary.

Documentation

cmd_op

office-command-operate · cmd_op

The Office suite built for AI agents.
Create, read, and edit Word, Excel, and PowerPoint from one self-contained binary —
deterministic JSON, a built-in renderer, and no Microsoft Office required.

1 binary  ·  3 formats  ·  350+ functions  ·  0 dependencies  ·  JSON everywhere

Release License npm PyPI Platforms Author

English · Deutsch · Français · 中文 · 日本語 · 한국어

The loop · Quick start · Why it's different · Capabilities · Showcase · AI agents · SDKs · Commands · Install


cmd_op gives any AI agent full control of .docx, .xlsx, and .pptx — from a chat, a script, or another program. One open-source binary (Apache-2.0) that runs headless on Linux and Windows, needs no Microsoft Office, and answers every command with deterministic JSON.

What sets it apart is that the agent can see. A built-in, high-fidelity rendering engine turns documents into HTML and PNG, so an agent can look at its own output, spot an overflowing title or an overlapping shape, and fix it — closing the render → look → fix loop without a human in between.

The loop

agent ──writes JSON──▶ cmd_op ──renders──▶ HTML / PNG
  ▲                    (1 binary)                  │
  └────────── sees the result, fixes, retries ─────┘

Every other Office library hands the agent a blind API. cmd_op gives it eyes: view html, view screenshot, and watch render the real layout, so mistakes get caught by the agent itself — in CI, in Docker, on a server with no display.

Quick start

# Linux
curl -fsSL https://raw.githubusercontent.com/karlmoriaty/office-command-operate/main/install.sh | bash

# Windows (PowerShell)
irm https://raw.githubusercontent.com/karlmoriaty/office-command-operate/main/install.ps1 | iex
cmd_op create deck.pptx

# Live preview → opens http://localhost:26315 and refreshes on every edit
cmd_op watch deck.pptx

# In a second terminal: every add / set / remove updates the browser instantly
cmd_op add deck.pptx / --type slide --prop title="Hello, World!"

That's the whole loop. Every add, set, or remove refreshes the preview in real time, so the browser becomes your feedback surface.

What makes it different


It can see

A built-in HTML / PNG renderer lets the agent inspect its own output and fix overflowing titles or overlapping shapes — headless, anywhere.


Deterministic JSON

Every command speaks the same stable schema with structured error codes. No regex-scraped logs, no screen parsing.


Path-based addressing

Every element has a stable path like /slide[1]/shape[2]. Agents navigate documents like a DOM — no XML namespaces.


Formulas that evaluate

350+ Excel functions run on write and pivot tables are aggregated on disk. Read final values with no Office round-trip.


Design once, fill many

merge replaces {{placeholders}} from JSON, so production code fills N reports from one designed layout.


One self-contained binary

The .NET runtime is embedded. No Office, no Python, no COM — just download, run, and call it from any language.

Everything below is a detail of these six ideas.

Core capabilities

Rendering engine — the agent's eyes

A from-scratch, high-fidelity HTML renderer ships inside the binary. It covers shapes, charts (trendlines, error bars, waterfall, candlestick, sparklines), equations (OMML → LaTeX, rendered with KaTeX), 3D .glb models via Three.js, morph transitions, slide zoom, and shape effects. Per-page PNG screenshots are produced by piping the rendered HTML through a headless browser.

cmd_op view deck.pptx html -o /tmp/deck.html       # standalone file, assets inlined
cmd_op view deck.pptx screenshot -o /tmp/deck.png  # --page 1-N for a range
cmd_op watch deck.pptx                             # http://localhost:26315

Without visualization, an agent generating slides is flying blind — it can read the DOM but can't tell whether the title overflows or two shapes overlap. Because rendering is built in, the loop works in CI, in Docker, and on a server with no display.

Formula & pivot engine

350+ Excel functions evaluate automatically on write — write =SUM(A1:A2), get the cell, and the value is already there. Covers spilling dynamic arrays (FILTER / SORT / UNIQUE / SEQUENCE / LET / LAMBDA / MAP), VLOOKUP / XLOOKUP / INDEX / MATCH, financial and bond math (XIRR / PRICE / YIELD / DURATION / COUPNUM), statistical distributions and regression (NORM.DIST / T.TEST / LINEST), plus date and text functions.

Pivot tables are written as native OOXML from a source range, so Excel opens the file already aggregated:

cmd_op add sales.xlsx '/Sheet1' --type pivottable \
  --prop source='Data!A1:E10000' --prop rows='Region,Category' \
  --prop cols=Quarter --prop values='Revenue:sum,Units:avg' \
  --prop showDataAs=percentOfTotal

Template merge — generate once, fill many

merge replaces {{key}} placeholders in .docx, .xlsx, or .pptx with JSON data — across paragraphs, table cells, shapes, headers, footers, and chart titles. The layout is designed once; production code fills it N times deterministically, with zero token cost per copy.

cmd_op merge invoice-template.docx out-001.docx --data '{"client":"Acme","total":"$5,200"}'
cmd_op merge q4-template.pptx q4-acme.pptx --data data.json

Round-trip dump — learn from existing documents

dump serializes a whole document — or any subtree (one paragraph, table, slide, worksheet, styles, numbering, theme, settings) — into replayable batch JSON; batch replays it.

cmd_op dump existing.docx -o blueprint.json            # whole document
cmd_op dump existing.docx /body/tbl[1] -o table.json   # any subtree
cmd_op dump existing.xlsx /Sheet1 -o sheet.json        # one worksheet
cmd_op batch new.docx --input blueprint.json

Resident mode & batch

For multi-step workflows, resident mode keeps the document in memory; batch mode applies many operations in one atomic pass.

# Resident mode — near-zero latency via named pipes
cmd_op open report.docx
cmd_op set report.docx /body/p[1]/r[1] --prop bold=true
cmd_op close report.docx

# Batch — atomic by default: any failed item rolls back the whole batch
cmd_op batch deck.pptx --commands '[{"op":"set","path":"/slide[1]/shape[1]","props":{"text":"Hi"}}]'

# Keep successful items even when others fail
cmd_op batch deck.pptx --input updates.json --best-effort --json

# Stop at the first failure instead of running the rest
cmd_op batch deck.pptx --input updates.json --stop-on-error --json

[!IMPORTANT] Reading the file with another tool? Flush first. cmd_op's own reads (get / query / view) always see the latest edits, but a live resident defers the disk write. Before python-docx, openpyxl, Word, a renderer, or an uploader reads the file, run cmd_op save report.docx (keeps the resident warm) or cmd_op close report.docx. A live resident also auto-flushes shortly after idle (adaptive 2–10 s). For pipelines that read after every command, set cmd_op_RESIDENT_FLUSH=each. Full model: docs → open / close.

One command instead of a library stack

Same slide: ~50 lines of python-pptx → one command
from pptx import Presentation
from pptx.util import Inches, Pt
prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[0])
title = slide.shapes.title
title.text = "Q4 Report"
# ... 45 more lines ...
prs.save('deck.pptx')
cmd_op add deck.pptx / --type slide --prop title="Q4 Report"

Three layers of control

Start simple, go deep only when needed.

LayerPurposeCommands
L1 · ReadSemantic views of contentview (text, annotated, outline, stats, issues, html, svg, screenshot)
L2 · DOMStructured element operationsget, query, set, add, remove, move, swap
L3 · Raw XMLDirect XPath access — the universal fallbackraw, raw-set, add-part, validate
# L1 — high-level views
cmd_op view report.docx annotated
cmd_op view budget.xlsx text --cols A,B,C --max-lines 50

# L2 — element-level operations
cmd_op query report.docx "run:contains(TODO)"
cmd_op add budget.xlsx / --type sheet --prop name="Q2 Report"
cmd_op move report.docx /body/p[5] --to /body --index 1

# L3 — raw XML when L2 isn't enough
cmd_op raw deck.pptx '/slide[1]'
cmd_op raw-set report.docx document \
  --xpath "//w:p[1]" --action append \
  --xml '<w:r><w:t>Injected text</w:t></w:r>'

Full capability index

Word (.docx) — i18n/RTL, runs, tables, styles, equations, diagrams, revisions, and more

Full i18n & RTL support (per-script font slots, per-script BCP-47 lang tags lang.latin/ea/cs, complex-script bold/italic/size, direction=rtl cascading through paragraph/run/section/table/style/header/footer/docDefaults, rtlGutter + pgBorders shorthand, locale-aware page numbering for Hindi/Arabic/Thai/CJK; create --locale ar-SA auto-enables RTL), paragraphs (framePr, tabs shorthand, char-based indents), runs (underline.color, position half-pts), tables (virtual column ops add/remove/move/copyfrom, hMerge), styles, textbox / shape (rotation, textDirection eaVert/vert270, gradient, shadow, opacity), headers/footers, images (PNG/JPG/GIF/SVG), equations (LaTeX input), diagrams (mermaid → native editable shapes, or any mermaid type as a full-fidelity PNG), comments, footnotes, watermarks, bookmarks, TOC, charts, hyperlinks, sections, form fields, content controls (SDT), fields (22 zero-param types + MERGEFIELD / REF / PAGEREF / SEQ / STYLEREF / DOCPROPERTY / IF), OLE objects, revisions / tracked changes (revision.type=ins|del|format|moveFrom|moveTo + revision.action=accept|reject, per-target /revision[@author=...] selector, tracked Find&Replace), page background color, document properties.

Excel (.xlsx) — formulas, pivots, slicers, conditional formatting, validation, and more

Cells (phonetic guide / furigana on add, Excel-UI --shift left|up on remove / shift=right|down on add), formulas (350+ built-in functions with auto-evaluation, spilling dynamic arrays with _xlfn. auto-prefix, financial / bond and statistical families, OFFSET/INDIRECT, defined-name formula bodies inlined at parse, formula-ref rewrite on row/col insert), sheets (visible/hidden/veryHidden, print margins, printTitleRows/Cols, RTL sheetView, cascade-aware sheet rename, empty-cell bloat filter on open), boolean and/or selectors (row[Salary>5000 and Region=EMEA]), tables, sort (sheet / range, multi-key, sidecar-aware), conditional formatting, charts (including box-whisker, pareto with auto-sort + cumulative-%, log axis), pivot tables (multi-field, date grouping, showDataAs, sort, grandTotals, subtotals, compact/outline/tabular layout, repeat item labels, blank rows, calculated fields, persistent labelFilter / topN filters, cache CoW + cross-pivot sharing), slicers, named ranges, data validation, images (PNG/JPG/GIF/SVG with dual-representation fallback), sparklines, comments (RTL), autofilter, shapes, OLE objects, CSV/TSV import, $Sheet:A1 cell addressing.

PowerPoint (.pptx) — animations, transitions, 3D models, SmartArt, zoom, and more

Slides (header/footer/date/slidenum toggles, hidden), shapes (pattern fill, blur effect, hyperlink tooltip + slide-jump links, highlight color on runs, slideMaster/slideLayout typed add/set/remove, arrow alias, effective.X + effective.X.src), images (PNG/JPG/GIF/SVG, fill modes: stretch/contain/cover/tile, brightness/contrast/glow/shadow, rotation, link + tooltip), tables (built-in PowerPoint style catalogue, virtual /col[C] get + swap/copyFrom, row/col Move/CopyFrom, fill/background alias), charts (pieOfPie, barOfPie, per-attr axisLine/gridline setters, series add/remove with theme palette, anchor=x,y,w,h shorthand), animations (15 emphasis + 16 exit template-backed presets, multi-effect chains, motion-path presets, repeat/restart/autoReverse, chart animations + chartBuild), transitions (morph + p14 + 12 p15 PowerPoint 2013+ presets), 3D models (.glb) (combined rotation=ax,ay,az), slide zoom, equations (LaTeX input), diagrams (mermaid flowchart / sequence → native editable shapes, or any mermaid type as a full-fidelity PNG), themes, connectors (from/to accept a full /slide[N]/shape[@name=Foo] path), video/audio (loop, autoStart), groups (link + tooltip; Get/Query/Add/Remove all descend into groups), notes (RTL, lang), comments (RTL, legacy + modern p188 threaded round-trip), SmartArt (round-trip via add-part + raw-set), OLE objects, placeholders (add/set by phType).


Showcase

Every document below was created entirely by AI agents through cmd_op —
no templates, no manual editing.

PowerPoint

cmd_op design presentation (PowerPoint)cmd_op business presentation (PowerPoint)cmd_op tech presentation (PowerPoint)
cmd_op space presentation (PowerPoint)cmd_op gaming presentation (PowerPoint)cmd_op creative presentation (PowerPoint)
More examples — Word documents and Excel spreadsheets

Word

cmd_op academic paper (Word)cmd_op project proposal (Word)cmd_op annual report (Word)

Excel

cmd_op budget tracker (Excel)cmd_op gradebook (Excel)cmd_op sales dashboard (Excel)

For AI agents

Three ways to wire cmd_op into an agent:

ApproachHow
Auto-install everythingcmd_op install — puts the binary on PATH, installs SKILL.md into every detected agent (Claude Code, Cursor, Windsurf, GitHub Copilot, Codex, and more), and can register the MCP server
Feed the skill filecurl -fsSL https://raw.githubusercontent.com/karlmoriaty/office-command-operate/main/SKILL.md — paste it into any agent's context
MCP servercmd_op mcp claude · cursor · vscode · lmstudio · opencode — all document operations exposed over JSON-RPC, no shell access needed. cmd_op mcp list shows registrations
Use any MCP client (generic stdio config)

If your client is not in the auto-register list, start the server with cmd_op mcp and paste this into its MCP configuration. cmd_op is also published to the official MCP registry.

{
  "mcpServers": {
    "cmd_op": {
      "command": "cmd_op",
      "args": ["mcp"]
    }
  }
}

No binary installed? Point the client at the npm package instead:

{
  "mcpServers": {
    "cmd_op": {
      "command": "npx",
      "args": ["-y", "cmd_op", "mcp"]
    }
  }
}
Manual skill install (if auto-detection misses your setup)
# Drop the skill file into Claude Code's skills directory
curl -fsSL https://raw.githubusercontent.com/karlmoriaty/office-command-operate/main/SKILL.md \
  -o ~/.claude/skills/cmd_op.md

For other agents, include the contents of SKILL.md in the system prompt or tool description.

Why agents thrive on it

Design choiceWhy it matters
Deterministic JSONEvery command supports --json with stable schemas — no regex scraping, no log parsing
Path-based addressingEvery element has a stable path (/slide[1]/shape[2]); agents navigate without touching XML namespaces (1-based indexes, element local names — not XPath)
Progressive complexityStart with read-only views (L1), escalate to DOM operations (L2), fall back to raw XML (L3) only when needed
Self-healing errorsvalidate, view issues, and structured error codes (not_found, invalid_value, unsupported_property, …) return suggestions and valid ranges so the agent corrects itself
Eyesview html, view screenshot, and watch render natively — the agent sees its output and fixes layout, even in CI, Docker, or a headless server
Computed values350+ Excel functions evaluate on write; pivot tables are aggregated on disk — agents read final values with no Office round-trip
Design once, fill manymerge replaces {{key}} placeholders from JSON, so production code fills N reports cheaply instead of regenerating layouts
Learn from samplesdump turns any existing document into replayable batch JSON; agents imitate human-authored layouts from a structured spec

JSON contract

Response shapes, error codes, and exit codes

Single element (get --json):

{"tag": "shape", "path": "/slide[1]/shape[1]", "attributes": {"name": "TextBox 1", "text": "Hello"}}

List of elements (query --json):

[
  {"tag": "paragraph", "path": "/body/p[1]", "attributes": {"style": "Heading1", "text": "Title"}},
  {"tag": "paragraph", "path": "/body/p[5]", "attributes": {"style": "Heading1", "text": "Summary"}}
]

Errors — non-zero exit with an actionable envelope:

{
  "success": false,
  "error": {
    "error": "Slide 50 not found (total: 8)",
    "code": "not_found",
    "suggestion": "Valid Slide index range: 1-8"
  }
}

Error codes: not_found, invalid_value, unsupported_property, invalid_path, unsupported_type, missing_property, file_not_found, file_locked, invalid_selector. Misspelled properties are auto-corrected with the closest match.

Mutations (set, add, remove, move, create with --json):

{"success": true, "path": "/slide[1]/shape[1]"}
Exit codeMeaning
0The operation landed
1It did not — the envelope carries error
2It ran with caveats: some property was dropped or a warning was raised. success may be true; read success / warnings[], not the exit code alone

Recovery loop — the agent inspects valid children and retries:

cmd_op get report.docx /body/p[99] --json   # → not_found + suggestion
cmd_op get report.docx /body --depth 1 --json  # → available children

SDKs

Thin resident-pipe clients — no per-call process spawn; the CLI is auto-provisioned when missing.

# Python — pip install cmd-op-sdk
import cmd_op

with cmd_op.create("deck.pptx") as doc:          # or cmd_op.open("deck.pptx")
    doc.send({"command": "add", "parent": "/", "type": "slide"})
    print(doc.send({"command": "get", "path": "/slide[1]"}))
// Node.js — npm install cmd-op-sdk
const oc = require("cmd-op-sdk");
const doc = await oc.create("deck.pptx");            // or oc.open("deck.pptx")
await doc.send({ command: "add", parent: "/", type: "slide" });
console.log(await doc.send({ command: "get", path: "/slide[1]" }));
await doc.close();

Both SDKs announce the CLI install rather than doing it silently. No SDK? Wrap the binary directly:

import json, subprocess
def cli(*args):
    return json.loads(subprocess.check_output(["cmd_op", *args, "--json"], text=True))
cli("create", "deck.pptx")

Recipes

Units & colors

TypeAccepted formatsExamples
Dimensionscm, in, pt, px, or raw EMU2cm, 1in, 72pt, 96px, 914400
ColorsHex, named, RGB, theme#FF0000, FF0000, red, rgb(255,0,0), accent1
Font sizesBare number or pt-suffixed14, 14pt, 10.5pt
Spacingpt, cm, in, or multiplier12pt, 0.5cm, 1.5x, 150%

Common patterns

# Replace all Heading1 text in a Word doc
cmd_op query report.docx "paragraph[style=Heading1]" --json | ...
cmd_op set report.docx /body/p[1]/r[1] --prop text="New Title"

# Export all slide content as JSON
cmd_op get deck.pptx / --depth 2 --json

# Bulk-update Excel cells
cmd_op batch budget.xlsx --input updates.json --json

# Import CSV data into an Excel sheet
cmd_op add budget.xlsx / --type sheet --prop name="Q1 Data"
cmd_op import budget.xlsx "/Q1 Data" sales.csv --header

# Template merge for batch reports
cmd_op merge invoice-template.docx invoice-001.docx --data '{"client":"Acme","total":"$5,200"}'

# Check document quality before delivery
cmd_op validate report.docx && cmd_op view report.docx issues --json

Self-healing end-to-end workflow

# 1. Create
cmd_op create report.pptx

# 2. Add content
cmd_op add report.pptx / --type slide --prop title="Q4 Results"
cmd_op add report.pptx '/slide[1]' --type shape \
  --prop text="Revenue: $4.2M" --prop x=2cm --prop y=5cm --prop size=28
cmd_op add report.pptx / --type slide --prop title="Details"
cmd_op add report.pptx '/slide[2]' --type shape \
  --prop text="Growth driven by new markets" --prop x=2cm --prop y=5cm

# 3. Verify
cmd_op view report.pptx outline
cmd_op validate report.pptx

# 4. Fix what the checks found
cmd_op view report.pptx issues --json
cmd_op set report.pptx '/slide[1]/shape[1]' --prop font=Arial

Built-in help

Don't guess property names — drill into the help:

cmd_op help pptx set              # all settable elements and properties
cmd_op help pptx set shape        # detail for one element type
cmd_op help docx query            # selector reference: attributes, :contains, :has(), etc.
cmd_op --help                     # full overview

Command reference

CommandDescription
createCreate a blank .docx, .xlsx, or .pptx (type from extension)
viewView content (modes: outline, text, annotated, stats (--page-count), issues, html, svg, screenshot, pdf (via exporter plugin), forms (via format-handler plugin)). docx supports --render auto|native|html.
load_skillPrint embedded SKILL.md content for a specialized skill (no install)
getGet element and children (--depth N, --json)
queryCSS-like query with boolean and/or, row-by-column-name (row[Salary>5000]), --find flag
setModify element properties; accepts selectors and Excel-native paths (parity with get/query), --find/--replace flags
addAdd element (or clone with --from <path>)
removeRemove an element
moveMove element (--to <parent>, --index N, --after <path>, --before <path>)
swapSwap two elements
validateValidate against OpenXML schema
view <file> issuesEnumerate document issues (text overflow, missing alt text, formula errors, ...)
batchMultiple operations in a single pass (stdin, --input, or --commands; atomic by default, --best-effort, --stop-on-error)
dumpSerialize a .docx, .pptx, or .xlsx into a replayable batch JSON (round-trip via batch); accepts a subtree path
refreshRecalculate TOC page numbers / PAGE / cross-references (.docx; Word backend on Windows, headless-HTML fallback)
pluginsList / inspect / lint installed plugins (extend to .doc, .hwpx, .pdf export via dump-reader / exporter / format-handler kinds)
mergeTemplate merge — replace {{key}} placeholders with JSON data
watchLive HTML preview in browser with auto-refresh
mcpStart MCP server for AI tool integration
rawView raw XML of a document part
raw-setModify raw XML via XPath
add-partAdd a new document part (header, chart, etc.)
openStart resident mode (keep document in memory)
closeSave and close resident mode
installInstall binary + skills + MCP (all, claude, cursor, etc.)
configGet or set configuration
help <format> <command>Built-in help (e.g. cmd_op help pptx set shape)

Comparison

cmd_opMicrosoft OfficeLibreOfficepython-docx / openpyxl
Open source & free✓ (Apache 2.0)✗ (paid license)✓✓
AI-native CLI + JSON✓✗✗✗
Zero install (single binary)✓✗✗✗ (Python + pip)
Call from any language✓ (CLI)✗ (COM/Add-in)✗ (UNO API)Python only
Path-based element access✓✗✗✗
Built-in agent-friendly renderer✓✗✗✗
Template merge across formats✓✗✗✗
Round-trip dump → batch JSON✓✗✗✗
Live preview on edit✓✗✗✗
Headless / CI✓✗Partial✓
Word + Excel + PowerPoint✓✓✓Separate libs

Installation

One binary, nothing else: the .NET runtime is embedded, and Office/Python/COM are not involved.

One-line installers

# Linux
curl -fsSL https://raw.githubusercontent.com/karlmoriaty/office-command-operate/main/install.sh | bash

# Windows (PowerShell)
irm https://raw.githubusercontent.com/karlmoriaty/office-command-operate/main/install.ps1 | iex

Package managers

npm install -g cmd_op   # Linux / Windows — fetches the native binary
scoop install cmd_op                # Windows

Manual download from GitHub Releases:

PlatformBinary
Linux x64cmd_op-linux-x64
Linux ARM64cmd_op-linux-arm64
Windows x64cmd_op-win-x64.exe
Windows ARM64cmd_op-win-arm64.exe

Verify with cmd_op --version.

Self-install from a downloaded binary (bare invocation also triggers it):

cmd_op install
cmd_op

Updates are checked automatically in the background. Disable with cmd_op config autoUpdate false, or skip a single run with cmd_op_SKIP_UPDATE=1. Configuration lives at ~/.cmd_op/config.json.

Documentation

Build from source

Requires the .NET 10 SDK for compilation only; the output is a self-contained native binary.

./build.sh

Tooling

  • Rust workspace (rust/README.md) — zero-dependency release checks (SHA256SUMS, CLI --version gate, formula conformance corpus) plus cmd_op-ooxml, a package inspector that answers inspect, text, verify and diff straight from the OOXML zip without a rendering engine.
  • tools/envelope-check — scenario-driven black-box runner for the --json envelope contract; CI drives the latest release asset through it on Linux and Windows.
  • tools/capability-index — typed catalog generated from schemas/help with a consistency audit and a documentation drift check (docs) covering both docs/reference element trees and the --prop keys used in this guide and SKILL.md; CI fails if the committed catalog or any guide drifts from the schemas.

License

Apache License 2.0 · © 2026 karlmoriaty

Bug reports and contributions are welcome on GitHub Issues.


If cmd_op is useful to you, give it a star — it helps others find the project.

Designed & built by karlmoriaty
GitHub · npm · PyPI · Releases · Issues
© 2026 karlmoriaty · Apache-2.0