> For the complete documentation index, see [llms.txt](https://stemma.sh/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://stemma.sh/docs/reference/mcp-advanced.md). Agents can also search and read this documentation through its [MCP server](https://stemma.sh/docs/~gitbook/mcp).

# MCP advanced

Use this page when the default five-tool profile cannot express a required expert operation. Start with the [core reference](https://stemma.sh/docs/reference/mcp.md) for the normal inspect, execute, verify, and save workflow.

Enable the complete 31-tool surface at server startup:

```bash
STEMMA_MCP_PROFILE=advanced npx -y @stemma-sh/mcp
```

Unknown profile values fail startup. Advanced tools use the same typed engine, workspace boundary, artifact identities, and validation gates as the core profile.

## Read and navigate

| Tool                                               | Purpose                                                                                                                                                                                                                                                       |
| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `open_docx(path)`                                  | Open a workspace-confined source and return a handle, compact index, and input identity.                                                                                                                                                                      |
| `read_outline` / `read_index`                      | Read the current structural outline or lightweight block index.                                                                                                                                                                                               |
| `read_window(from_block_id,to_block_id,format)`    | Render an inclusive block range as text, Markdown, or HTML.                                                                                                                                                                                                   |
| `read_markdown` / `read_text` / `read_html`        | Read whole-document projections.                                                                                                                                                                                                                              |
| `read_block(block_id)`                             | Read one block's text spans, handles, guards, marks, and opaque anchors.                                                                                                                                                                                      |
| `read_redline` / `read_accepted` / `read_rejected` | Read current, accept-all, or reject-all projections without mutation.                                                                                                                                                                                         |
| `find(pattern)`                                    | Locate matching text and return bounded excerpts plus block ids; matches in links, textboxes, controls, and headers and footers are included, with the same fields as `inspect_docx` [`find`](https://stemma.sh/docs/reference/mcp.md#inspecting-a-document). |
| `get_section(heading_id)`                          | Read one heading subtree.                                                                                                                                                                                                                                     |
| `read_styles`                                      | Read authored document defaults and styles.                                                                                                                                                                                                                   |
| `list_revisions`                                   | List current revisions and their content-derived ids.                                                                                                                                                                                                         |

Re-read a block after editing it. Span handles and guards become stale after a write to the same block. Revision ids are content-derived: a revision whose own content is untouched keeps its id across save, reopen, and the resolution of other revisions (see [id durability](https://stemma.sh/docs/reference/cli.md#extract)). Among changes that look exactly alike (same kind, author, date and text), ids are kept by Stemma's own save, reopen and resolutions; after another editor changes the file, lookalikes are numbered again by document order, so re-read ids after any edit made outside Stemma. Read them from `list_revisions` or a receipt, never from raw XML; the one exception is a change inside a textbox, whose id is its own `w:id`.

## Edit

| Tool                 | Purpose                                                                                                      |
| -------------------- | ------------------------------------------------------------------------------------------------------------ |
| `replace_text`       | Tracked replacement of one exact or normalized phrase, including text inside existing redlines.              |
| `replace_text_batch` | Ordered replacement worklist with per-item outcomes and optional throwaway preview. Deliberately non-atomic. |
| `replace_all`        | Tracked find and replace across body paragraphs.                                                             |
| `apply_edit`         | Apply one atomic v4 transaction, tracked by default.                                                         |
| `apply_batch`        | Preview or apply one v4 transaction.                                                                         |
| `check_edit`         | Run the same validation as `apply_edit` against a throwaway clone.                                           |

`replace_text` defaults to one expected match. A mismatch reports the matches needed to disambiguate. `match_mode:"normalize_ws"` normalizes supported whitespace and quote classes for matching while preserving the replacement text verbatim.

```
replace_text     {"doc_id": ..., "old": "30 days", "new": "45 days", "author": "Approved Reviewer"}
```

## Review, resolve, and export

| Tool                                | Purpose                                                                        |
| ----------------------------------- | ------------------------------------------------------------------------------ |
| `accept_changes` / `reject_changes` | Resolve changes by current id, author, block range, or all.                    |
| `review_session`                    | Audit everything changed since open, including untouched proof and validation. |
| `audit_docx`                        | Produce the same audit for any two workspace-confined files.                   |
| `compare_docx`                      | Commit a create-new redline from base and target files.                        |
| `validate_docx`                     | Run package and OOXML validation.                                              |
| `save_docx`                         | Validate and commit an open document to a new path.                            |

An empty resolution selection is an error. Accept keeps the proposed state; reject restores the prior state. Verify by content because both actions remove revision markers.

## The edit transaction (v4)

```json
{
  "ops": [
    {
      "op": "replace",
      "target": "p_3",
      "expect": "strict liability",
      "content": {
        "type": "paragraph",
        "content": [
          {
            "type": "text",
            "text": "The Supplier's liability is limited to negligence."
          }
        ]
      }
    }
  ],
  "revision": {
    "author": "J. Osei"
  },
  "summary": "Soften liability clause"
}
```

A transaction is atomic. Targets are block ids from the current document. `expect`, `guard`, or `semantic_hash` provides optimistic concurrency.

Operation families include:

* block and span replacement, insertion, deletion, and movement;
* run, paragraph, cell, row, table, and section formatting;
* comments and footnotes or endnotes;
* images, equations, bookmarks, cross-references, and numbering;
* styles and content controls;
* page setup, headers, and footers.

The complete catalog is published as the [v4 operation reference](https://stemma.sh/docs/reference/operations.md): every operation, its accepted fields, and canonical shapes, generated from the engine's parser table. At runtime, retrieve the same catalog through `inspect_docx` with `query:"operations"`; the running server's answer is authoritative for its own version and additionally lists the MCP edge fields (such as image `path`).

## Path-backed images

Image paths are workspace-confined. Source identity is registered only after a mutation applies. Preview and rejected edits register nothing.

Two startup limits count source bytes before base64 expansion. Setting a value to `0` disables that limit:

| Variable                           | Scope                               | Default          |
| ---------------------------------- | ----------------------------------- | ---------------- |
| `STEMMA_MCP_MAX_IMAGE_BYTES`       | Each image path                     | `20971520` bytes |
| `STEMMA_MCP_MAX_IMAGE_TOTAL_BYTES` | Image-path bytes in one transaction | `52428800` bytes |

Exceeding a limit returns `artifact_source_too_large`. Reduce or split the input. Only the host operator should raise process-wide limits.

## Refusal vocabulary

| Refusal                            | Meaning                                                                                                                                                                                                                                                                                                | Do instead                                                                                                                       |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- |
| `StaleEdit`                        | The addressed content changed after inspection.                                                                                                                                                                                                                                                        | Re-read and rebuild the operation.                                                                                               |
| `NoOpEdit`                         | The replacement equals the current text.                                                                                                                                                                                                                                                               | Re-read and correct the intended text.                                                                                           |
| `MatchCountMismatch`               | The replacement found a different number of matches.                                                                                                                                                                                                                                                   | Narrow the text, scope it, or correct the expected count.                                                                        |
| `AmbiguousAnchorAfterMove`         | The plan anchors on a block moved earlier in the transaction.                                                                                                                                                                                                                                          | Use the moved id named by the error or a stable neighbor.                                                                        |
| `OpaqueDestroyed`                  | The operation would silently drop an opaque object.                                                                                                                                                                                                                                                    | Edit around it or use a structure-aware operation.                                                                               |
| `AuthorLabelCollision`             | The Word author label was already present when the document was opened.                                                                                                                                                                                                                                | If the user intended the existing reviewer group, pass the explicit override. Otherwise ask the user to choose a separate label. |
| `CommentAnchorOverlapsDeleted`     | A comment anchor falls on deleted text (wire code `AnchorNotFound`).                                                                                                                                                                                                                                   | Anchor on retained text or resolve the deletion first.                                                                           |
| `ParagraphContainsTrackedSegments` | The requested span operation lacks a safe coordinate space (wire code `UnsupportedEdit`).                                                                                                                                                                                                              | Resolve the paragraph or use `replace_text`.                                                                                     |
| `StyleNotFound`                    | A requested style does not exist (wire code `AnchorNotFound`).                                                                                                                                                                                                                                         | Read current styles or create the style in the same transaction.                                                                 |
| `PrefixDuplicatesLabel`            | The content starts with the paragraph's own label, which would print twice, or with a different label on automatic list numbering.                                                                                                                                                                     | Send the body only; the message names the content to send. Change list numbering with `set_numbering`.                           |
| `ReplaceTextInsideInlineObjects`   | The phrase also stands in a link or content control whose text cannot be replaced (a content-locked, non-text or placeholder control, pending changes inside it, or a replacement that would empty it); `unreached_matches` names each object and why (wire code `UnsupportedEdit` on `replace_text`). | Unlock, fill or resolve that object first, or narrow the scope, then replace.                                                    |
| `ExpectCrossesInlineObject`        | `expect` runs across a field, image, break, or other inline object the operation cannot span (wire code `UnsupportedEdit`).                                                                                                                                                                            | Give text on one side of the named object.                                                                                       |
| `TableColumnHeaderMismatch`        | A column op's `expect_header` is not the text of that column's top cell (wire code `UnsupportedEdit`).                                                                                                                                                                                                 | Take the index from the refusal, which lists every column with its header.                                                       |
| `NoteBodyLineCountMismatch`        | An `edit_note` body has a different number of lines than the note has paragraphs (wire code `UnsupportedEdit`).                                                                                                                                                                                        | Give one line per paragraph, in order, repeating a line to keep it.                                                              |
| `BlockedJoin`                      | A selective resolution would join paragraphs across blocks that another pending revision removes (wire code `UnsupportedEdit`; `context` lists `required_revision_ids`).                                                                                                                               | Resolve the listed revisions together.                                                                                           |
| `doc_id_required`                  | The call omitted `doc_id` while no document or several documents are open; `open_doc_ids` lists them.                                                                                                                                                                                                  | Pass the `doc_id` that `open_docx` returned.                                                                                     |
| `InvalidRange`                     | A revision selector matched nothing.                                                                                                                                                                                                                                                                   | Re-read revisions and correct the selector.                                                                                      |
| `FormatRevisionConflict`           | The target already carries a pending formatting revision from another proposal.                                                                                                                                                                                                                        | Resolve that revision, leave it pending, or comment; the refusal names which.                                                    |
| `AmbiguousFormatTarget`            | `expect` matched more than one eligible span in the block.                                                                                                                                                                                                                                             | Lengthen `expect` until it matches one span.                                                                                     |

### Typed formatting refusals

`FormatRevisionConflict` and `AmbiguousFormatTarget` answer with data, not prose. The response names the target and its tracking state, the invariant that would break, the conflicting revision and its author when one exists, and `mutation`, which is `none` for every refused transaction: nothing was written, so no retry is needed to undo anything.

`allowed_actions` carries filled-in action templates rather than vocabulary words: every field the engine can determine is already populated, so the caller supplies only the session envelope, the acting author, and free content such as a comment body.

```json
{
  "code": "format_revision_conflict",
  "target": {"block_id": "p_6", "text": "$150", "tracking_status": "inserted"},
  "existing_revision": {"revision_id": 880725669, "kind": "format_run", "author": "Round1Reviewer"},
  "invariant": "a second independently resolvable run-format revision cannot be preserved",
  "allowed_actions": [
    {"action": "reject_changes", "selector": {"by": "by_ids", "revision_ids": [880725669]}},
    {"action": "leave_pending"},
    {"action": "comment_create", "target": "p_6", "expect": "$150"}
  ],
  "mutation": "none"
}
```

`allowed_actions` is guidance, not permission. Stemma never resolves a revision, converts a tracked edit to direct formatting, or creates a comment on its own; choosing among them stays the caller's decision.

`AuthorLabelCollision` is an attribution-confirmation refusal, not an identity or authentication check. Word author values are free-form display labels, and Word groups revisions that carry the same label. The refusal response includes the label, the current pending-revision count, the open-time scope, two explicit actions, and `mutation: "none"`.

```json
{
  "code": "AuthorLabelCollision",
  "status": "confirmation_required",
  "author_label": "J. Osei",
  "existing_revision_count": 12,
  "existing_scope": "present_when_document_opened",
  "mutation": "none",
  "actions": [
    {"action": "continue_existing_label", "allow_existing_author": true},
    {"action": "use_separate_label"}
  ]
}
```

The `allow_existing_author` argument on mutating tools is a per-call assertion that deliberately continues the existing Word reviewer group (it is never a transaction field):

```
apply_edit  {"doc_id": ...,
             "transaction": {"ops": [{"op": "delete", "target": "p_7"}],
                             "revision": {"author": "J. Osei"}},
             "allow_existing_author": true}
```

Successful mutation and preview receipts record `author_label_policy` as `continue_existing` when that assertion was supplied, otherwise `require_confirmation_on_collision`. Direct materialization records `not_applicable_direct` because it creates no Word revisions.

Never invent a new author label merely to clear the refusal. If the existing label was not explicit in the user's instruction or another approved source, surface the choice between continuing that group and supplying a separate, user-chosen label.

On text nodes, `marks` takes an array of marks such as `[{"type":"bold"}]`; a plain mark may also be its bare name (`["bold"]`), and an unknown name is refused with the valid ones. The grammar is specified under [content nodes](https://stemma.sh/docs/reference/operations.md#content-nodes). On `set_format`, `marks` is a tri-state patch object. An omitted property is left unchanged, `true` turns it on, and `false` turns it off, so `{"bold": false}` is how formatting is removed:

```json
{"op": "set_format", "target": "p_6", "expect": "the fee", "marks": {"bold": true, "italic": false}}
```

The older on-only array form is still accepted on `set_format` for compatibility, but a request carrying both forms is refused, and an empty or no-effect patch fails loudly rather than reporting a write that changed nothing. Span replacement takes plain text; use a whole-paragraph replacement for mark changes.

## Recipes

Every output path below must be new.

### Flatten a redline

```
open_docx        {"path": "draft-redline.docx"}
accept_changes   {"doc_id": ..., "selector": {"by": "all"}}
validate_docx    {"doc_id": ...}
save_docx        {"doc_id": ..., "path": "final.docx"}
```

Use `reject_changes` instead when the proposed state should be discarded.

### Resolve one author

```
open_docx        {"path": "grant-proposal.docx"}
list_revisions   {"doc_id": ...}
accept_changes   {"doc_id": ..., "selector": {"by": "by_author", "author": "L. Marsh"}}
validate_docx    {"doc_id": ...}
save_docx        {"doc_id": ..., "path": "grant-proposal-round2.docx"}
```

List revisions again before saving and confirm that only the intended reviewer's changes were resolved.

### Compare two files

```
compare_docx  {"base_path": "as-sent.docx",
               "target_path": "as-returned.docx",
               "out_path": "what-they-changed.docx",
               "author": "Approved Reviewer"}
```

Reject-all must reconstruct the base reading. Accept-all must reconstruct the target reading. The response keeps `change_count` as the number of semantic differences, reports pending Word carriers separately as `revision_count`, and attributes import normalization under `base_diagnostics` or `target_diagnostics`.

### Negotiation round

For a mixed accept, reject, and counterproposal task:

1. Open the document and list current revisions.
2. Accept and reject only explicit current ids.
3. Add the counterproposal under the user-chosen author label.
4. Read the accepted projection.
5. Run `review_session` or `validate_docx`.
6. Save to a new path.

Do not reuse revision ids from a previous session, hide new work under an existing reviewer group without confirmation, or end with unsaved in-memory state.

## Related

* [MCP core reference](https://stemma.sh/docs/reference/mcp.md)
* [Read model reference](https://stemma.sh/docs/reference/read-model.md)
* [Use Stemma with an agent](https://stemma.sh/docs/guides/use-with-an-agent.md)
* [Troubleshooting](https://stemma.sh/docs/help/troubleshooting.md)
* [Filesystem and artifact boundary](https://stemma.sh/docs/reference/mcp.md#filesystem-and-artifact-boundary)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://stemma.sh/docs/reference/mcp-advanced.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
