Using OfficeCLI `--json` Output for AI Agent Workflows: Complete Technical Guide
OfficeCLI's --json flag returns a standardized envelope containing success, data, and warnings keys, enabling AI agents to parse document operations programmatically and recover from errors via structured suggestions.
The iOfficeAI/OfficeCLI repository provides a single-binary, cross-platform tool for manipulating Microsoft Office documents through the command line. When building autonomous AI agents that automate Word, Excel, or PowerPoint tasks, using OfficeCLI --json output for AI agent workflows provides a deterministic, machine-readable contract that eliminates parsing ambiguity and enables self-correcting behavior through schema discovery.
Understanding the JSON Envelope Architecture
All commands accept a --json flag that triggers structured output via the OutputFormatter.WrapEnvelope method in src/officecli/Core/OutputFormatter.cs. This method constructs a consistent top-level envelope containing three guaranteed keys:
success: A boolean indicating operation statusdata: The command-specific payload parsed as JSONwarnings: An optional array ofCliWarningobjects collected viaWarningContext
The implementation at lines 65–77 ensures type safety:
public static string WrapEnvelope(string dataJson, List<CliWarning>? warnings = null, bool success = true)
{
var envelope = new JsonObject { ["success"] = success };
try { envelope["data"] = JsonNode.Parse(dataJson); }
catch { envelope["data"] = dataJson; }
if (warnings is { Count: > 0 })
envelope["warnings"] = JsonSerializer.SerializeToNode(warnings, AppJsonContext.Default.ListCliWarning);
return envelope.ToJsonString(JsonOptions);
}
This envelope guarantees that AI agents can check .success before processing .data, regardless of the specific command executed.
Command-Level JSON Implementation
Each command handler receives a shared Option<bool> jsonOption that determines output formatting. In src/officecli/CommandBuilder.GetQuery.cs, the handler retrieves this value at lines 12–14:
var json = result.GetValue(jsonOption);
When json is true, commands call OutputFormatter.FormatNodes with OutputFormat.Json before wrapping the result. The get command implementation at lines 96–104 demonstrates this pattern:
if (json)
Console.WriteLine(OutputFormatter.WrapEnvelope(
OutputFormatter.FormatNodes(new List<DocumentNode> { node }, OutputFormat.Json)));
else
Console.WriteLine(OutputFormatter.FormatNode(node, OutputFormat.Text));
This pattern appears consistently across query, set, add, and remove commands, ensuring a uniform JSON contract throughout the CLI.
Structured Error Handling for Self-Healing Agents
When operations fail, OfficeCLI returns structured error objects within the envelope rather than unstructured text. This enables programmatic error recovery without regex parsing.
A failed operation returns success: false with additional diagnostic fields:
{
"success": false,
"error": "Unrecognized property 'colour'",
"code": "unsupported_property",
"suggestion": "Did you mean 'color'?"
}
Agents can inspect the code field to categorize failures (e.g., not_found, unsupported_property) and use the suggestion field to automatically correct parameters. For example, when an agent attempts to set a non-existent property, it can query the schema to discover valid alternatives, eliminating hard-coded assumptions about property names.
Schema-Driven Discovery with help --json
To avoid brittle hard-coding of property names, agents can query element-specific JSON schemas at runtime. The SchemaHelpLoader class in src/officecli/Help/SchemaHelpLoader.cs loads schema definitions embedded as assembly resources at lines 275–280:
using var stream = typeof(SchemaHelpLoader).Assembly.GetManifestResourceStream(resourceName);
Running officecli help <format> <element> --json (e.g., officecli help pptx shape --json) returns the complete schema for that element, including:
- Valid property names and their types
- Enumerated values for constrained fields
- Supported operations (
query,set,add)
This schema-driven approach allows agents to discover valid property names like color versus colour dynamically, enabling self-correcting workflows that adapt to schema changes without prompt engineering updates.
Practical Implementation Examples
Retrieving Document Elements
Extract a specific shape from a PowerPoint deck:
officecli get deck.pptx '/slide[1]/shape[1]' --depth 1 --json
The returned envelope includes document nodes with paths, tags, and attributes:
{
"success": true,
"data": {
"matches": 1,
"results": [
{
"path": "/slide[1]/shape[1]",
"tag": "shape",
"attributes": {
"name": "Title 1",
"text": "Q4 Report",
"font": "Arial",
"size": "24"
}
}
]
}
}
Querying with Predicates
Find all cells containing "Revenue" in an Excel workbook:
officecli query sales.xlsx 'cell:contains("Revenue")' --json
Self-Correcting Property Updates
Demonstrate error recovery:
# Attempt with invalid property name
officecli set deck.pptx '/slide[1]/shape[1]' --prop colour=red --json
# Returns error code; agent queries schema
officecli help pptx shape --json | jq '.properties | keys[]'
# Retry with correct property name
officecli set deck.pptx '/slide[1]/shape[1]' --prop color=red --json
Batch Operations with JSON Input
Execute multiple updates atomically:
cat > updates.json <<'EOF'
[
{ "op": "set", "path": "/slide[1]/shape[1]", "props": { "text": "Revenue ↑ 25%" } },
{ "op": "set", "path": "/slide[1]/shape[2]", "props": { "fill": "#00FF00" } }
]
EOF
officecli batch deck.pptx --input updates.json --json
Python SDK Integration
The Python SDK wraps the binary to provide native objects while preserving the JSON contract:
from officecli import Doc
with Doc("deck.pptx") as d:
slide = d.add("/", type="slide", title="Executive Summary")
print(slide.get_json()) # Returns parsed JSON envelope
Summary
- Consistent Envelope: Every command using
--jsonreturns a top-level envelope withsuccess,data, and optionalwarningskeys viaOutputFormatter.WrapEnvelopeinsrc/officecli/Core/OutputFormatter.cs. - Command Uniformity: The
jsonOptionflag is implemented consistently across all handlers insrc/officecli/CommandBuilder.GetQuery.cs, ensuring predictable behavior forget,query,set, and other operations. - Structured Errors: Failed operations return machine-readable error objects with
codeandsuggestionfields, enabling agents to implement self-healing logic without human intervention. - Runtime Schema Discovery: Agents can query
officecli help <format> <element> --jsonto discover valid properties dynamically viaSchemaHelpLoaderinsrc/officecli/Help/SchemaHelpLoader.cs, eliminating hard-coded dependencies. - Cross-Language Support: Thin SDKs for Python and Node.js parse the JSON envelope internally, allowing agents to work with native objects while maintaining the deterministic contract.
Frequently Asked Questions
What is the exact structure of OfficeCLI's JSON output?
Every command returns a JSON envelope containing three top-level keys: success (boolean), data (the command-specific result or error details), and warnings (array of optional caution messages). This structure is generated by OutputFormatter.WrapEnvelope in src/officecli/Core/OutputFormatter.cs and remains consistent across all document types and operations.
How can AI agents handle errors programmatically with --json?
When an operation fails, the envelope contains success: false and a structured error object with error (human-readable message), code (machine-readable category like not_found or unsupported_property), and suggestion (corrective hint). Agents can branch on the code value to implement automatic retries, parameter corrections, or escalation logic without parsing free-form text.
Can agents discover valid property names without hard-coding them?
Yes. By executing officecli help <format> <element> --json, agents retrieve the complete JSON schema for any document element (shapes, cells, paragraphs). The SchemaHelpLoader class loads these definitions from embedded resources in src/officecli/Help/SchemaHelpLoader.cs, exposing valid properties, enums, and supported operations. This enables dynamic discovery of property names like color versus fill at runtime.
Is the --json output format stable across Word, Excel, and PowerPoint?
Yes. The envelope structure (success, data, warnings) is identical across all document types. While the contents of the data field vary by command and file format (e.g., slide paths versus cell ranges), the wrapping envelope and error handling conventions remain consistent, allowing agents to use the same parsing logic regardless of whether they are manipulating .docx, .xlsx, or .pptx files.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →