> 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.md). Agents can also search and read this documentation through its [MCP server](https://stemma.sh/docs/~gitbook/mcp).

# MCP core

Use this page to look up the default five-tool MCP contract. For installation and a first edit, start with [Use Stemma with an agent](https://stemma.sh/docs/guides/use-with-an-agent.md).

The default `core` profile exposes:

```
open_docx -> inspect_docx -> execute_plan -> verify_docx -> save_docx
```

Set `STEMMA_MCP_PROFILE=advanced` only when a task needs an expert escape hatch. The complete 31-tool surface is in the [advanced reference](https://stemma.sh/docs/reference/mcp-advanced.md). Unknown profile values fail startup.

## Tools

| Tool                               | Purpose                                                                                                                                                                                                                               |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `open_docx(path, task?, task_id?)` | Open one workspace-confined source. Returns `doc_id`, exact `input_artifact`, import `diagnostics`, and the first compact index page. The first task target may declare a complete multi-file task; later targets name its `task_id`. |
| `inspect_docx(doc_id, ...)`        | Locate and read bounded document content, revisions, styles, notes, projections, or operation schemas.                                                                                                                                |
| `execute_plan(...)`                | Preview or apply one transaction, replacement worklist, revision selection, or two-file comparison.                                                                                                                                   |
| `verify_docx(...)`                 | Audit an open session or a before/after pair before delivery.                                                                                                                                                                         |
| `save_docx(doc_id, path)`          | Validate and commit an open document to a new path.                                                                                                                                                                                   |

While exactly one document is open, `doc_id` may be omitted from any call that needs a document: the call is about that document, so a file can be opened and queried in the same turn. With no document or several open, such a call is refused with `doc_id_required` and the `open_doc_ids`. A named `doc_id` is always used as given, and a two-file comparison or a `verify_docx` of a before/after pair never takes the open document.

Every successful object response and structured error includes `server_version`. Tagged binaries report `version+g<12-character-commit>`.

`open_docx` also returns `diagnostics` and `document_protection` (null when absent). Protection reports the edit mode, enforcement flag, and credential presence only, never credential material. Stemma does not enforce document protection; enforced protection produces an import warning. The caller must decide whether programmatic editing is appropriate for its workflow. Successful import does not imply that a host application permits every review operation.

## Golden path

For an ordinary single-document edit, open with the existing input `path` alone; omit `task` and `task_id`. Supply the new output path only to `save_docx`. Task declarations are optional bounded multi-document delivery contracts, not required initialization. An existing task binding must not be bypassed or broadened.

1. Call `open_docx(path)`. Keep the returned `doc_id` and exact input identity.
2. Use `inspect_docx` to find relevant content, then inspect the exact block.
3. Submit an explicit plan to `execute_plan` with `preview:true`.
4. Resolve every refusal, then submit the same plan with `preview:false`.
5. Call `verify_docx({doc_id})` and inspect every reported section.
6. Call `save_docx(doc_id, path)` with a new output path. Save reruns the session audit, serializes, checks the bytes with the package gate, and commits create-new. Only a package-gate error refuses the save. The receipt's `verdict.status` is `pass`, or `needs_review` when the audit found changes it cannot explain; act on it before delivering.

A complete preview reports `apply_ready:true`. Do not rediscover or reformulate the plan between preview and apply unless the document state or intended scope changed.

## Multi-document task delivery

When success depends on several outputs, declare the complete task on the first task-bearing `open_docx`. The declaration fixes every read-only input, target, and exact-count replacement before any task mutation. Task-bound worklist items must name a matching `effect_id`; other mutation shapes are refused. Earlier target saves remain non-deliverable task state. The last target save emits a create-once complete or partial manifest.

The manifest carries checkable evidence, trusting Stemma emitted it. It is unsigned and cannot prove the caller declared everything the human intended. See [Verify a multi-document task delivery](https://stemma.sh/docs/guides/verify-task-delivery.md) for the wire examples, partial semantics, offline command, and trust limits.

## Inspecting a document

`open_docx` returns the first 16 rows of a compact index. Each row contains a stable block id, role, bounded text preview, and tracking status. Use `index_has_more` and `index_next_offset` when structural navigation requires another page.

Prefer targeted `inspect_docx` queries:

| Query                             | Use it for                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `find`                            | Locate wording without reading every block. Pass `patterns` with up to eight known phrases to batch them in one request; each pattern, including a zero-match pattern, returns its own exact totals and paging. Each match says where it hit in `matched_in`: `text`, or `hyperlink`, `textbox`, `content_control`, `form_field` or `image_alt` with the `anchor` that edits it. A table match lists its matching cells, each with the `block_id` of the paragraph holding the match (null, with `match_spans_paragraphs:true`, when the match runs across two) and all of the cell's `block_ids`. Header and footer matches are listed under `story_matches`, one entry per part with the `header_part` or `footer_part` an edit names. |
| `block`                           | Read one exact paragraph, table locator set, guard, or formatting projection.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `window`                          | Read an inclusive range of block ids.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `document`                        | Page through the extended-Markdown document projection.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `revisions`                       | List current pending revisions, optionally filtered by author, kind, or block range.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `styles`                          | Inspect authored style state.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `notes`                           | Read editable footnote and endnote rows.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `comments`                        | Read every comment: `id`, `author`, `date`, `text`, `resolved`, and the thread position (`parent_id`, with the raw `parent_para_id`). The `id` is the `parent_comment_id` that `comment_reply` takes; the fields are the same as `comments` in [`stemma read`](https://stemma.sh/docs/reference/cli.md#read).                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `headers_footers`                 | Discover authored header/footer part names, story kinds, block ids, text and opaque field anchors before `edit_header`/`edit_footer`. Page with `offset`/`limit` (default 8, maximum 64); select `pattern:"<part_name>"` and `block_id` for exact detail, optionally `detail:"formatting"` and table `cell_offset`/`cell_limit`. Block ids are story-local; an ambiguous id requires a part selection. Synthesized blank stories have no editable package part and are excluded.                                                                                                                                                                                                                                                         |
| `nested_form_fields`              | Discover legacy fields inside opaque body controls, with positional addresses, containing-block hashes, instructions, cached results and paragraph context. Page with `offset`/`limit` (default 8, maximum 64). Names may repeat. Use `set_block_form_text` for a FORMTEXT result, not the enclosing control's first-text fill.                                                                                                                                                                                                                                                                                                                                                                                                          |
| `redline`, `accepted`, `rejected` | Read the current, accept-all, or reject-all projection.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `operations`                      | Retrieve the parser-derived transaction vocabulary and examples.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |

Find results are locators, not substitutes for exact reads. Inspect a returned block id before editing it. Request `detail:"formatting"` only when complete run spans, marks, and style properties are needed. The shapes these reads project are the engine's read model, documented field by field in the [read model reference](https://stemma.sh/docs/reference/read-model.md).

A block read lists the paragraph's opaque `anchors`. A drawing anchor carries its `size_emu` (`{cx, cy}`), and a textbox also its `textbox_text`, so a resize or a textbox edit starts without a second read.

Reads are explicitly bounded. Find returns at most 16 matches by default. Document pages default to 16 top-level blocks. Table reads return paged cell locators rather than an unbounded aggregate body.

## Executing a plan

`execute_plan` accepts four plan shapes:

| Shape                  | Behavior                                                                      |
| ---------------------- | ----------------------------------------------------------------------------- |
| v4 transaction         | Atomic. Every operation applies or none do.                                   |
| `replacement_worklist` | Ordered literal replacements with per-item outcomes. Deliberately non-atomic. |
| revision selection     | Accepts or rejects the explicit current revision selection.                   |
| `comparison`           | Produces a tracked redline from base and target paths.                        |

A mutation receipt's `changed_blocks` rows carry each block's `text`, the redline reading with pending deletions included. A paragraph that carries tracked changes also has `accepted_text`, what it reads once they are accepted: check that against the intended sentence.

For a replacement worklist:

* use an integer `expected_matches` or `replace_all:true`, never both;
* use `match_mode:"exact"` or `match_mode:"normalize_ws"`;
* preview first;
* reissue only refused items after correcting them;
* scope by block id when the intended text is not unique;
* text inside a hyperlink's display text or a content control's value is replaced there too; an item whose text stands in a control that cannot be edited (content-locked, a drop-down or date, showing its placeholder) refuses, listing each one with its reason in `unreached_matches`.

The omitted replacement scope covers top-level and table-cell paragraphs. Preview runs the ordered worklist against a throwaway snapshot, including the effect of earlier successful items, without changing the live document.

For a two-file comparison, omit `doc_id` and pass `comparison:{base_path,target_path,out_path,author?}` with `preview:false`.

## Verification

`verify_docx({doc_id})` audits the open session before delivery. `save_docx` recomputes the same audit and reports it in the receipt (`audit_binding` and `verdict`). A declared task refuses a non-deliverable audit before the destination exists, because its manifest certifies a passing audit. The producer-neutral form audits any before/after pair. A deliverable result should report:

* no unexpected direct delta;
* no untouched-scope violations;
* every pre-existing revision in its intended disposition: `untouched`, or `edited_inside` when the delivery's own tracked changes are stacked inside it (rejecting them restores it; it counts as an expected change), or `resolved` by a resolution the session made. `modified` (changed without a covering tracked change) is always unexpected;
* `validator.new_issue_count: 0`.

`baseline_validator` reports findings that already existed when the source was opened. Unchanged baseline findings must be disclosed, but they are not new regressions.

An audit pass is not proof that the requested field was edited or that every Word consumer will render the result identically. The untouched proof checks canonical block fidelity; package validation checks structural constraints. Session review uses shared block identities, while file-pair auditing uses native insertion evidence and conservative baseline positions rather than inferring document lineage from content similarity.

Image resize and alt-text changes are inherently direct. They are accounted for only when the remaining paragraph and drawing content is unchanged; an unrelated formatting or drawing change does not receive an image exemption.

Audit lists return 16 rows by default and 64 at most. Use `detail`, `offset`, and `limit` to retrieve all continuation pages.

## Filesystem and artifact boundary

The MCP server confines every filesystem path to one root, selected once at startup. `--workspace-root PATH` takes precedence, followed by `STEMMA_MCP_WORKSPACE_ROOT`, then Claude Code's `CLAUDE_PROJECT_DIR`. If none is present, the canonical startup directory is used with a compatibility warning. A present but invalid higher-priority setting fails rather than falling through. Startup also fails if the selected root is not a directory or cannot be represented exactly in UTF-8 artifact receipts.

Relative paths resolve under the root. Absolute paths must still resolve inside it. Existing source symlinks are canonicalized, so a symlink that escapes the root is refused.

Every output commit is create-new:

* an existing destination is refused;
* a destination that aliases a consumed input is refused;
* there is no overwrite flag or per-call override;
* bytes are validated and staged in the destination directory;
* commit does not clobber a path created concurrently;
* committed bytes are read back and checked by byte length and SHA-256.

An input artifact identity has this shape:

```json
{
  "role": "input_docx",
  "supplied_path": "draft.docx",
  "resolved_path": "/workspace/draft.docx",
  "digest": {
    "algorithm": "sha256",
    "hex": "<64 lowercase hex characters>"
  },
  "bytes": 12345
}
```

An output artifact adds the collision policy and disposition:

```json
{
  "identity": {
    "role": "output_redline",
    "supplied_path": "result.docx",
    "resolved_path": "/workspace/result.docx",
    "digest": {
      "algorithm": "sha256",
      "hex": "<64 lowercase hex characters>"
    },
    "bytes": 23456
  },
  "collision_policy": "create_new",
  "disposition": "created"
}
```

Artifact identities contain absolute paths and exact-byte hashes. Treat them as document-sensitive metadata.

This boundary protects against ordinary caller mistakes and failed writes. It does not protect against a hostile same-user process racing paths, storage corruption, or power loss.

Stable artifact failure codes:

| Code                             | Meaning                                                                       |
| -------------------------------- | ----------------------------------------------------------------------------- |
| `artifact_outside_workspace`     | A path resolves outside the configured root.                                  |
| `artifact_output_exists`         | The create-new destination already exists.                                    |
| `artifact_protected_source`      | The destination aliases a protected input.                                    |
| `artifact_source_too_large`      | A path-backed image exceeds a configured limit.                               |
| `artifact_read_failed`           | A source cannot be resolved, represented, opened, identified, or read safely. |
| `artifact_commit_failed`         | Staging, commit, or post-commit verification failed.                          |
| `artifact_session_state_missing` | A live document lost protected source state and must be reopened.             |

## Refusal vocabulary

| Refusal                                | Safe next action                                                                                                                                                                                         |
| -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Stale guard or expected text           | Re-read the block and rebuild the plan.                                                                                                                                                                  |
| Match-count mismatch                   | Narrow or scope the replacement, or correct the expected count.                                                                                                                                          |
| Existing author-label collision        | If the user intended the existing label, continue that Word reviewer group by passing `allow_existing_author: true`. Otherwise ask the user for a separate label; never invent one to clear the refusal. |
| Opaque content would be destroyed      | Edit around the opaque object or choose a structure-aware operation.                                                                                                                                     |
| Empty revision selection               | Re-read the current revision list and correct the selector.                                                                                                                                              |
| Existing output                        | Choose a new output path.                                                                                                                                                                                |
| Task declaration mismatch              | Reissue the exact declared replacement, or edit the document outside a task. The declaration cannot be widened.                                                                                          |
| Unknown or already-applied `effect_id` | Use a pending effect declared for that target; do not restate a completed effect.                                                                                                                        |
| Undeclarable task plan shape           | Use a declaration-matched replacement worklist, or leave task mode for broader editing.                                                                                                                  |

No refusal should be converted into apparent success. See [Troubleshooting](https://stemma.sh/docs/help/troubleshooting.md) for symptom-first recovery and the [advanced refusal table](https://stemma.sh/docs/reference/mcp-advanced.md#refusal-vocabulary) for stable engine names.

## Session rules

* Re-read a block after any edit that can invalidate its guards.
* Scope edits to the content the instruction actually denotes.
* Preview before applying.
* Verify before saving.
* Save to a new path. Unsaved in-memory edits are not durable.
* Treat artifact identities and receipts as document-sensitive metadata.

## Related

* [Use Stemma with an agent](https://stemma.sh/docs/guides/use-with-an-agent.md)
* [MCP advanced reference](https://stemma.sh/docs/reference/mcp-advanced.md)
* [CLI approved-worklist contract](https://stemma.sh/docs/reference/cli.md#apply)
* [Stability policy](https://stemma.sh/docs/understand-the-model/stability.md)


---

# 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.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.
