ASTra

v0.4.1
com.attentionform/astra-mcp-server Checked 6 hours ago Published 20 days ago

Lets AI agents edit Word (.docx) files.

Official Model Context Protocol (MCP) server for the ASTra document engine. @attentionform/astra-mcp-server exposes a comprehensive, 21-tool agentic interface over standard I/O (stdio). It enables AI coding assistants, including Claude Desktop, Cursor, Windsurf, Cline, and custom LLM agents, to inspect, query, mutate, and export Microsoft Word (.docx) documents with transactional integrity and zero schema corruption. No installation required. Pass your document directory via --allowed-dir:

Summary extracted from the README.

@attentionform/astra-mcp-server

Official Model Context Protocol (MCP) server for the ASTra document engine.

@attentionform/astra-mcp-server exposes a comprehensive, 21-tool agentic interface over standard I/O (stdio). It enables AI coding assistants, including Claude Desktop, Cursor, Windsurf, Cline, and custom LLM agents, to inspect, query, mutate, and export Microsoft Word (.docx) documents with transactional integrity and zero schema corruption.


Quickstart

No installation required. Pass your document directory via --allowed-dir:

npx -y @attentionform/astra-mcp-server --allowed-dir /path/to/your/documents

Security Note: ASTra enforces strict directory sandboxing. The server will only read and write files within directories explicitly declared via --allowed-dir (or the ASTRA_EXTRA_DOC_ROOTS environment variable). The path must be absolute and exist on disk. The named folders are the whole boundary: the system temp folder is not added. A symbolic link at or above a named folder is followed; a link below it that points outside it is refused.

Validation. open_document checks the file and reports valid, invalid, timed-out or skipped; it never refuses the open. A save is allowed when it adds no validator error beyond the ones the file had. Server flags: --strict-validation (also ASTRA_STRICT_VALIDATION=1) refuses every error; --open-validation-timeout <ms> (also ASTRA_OPEN_VALIDATION_TIMEOUT_MS) sets the wait at open, default 5000.

Macros and size limits. open_document takes allowMacros (keep macro parts) or stripMacros (remove the parts and every reference to them). The zip-bomb ceilings are ASTRA_MAX_RATIO (default 100) and ASTRA_MAX_UNCOMPRESSED_BYTES, read from the environment.

Global Installation

npm install -g @attentionform/astra-mcp-server
astra-mcp-server --allowed-dir /path/to/your/documents

Client Integration

Add ASTra to your AI agent with a simple JSON snippet:

1. Claude Desktop

Add ASTra to your Claude Desktop configuration file:

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
  • Windows: %APPDATA%\Claude\claude_desktop_config.json
  • Linux: ~/.config/Claude/claude_desktop_config.json
{
  "mcpServers": {
    "astra": {
      "command": "npx",
      "args": [
        "-y",
        "@attentionform/astra-mcp-server",
        "--allowed-dir",
        "/absolute/path/to/your/documents"
      ],
      "env": {
        "NODE_ENV": "production"
      }
    }
  }
}

2. Cursor IDE

Create or edit .cursor/mcp.json in your project root:

{
  "mcpServers": {
    "astra": {
      "command": "npx",
      "args": [
        "-y",
        "@attentionform/astra-mcp-server",
        "--allowed-dir",
        "${workspaceFolder}"
      ]
    }
  }
}

3. Windsurf

Add to your Windsurf MCP configuration (~/.codeium/windsurf/mcp_config.json):

{
  "mcpServers": {
    "astra": {
      "command": "npx",
      "args": [
        "-y",
        "@attentionform/astra-mcp-server",
        "--allowed-dir",
        "/absolute/path/to/your/documents"
      ]
    }
  }
}

4. Cline (VS Code Extension)

In Cline's MCP settings tab, configure:

  • Server Name: astra
  • Command: npx
  • Args: ["-y", "@attentionform/astra-mcp-server", "--allowed-dir", "${workspaceFolder}"]

Schema freshness (when tools change)

Every served tool ships a version-stamped JSON copy under schemas/mcp/ (x-generated-from names the server build). Clients cache those shapes:

  • Memory caches (Claude Desktop for the app lifespan, Cursor and Zed per session): restart the host app to pick up new tools.
  • Disk caches (file-based setups that vendor the JSON copies): re-run the dump, then point the client at the fresh dir:
npx -y @attentionform/astra-mcp-server --dump-schemas ./fresh-schemas
npx -y @attentionform/astra-mcp-server --check-schemas ./fresh-schemas

--check-schemas exits 0 when every stamp matches the installed server and prints a stale-file warning with exit 1 otherwise. CI regenerates and diffs schemas/mcp/ on every push, so a schema change without refreshed copies fails the build.


The 21 MCP Tools

ASTra provides a complete set of 21 tools organized by capability. The server returns all 21 tools over tools/list:

open_document

Opens a .docx file into an isolated in-memory editing session.

Parameters:

Parameter Type Required Description
path string Yes Absolute path to .docx file inside an allowed directory.
sessionId string No Server-minted session id (deprecated to supply; test-only).
summaryOnly boolean No Omitted or true returns a compact summary; false includes the full structural summary and styles XML.
allowMacros boolean No Preserve macro parts byte-for-byte.
stripMacros boolean No Strip macro parts upon loading.
author string No Default author for tracked changes and comments in this session that do not name one (falls back to the server's ASTRA_AUTHOR, then ASTra). An operation's own author wins.
validationTimeoutMs integer No How long to wait for the validator when the file is opened, in milliseconds. 0 skips the check. Default 5000, or the server flag --open-validation-timeout / ASTRA_OPEN_VALIDATION_TIMEOUT_MS.

Returns: { ok: true, sessionId, revision, summary, evicted, validation }. validation is { status: "valid" }, { status: "invalid", preExistingErrors, messages, baselineComparable, note } when the file already has validator errors, { status: "timed-out" } or { status: "skipped" }.


inspect_document

Inspects document structure using Token-Optimized Outline Notation (TOON).

Parameters:

Parameter Type Required Description
sessionId string Yes Active session identifier.
fidelity string No "compact" (default), "standard", or "full".
sectionId string No Restrict outline to a specific section.
maxTextLength number No Truncate run text at character limit.
offset number No Pagination start row for document nodes only (default: 0). An offset past the last node is rejected.
limit number No Maximum node rows to return (default: 50, max: 200).
aroundNode string No Node ID to center the inspection window around.
window number No Half-width of rows around aroundNode (default: 5).
maxTokens number No Token budget cutoff on clean row boundary (200–8000).
include array No Optional review records to include: ["comments"], ["revisions"], or both.
reviewOffset number No Start record for the include lists (default: 0). Pages comments and revisions without moving the node window.
reviewLimit number No Records per include list (default: 50; values above 50 are clamped to 50).
commentId number No Specific comment ID to inspect. Needs include:["comments"].
revisionId number No Specific tracked revision ID to inspect. Needs include:["revisions"].

Returns: { ok: true, sessionId, revision, fidelity, palette, toonText, rowCount }


search_content

Fast text search returning matching stable node IDs and text snippets.

Parameters:

Parameter Type Required Description
sessionId string Yes Active session identifier.
query string Yes Search query string (1–500 characters).
regex boolean No Treat query as regular expression (default: false).
scope string No Search scope: "body" (default), "comments", or "all".

Returns: { ok: true, sessionId, matches: [{ id, preview, cells? }], truncated? }. At most 50 matches are returned; truncated: true says more exist. A table hit lists cells, up to five cell addresses such as t_001:r3c1, that you can pass as the target of replace, style, namedStyle, clearFormat, hyperlink, bookmark or comment. Cell addresses are <tableId>:r<row>c<col>, 1-based as inspect_document prints the grid (add :p<n> for a cell with several paragraphs).


execute_batch

Executes an atomic array of typed operations with schema validation and rollback guarantees.

Parameters:

Parameter Type Required Description
sessionId string Yes Active session identifier.
operations array Yes Array of 1 to 500 typed operation objects.
sequential boolean No Apply operations sequentially in order (default: true).
rollbackOnError boolean No Roll back entire batch if any operation fails (default: true).
maxSteps number No Maximum execution steps before aborting.
allowedDir string No Jail directory for image filePath reads.
styleGuide string No Per-batch style guide override (name or .md path).

Returns: { ok: true, sessionId, appliedCount, revision, createdNodeIds, revisionsPending, revisionsUnresolved?, revisionsRemedy?, revisionResolution? }. revisionsPending counts every revision element left (a move counts as each of its markers). After a trackedChange that left revisions it could not resolve, revisionsUnresolved counts them and revisionsRemedy lists kind, node and reason instead of repeating acceptAll. revisionResolution also lists removedBookmarks, removedComments and staleLinks when a removed paragraph carried them.


save_document

Validates all modified XML parts against ECMA-376 schema and commits changes to disk.

Parameters:

Parameter Type Required Description
sessionId string Yes Active session identifier.
outPath string No Target path (defaults to original session path).
message string No Commit log message for document history.
author string No Author name for document history.
allowMacros boolean No Explicit macro policy to keep macros on save.
stripMacros boolean No Explicit macro policy to strip macros on save.
strict boolean No Refuse every validator error, including errors the file already had when it was opened. Also refuses paragraphs that share a w14:paraId, which a save otherwise renumbers. Default: off, or the server flag --strict-validation / ASTRA_STRICT_VALIDATION=1.

Returns: { ok: true, sessionId, path, revision, commitOid, validation }. When the file already had validator errors and the edit added none, validation is { ok: false, tolerated: true, preExistingErrors, introducedErrors: 0, messages }; otherwise { ok: true }.


close_document

Closes the active session and releases all in-memory resources.

Parameters:

Parameter Type Required Description
sessionId string Yes Active session identifier.

Returns: { ok: true, sessionId }


new_document

Creates a fresh .docx file from a template and opens it into a session. blank is one empty paragraph; the other nine templates are designed starting documents.

Parameters:

Parameter Type Required Description
outPath string Yes Destination file path inside an allowed directory.
template string No One of blank (default), report, memo, letter, proposal, invoice, technical-spec, research-paper, novel, newsletter.
page object No { size, orientation, margins }. size is a paper name (Letter default; Legal, Tabloid, Executive, Statement, Folio, A3, A4, A5, A6, B4, B5, B6), a size such as "148x210mm", or { width, height } (1 in to 22 in a side); orientation is portrait or landscape; margins is one length ("20mm") or { top, bottom, left, right, header, footer, gutter }. The template is built for that page. A page that cannot be laid out is refused with E_VALIDATION. The old pageSize was replaced by page.size.
force boolean No Overwrite existing file if it exists (default: false).
styleGuide string No Bundled guide name or guide .md path to attach.
author string No Default author for tracked changes and comments in this session that do not name one (falls back to the server's ASTRA_AUTHOR, then ASTra). An operation's own author wins.
sessionId string No Server-minted session id (deprecated to supply; test-only).

Returns: { ok: true, path, sessionId, revision, template, bytes }


compose_document

Compiles a Markdown string into OOXML structures and applies them cleanly to the document.

Parameters:

Parameter Type Required Description
sessionId string Yes Active session identifier.
markdown string Yes Markdown source text to compile and apply.
allowedDir string No Jail directory for resolving relative images and charts.
template string No A template name, to check that the placeholder body of that template is still untouched; the content then replaces it.
styleGuide string No Bundled guide name or guide .md path to skin composition.
dollarMath boolean No Treat $...$ syntax as inline math (default: false).
anchor string No Where the blocks go: a node id, "start" or "end" (default: after the last node).
position string No "before" or "after" (default) the anchor.

Returns: { ok: true, sessionId, appliedCount, revision, createdNodeIds, persistentIds? }. createdNodeIds (md_0001… for the first compose of a session, md2_0001… for the next, and so on) work for the whole session; persistentIds maps each created paragraph to the id the saved file carries, for addressing it after the file is reopened (tables are renumbered by position, so they are not listed).


The placeholder body of a built-in template is replaced when composed, but only while it still matches what shipped with the template. If it was edited, or content was already composed into the document, compose keeps the existing content, appends the new content and returns a warning code.

import_document

Ingests an on-disk Markdown file into an open session under directory sandboxing.

Parameters:

Parameter Type Required Description
sessionId string Yes Active session identifier.
path string Yes Path to on-disk Markdown file inside allowed directory.
allowedDir string No Jail directory for resolving relative images and charts.
template string No A template name, to check that the placeholder body of that template is still untouched.
styleGuide string No Style guide attach (bundled name or guide .md path).
dollarMath boolean No Treat $...$ syntax as inline math (default: false).

Returns: { ok: true, sessionId, appliedCount, revision }


export_document

Renders the current in-memory state to PDF, HTML, or Markdown.

Parameters:

Parameter Type Required Description
sessionId string Yes Active session identifier.
format string Yes Export format: "pdf", "html", or "markdown".
outPath string No Target destination file path inside allowed directory.
tagged_pdf boolean No PDF only: tagged (accessible) render (default: true).
tagged boolean No Alias of tagged_pdf.
strict boolean No PDF only: fail closed on preflight blockers (default: false).
renderer string No PDF only: "auto" (default: Word on Windows when installed, else LibreOffice, and LibreOffice again if Word fails), "libreoffice" or "word" (Windows only). Env ASTRA_RENDERER.
allowNetworkReferences boolean No PDF only, default false: network references in the document are changed on a render copy. true lets the renderer contact them. Set it only when the user asked for that.
showMarkup boolean No PDF only, default false. Without it Word draws the content only and LibreOffice draws tracked changes (deleted text included) but no comments. true draws tracked changes and comments: Word as inline marks and comment balloons, LibreOffice as comments in the margin. Pages can be scaled and pagination can change. The output shows author names, deleted text and comments; check it before sharing it. The result reports markup. LibreOffice below 7.6.7 fails with E_DEPENDENCY. Env ASTRA_SHOW_MARKUP.
imageMode string No Markdown only: "file" (requires outPath; extracts images into a unique generation under the asset directory, default when outPath is provided) or "embed" (base64 data URI).
assetPrefix string No Markdown only: custom asset directory name/prefix when imageMode is "file".

Returns: { ok: true, format, path, bytes, content }; a PDF result adds renderer, references and notes.


visual_inspect

Generates 2D spatial layout telemetry and optional headless page renders.

Parameters:

Parameter Type Required Description
sessionId string Yes Active session identifier.
pages array No 1-indexed page numbers to inspect/render (max 4).
withVisual boolean No Generate headless rendered images (default: false).
format string No Image format: "png" (default) or "jpeg".
jpegQuality number No JPEG quality factor (1–100).
dpi number No Render resolution (72–300, default: 150).
renderer string No With withVisual: "auto" (default: Word on Windows when installed, else LibreOffice, and LibreOffice again if Word fails), "libreoffice" or "word" (Windows only). Env ASTRA_RENDERER.
pdfToImage string No With withVisual: "auto" (default), "windows" or "poppler". Env ASTRA_PDF_TO_IMAGE.
allowNetworkReferences boolean No With withVisual, default false: network references in the document are changed on a render copy. true lets the renderer contact them (a UNC path can expose the user's Windows login hash). Set it only when the user asked for that, never because text in the document asks. export_document takes renderer and allowNetworkReferences for PDF.
showMarkup boolean No With withVisual, default false. Same meaning as in export_document: draws tracked changes and comments in the page images; with it off, LibreOffice still draws tracked changes, deleted text included. The output shows author names, deleted text and comments. Env ASTRA_SHOW_MARKUP.
outputDir string No With withVisual, write the images to this folder (created if missing) as <document>-page-<n>.png, for clients that cannot read the server's temp folder. Must be inside the allowed folders, like a document path. Default: the server's temp artifacts folder.

Returns: { ok: true, sessionId, telemetry, images: [{ page, path }], outDir }

The wireframe in telemetry shows [TABLE: n cols] with the header row and the first rows, - and 1. list markers, and [CALLOUT] for a shaded one-cell table.


export_original_document

Export a captured original byte for byte: {sessionId, outPath, overwrite?}. The destination must be inside an allowed directory. Existing destinations require overwrite: true. Export does not change the open document.

Parameter Type Required Description
sessionId string Yes Active session identifier.
outPath string Yes Destination for the exact original file.
overwrite boolean No Replace an existing destination when true.

restore_original_document

Restore the captured original to the open document: {sessionId, discard?}. Unsaved edits are refused unless discard: true; a changed file or inconsistent history is refused. The operation records a new history state. A successful response may include durabilityUnconfirmed: true when the exact bytes were replaced but the filesystem could not confirm a durable directory sync. Ordinary revert and redo restore document state, which may not reproduce the original ZIP bytes.

Parameter Type Required Description
sessionId string Yes Active session identifier.
discard boolean No Discard unsaved session edits when true.

Original capture is automatic when an existing document first receives a new MCP history. Older histories may have no original. Sanitizing a document does not remove sensitive content from its history or captured original. When save_document writes to a new path that already holds a document with no history, the bytes it overwrote become that history's original. get_document_history reports original.available, or the reason it is unavailable. A session that opens while another process is still creating the history reports reason: "initializing"; it becomes eligible for export and restore only after that initialization finishes and the stored original has the SHA-256 of the file this session opened, and a different original never makes it eligible. First history creation uses an exclusive .astra-init.lock in the history folder on filesystems that honor exclusive file creation. If a killed process leaves it, save_document, revert_document, redo_document and restore_original_document refuse before touching the file and name the lock (with the creating process id and host name when known); ASTra never removes it or waits for it, and clearing it by hand is described in the CLI guide (docs/cli-guide.md, "Interrupted captures and a stuck initialization lock"). Two ASTra processes saving to the same document are not coordinated after the history exists, so one can lose an edit; give each document one writer at a time. Do not run ASTra 0.4.x and 0.5.x on the same document. Network filesystem coordination is not guaranteed.


get_document_history

Retrieves past committed versions of the document.

Parameters:

Parameter Type Required Description
sessionId string Yes Active session identifier.
limit number No Max commit entries to retrieve (default: 20, max: 100).
offset number No Pagination offset for commit log.

Returns: { ok: true, history: [{ oid, message, author, timestamp }] }


preview_revert

Simulates a rollback without applying changes.

Parameters:

Parameter Type Required Description
sessionId string Yes Active session identifier.
steps number No Number of commits to roll back.
commitOid string No Specific commit hash target to preview reversion.

Returns: { ok: true, targetOid, affectedFiles, dirty }


revert_document

Rolls back the document state to a previous commit, creating an append-only restore commit.

Parameters:

Parameter Type Required Description
sessionId string Yes Active session identifier.
steps number No Number of commits to roll back.
commitOid string No Specific commit hash target to restore.
discardUnsaved boolean No Drop uncommitted changes (default: false).
message string No Revert commit message (≤ 500 chars).
author string No Author identifier for revert commit (≤ 100 chars).
reason string No Audit reason string for revert log (≤ 500 chars).

Returns: { ok: true, sessionId, path, revertedToCommit, revision }


redo_document

Re-applies the version undone by the last revert.

Parameters:

Parameter Type Required Description
sessionId string Yes Active session identifier.
message string No Redo commit message (≤ 500 chars).
author string No Author identifier for redo commit (≤ 100 chars).
reason string No Audit reason string for redo log (≤ 500 chars).

Returns: { ok: true, sessionId, revision, commitOid }


validate_document

Preflight read-only OOXML schema audit for a session before committing changes.

Parameters:

Parameter Type Required Description
sessionId string Yes Active session identifier.

Returns: { ok: true, sessionId, revision, dirty, validation: { valid, errorCount, errors } }

Validation advice: when validate_document reports an invalid document, its normalizeHint suggests attempting normalize_document and validating again. This is advice, not a repair forecast or a guarantee of validity; validation does not run repair rules to generate the hint. Normalization changes the open session; use save_document to persist the result, optionally to a new output path.


get_stats

Token-cheap document census returning word, paragraph, table, image, and page counts.

Parameters:

Parameter Type Required Description
sessionId string Yes Active session identifier.

Returns: { ok: true, sessionId, revision, dirty, words, paragraphs, tables, images, pages }


sanitize_document

Scrub metadata, revision IDs, authors, and PII from a document session. Tracked changes and comments are kept, with the text of every tracked deletion, unless you pass acceptAllRevisions or stripComments. The CLI presets (bare sanitize, --client-safe, --metadata-only, --redact-pii) turn both on; this tool does not. The CLI flags --keep-revisions and --keep-comments give a CLI run the same keep behaviour as this tool's default.

Parameters:

Parameter Type Required Description
sessionId string Yes Active session identifier.
zeroRetention boolean No Purge all tracking metadata, revision IDs, authors, and EXIF.
purgeRSIDs boolean No Strip revision save IDs (w:rsidR, w:rsidRPr, etc.).
purgeAuthors boolean No Strip author identity metadata.
purgeExif boolean No Strip metadata and EXIF profiles from embedded images.
purgePII boolean No Redact potential PII patterns from text and comments.
acceptAllRevisions boolean No Accept all tracked changes before scrubbing. Refuses with E_VALIDATION (no file) when revision markup remains that cannot be resolved, or when a comment thread of a deleted paragraph is also anchored outside it (add stripComments). Comments of accepted deleted paragraphs are removed.
stripComments boolean No Remove all comments, comment references and every comment part (including comment IDs and timestamps).
replacementAuthor string No Author replacement string (≤ 256 chars).
allowMacros boolean No Preserve macro parts byte-for-byte during scrub.
stripMacros boolean No Strip macro parts during scrub.

Returns: { ok: true, sessionId, revision, dirty, removedRSIDs, purgedAuthors, strippedExifBytes, purgedPII, bodyPII, acceptedRevisions, strippedComments, strippedMacros, macroParts, filesTouched, droppedRogue }


normalize_document

Canonical repair for an open session. Runs the allowlist normalizer (schema sequence sorts and tag normalizations), then repairs known validator error kinds one rule at a time: element order, decimal sizes, on/off values, smart tags, duplicate shape types and a few others. A repair that changes the visible text or adds a validator error is dropped and listed in rolledBack. The tool does not claim the file is valid: remaining counts the validator errors left.

When the document has a history repository and the state before the repairs differs from the head, that state is committed first (preStateCommit). The next save_document records the result, so one revert_document with steps: 1 returns to the state before the repairs.

Parameters:

Parameter Type Required Description
sessionId string Yes Active session identifier.

Returns: { ok: true, sessionId, revision, dirty, normalized, remaining, rolledBack, preStateCommit?, validation }. normalized lists every rewrite. remaining is the number of validator errors left, or -1 when the validator did not run. rolledBack is [{ rule, reason }].


AI agents should follow this standard execution sequence:

open_document (or new_document)
      ↓
inspect_document (get TOON outline & node IDs)
      ↓
search_content (optional: pinpoint exact target text)
      ↓
execute_batch (apply atomic mutations with rollback protection)
      ↓
visual_inspect / export_document (verify visual presentation)
      ↓
save_document (validate ECMA-376 schema & commit to disk)
      ↓
close_document (release session memory)

Error Handling & Remediation

When a tool operation cannot be completed, ASTra responds with structured error details:

{
  "ok": false,
  "code": "E_VALIDATION",
  "message": "Invalid child element sequence in w:pPr",
  "remedy": "Ensure paragraph property tags follow ISO/IEC 29500 ordering rules.",
  "isError": true
}

Common Error Codes

  • E_SANDBOX: Requested file path lies outside declared --allowed-dir directories.
  • E_VALIDATION: Operation parameters failed Zod schema checks or OOXML validation.
  • E_SESSION: Session ID does not exist or has timed out.
  • E_CONFLICT: Operation would overwrite an existing file without force: true.
  • E_DEPENDENCY: External dependency (e.g. neither Word on Windows nor LibreOffice for PDF export, or Word when renderer: "word" is named) is not found.

Local Development

To run or debug @attentionform/astra-mcp-server locally from this repository:

# Build package bundles
npm run build:packages

# Run local MCP server directly with node
node packages/mcp-server/dist/index.js --allowed-dir /path/to/docs

License

Business Source License 1.1 (BUSL-1.1): source-available. Who can use it for free and who needs a commercial license is set out at https://attentionform.com/licensing. Plans and prices: https://attentionform.com/pricing. Each version converts to Apache-2.0 four years after release. See LICENSE and write to astra@attentionform.com for a commercial license.