How OfficeCLI Error Codes Enable Self-Healing Agent Workflows

OfficeCLI leverages standardized JSON-RPC 2.0 error codes to let automated agents detect, classify, and recover from failures without human intervention.

The iOfficeAI/OfficeCLI project implements a machine-readable error protocol that transforms runtime failures into structured remediation opportunities. By adopting the JSON-RPC 2.0 error model across its core server components, OfficeCLI provides deterministic signals that self-healing agents can act upon programmatically.

Understanding the JSON-RPC 2.0 Error Model in OfficeCLI

OfficeCLI structures every error response as a JSON envelope containing a numeric error code, a human-readable message, and optional metadata. This format originates in McpServer.cs, where the server constructs error payloads through the ErrorJson() helper method.

The four primary error codes map to distinct failure modes:

Code Meaning Source Location
-32600 Invalid Request — malformed JSON or illegal characters McpServer.cs line 95: ErrorJson(null, -32600, msg)
-32601 Method Not Found — requested RPC method does not exist McpServer.cs line 123: ErrorJson(id, -32601, …)
-32602 Invalid Params — missing or incorrectly typed parameters McpServer.cs line 207: ErrorJson(id, -32602, "Missing params")
-32603 Internal Error — unexpected exception during request handling McpServer.cs line 135: ErrorJson(id, -32603, $"Internal error: {ex.Message}")

These codes propagate through the ResidentServer layer, which wraps errors into response envelopes via MakeResponse(1, "", $"Error: …") at lines 913-917 of ResidentServer.cs. The CLI simultaneously writes messages to Console.Error for human users while preserving the structured JSON for automated consumers.

Mapping Error Codes to Agent Remediation Strategies

Self-healing agents interpret OfficeCLI error codes as decision triggers. Each code indicates a specific recovery path:

-32600: Input Validation Failure

Agents receiving this code should reject the request immediately and verify input encoding. The malformed payload cannot be salvaged; upstream correction is required.

-32601: Method Discovery Failure

Agents can fallback to default commands or query alternative tool registries. This error signals a capability mismatch rather than a runtime fault.

-32602: Parameter Recovery

Missing or invalid parameters enable the richest remediation opportunities. Agents may:

  • Auto-populate defaults from configuration schemas
  • Prompt users interactively for required values
  • Infer parameters from context or previous operations

-32603: Transient Internal Failure

Unexpected exceptions warrant retry logic with exponential back-off or failover to redundant service instances. This code distinguishes recoverable infrastructure issues from permanent logic errors.

Practical Implementation Examples

Triggering a JSON-RPC Error from a Plugin

// Inside a plugin command handler
if (string.IsNullOrEmpty(request.Args["path"]))
{
    // Missing required argument → return -32602
    return OfficeCli.CommandBuilder.MakeResponse(
        1, "", $"Error: {OfficeCli.Core.MsysPathHint.AugmentMessage("Missing 'path' argument")}");
}

The CommandBuilder.MakeResponse() method standardizes error formatting across all OfficeCLI commands, ensuring consistent envelope structure.

Python Agent Auto-Healing Missing Parameters

import json
import time
import requests

def call_officecli(payload):
    r = requests.post("http://localhost:1234/rpc", json=payload)
    resp = r.json()
    
    if resp.get("error"):
        code = resp["error"]["code"]
        if code == -32602:  # Missing params

            # Insert sensible default and retry

            payload["params"]["path"] = "./default.pptx"
            time.sleep(0.5)  # Simple back-off

            return call_officecli(payload)
    
    return resp

# Initial (faulty) request without required path parameter

result = call_officecli({"jsonrpc": "2.0", "method": "render", "params": {}})
print(json.dumps(result, indent=2))

Go Agent Handling Internal Errors with Failover

func handleError(err jsonrpcError) {
    switch err.Code {
    case -32603:
        // Try alternative rendering engine
        switchBackend("chromium")
        retry()
    default:
        log.Fatalf("Unrecoverable error: %s", err.Message)
    }
}

Key Source Files for Error Handling

File Responsibility
src/officecli/McpServer.cs JSON-RPC server emitting error envelopes with standardized codes
src/officecli/ResidentServer.cs Wraps errors for resident-mode operation, mirrors non-resident path
src/officecli/Program.cs Configures Console.Error redirection for human-readable output
src/officecli/CommandBuilder.cs Generates final CLI responses including error formatting via MakeResponse

Cross-Language and Cross-Plugin Consistency

Because OfficeCLI error codes derive from the JSON-RPC 2.0 specification rather than ad-hoc conventions, the same agent logic applies uniformly across:

  • All OfficeCLI subcommands and plugins
  • Language SDKs that re-export the error envelope
  • Third-party integrations consuming the RPC interface

This standardization eliminates special-case handling and reduces agent complexity.

Summary

  • OfficeCLI error codes follow JSON-RPC 2.0, providing predictable, machine-parseable failure signals
  • Four core codes (-32600 through -32603) cover malformed requests, missing methods, invalid parameters, and internal exceptions
  • Self-healing agents map each code to specific remediation: validation, fallback, auto-completion, or retry with failover
  • McpServer.cs and ResidentServer.cs implement the error generation and propagation pipeline
  • Standardized envelopes enable portable agent logic across commands, plugins, and language bindings

Frequently Asked Questions

How does OfficeCLI format error responses for automated consumption?

OfficeCLI returns JSON-RPC 2.0 error objects containing code, message, and optional data fields. The McpServer.cs file constructs these envelopes via ErrorJson(), and ResidentServer.cs wraps them for resident-mode operations. Automated agents parse this structure without scraping human-readable console output.

Can agents distinguish between permanent errors and retryable failures?

Yes. OfficeCLI uses -32603 exclusively for unexpected internal exceptions, signaling that retry or failover may succeed. Codes -32600, -32601, and -32602 indicate client-side or request-level issues that will not resolve through repetition and require request modification.

Where does OfficeCLI write errors for human users versus machines?

Human-oriented messages route through Console.Error as configured in Program.cs. Machine-oriented JSON envelopes travel through the RPC response channel. The ResidentServer.cs layer maintains both pathways simultaneously, ensuring no information loss for either audience.

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:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →