Skip to content

[Epic] MCP as a bidirectional channel: agent-side ingestion and the review closed-loop #563

Open

Description

@duguankui

Background

The MCP server is read-only today. All four tools carry ReadOnly = true — search_documents (core/src/Dignite.Vault.Extract.Mcp/Documents/DocumentSearchTool.cs:32), get_document (Documents/DocumentTools.cs:23), list_cabinets (Documents/CabinetTools.cs:17), list_document_types (Documents/DocumentTypeTools.cs:26) — and there is no write path of any kind under core/src/Dignite.Vault.Extract.Mcp/. Ingestion exists only as IDocumentAppService.UploadAsync over REST (core/src/Dignite.Vault.Extract.Application/Documents/DocumentAppService.cs:172), driven by the Angular operator UI.

CLAUDE.md currently describes REST and MCP as "parallel egress adapters". This epic proposes making MCP bidirectional, and — the more consequential half — proposes that the AI agent client, not the Angular admin UI, becomes the primary surface both for getting documents into the channel and for clearing the review queue that gates them.

The mechanical change is that the agent client converts the document to Markdown before submitting it. The strategic change is what that implies.

Why this is more than a transport addition

Four consequences, in increasing order of importance:

  1. Server-side conversion load drops. The original motivation. True, and the least interesting of the four.

  2. Conversion cost moves to the customer. Today the host deployment pays for OCR (Azure Document Intelligence, VisionLlm). When the client agent produces the Markdown, that work is billed to the customer's own agent subscription. The host's marginal OCR cost per ingested document approaches zero. This is a unit-economics change, not a performance optimization.

  3. Format coverage stops being gated on provider work. DocumentConsts.IsAllowedUploadType is a fail-closed extension/content-type allow-list: only formats with a server-side provider can enter at all. An agent that can read a format can produce its Markdown whether or not this repo has ever implemented a provider for it — .eml, .heic, niche CAD or accounting exports. The original is archived as a blob and the server never needs to parse it. The supported-format set changes from "what we have shipped providers for" to "what an agent can read", with no new provider work. This requires splitting the allow-list into two dimensions (see Open questions).

  4. It repositions the channel ahead of OCR commoditization. Vision models make "turn a scan into text" cheaper and better every release. A channel layer whose value proposition is "we run the OCR for you" is standing on a declining curve. What does not commoditize is the document type system, the field schema, the Ready gate, and the downstream event contract. This change gives the conversion away deliberately in exchange for moving up the stack.

Consequence 4 implies a rewording of the positioning sentence in CLAUDE.md as part of this epic: trustworthiness must stop being implicitly derived from "we performed the conversion" and start being derived from "we define the schema, validate the result, gate Ready, and guarantee the downstream contract" — regardless of whether the Markdown came from a server provider or from an agent. Proposed text in Documentation changes below.

Goals

  • Add an MCP ingestion path: the client agent submits an already-converted Markdown body together with the original file, and the result is an ordinary Document that is indistinguishable downstream except for its recorded provenance.
  • Move the review closed-loop into MCP as well, so a document submitted from an agent can also be unblocked from an agent (see "The review closed-loop is not optional" below).
  • Publish a companion skill that defines the conversion contract, so client-side conversion is versioned and reproducible rather than per-client-per-prompt.
  • Keep every existing guarantee intact: single pipeline entry point, #411 duplicate detection, the Ready gate (ReviewReasonPolicy.Blocking), thin multi-stage ETOs, IMultiTenant isolation, and the .claude/rules/llm-call-anti-patterns.md conventions.

Non-goals

Design decisions taken

1. Ambient tenant only — no tenant parameter on any write tool

The /mcp endpoint is behind RequireAuthorization(); the tenant comes from the token's claim and is resolved by ABP into the ambient CurrentTenant. Write tools take no tenant argument and never call ICurrentTenant.Change.

The optional tenantId argument that exists today (McpTenantScope.Parse / .Change) belongs to the cross-tenant read feature added by #518/#519, which #524 is already turning off by default behind a deny-by-default IMcpTenantAccessValidator. Writes create durable state, blob storage, and background jobs; letting the caller name the target tenant is strictly worse on a write path than on a read path. This epic therefore has no multi-tenancy dependency at all.

Note for the deployment side (out of scope here): switching tenants from an MCP client is best solved at the authorization server, not at the MCP server — if tenant selection happens during the OAuth authorize step and is baked into the token, switching tenants means re-authorizing the connection and Extract needs zero changes. The cost is one configured MCP connection per tenant in clients that configure connections once.

2. The original file is mandatory

A submission carries both the Markdown and the source file. Markdown-only ingestion is explicitly rejected.

The reason is not caution, it is reversibility. With the original archived:

This is what makes the client-conversion bet acceptable at all, and it is what lets ClientSuppliedContent default to non-blocking (decision 8).

The corollary must be stated explicitly so it is not re-litigated during implementation: because the original is present, the server could re-derive the Markdown itself, and must not. Client Markdown is authoritative but recomputable — adopted by default (that is where the cost benefit lives), with re-OCR available as a deliberate, operator-triggered action. An automatic verification pass that re-runs conversion server-side would erase the entire economic rationale for the feature.

3. Transport: pre-flight check, ticket, client-side HTTP PUT

MCP tool arguments are JSON generated token-by-token by the model. A 20 MB original (DocumentConsts.MaxUploadFileBytes) base64-encodes to roughly 27 MB, which is not slow but infeasible. Binary therefore never travels over the MCP channel.

1. Agent computes SHA-256 of the original locally
2. MCP  check_duplicate(sha256)                                  -> stop here if it already exists
3. Agent converts the document to Markdown
4. MCP  begin_ingest(sha256, fileName, contentType, size)        -> short-lived single-use ticket
5. HTTP PUT of the original to a REST endpoint, authenticated by the ticket
6. MCP  complete_ingest(ticket, markdown, ...)                   -> server verifies bytes against
                                                                    the declared SHA-256, then creates
                                                                    the Document

Step 2 is deliberately before step 3, not folded into step 4: the point is to avoid spending the agent's conversion budget on a document that is already in the vault. That is the main value of a separate pre-check tool.

Whether steps 4 and 2 collapse into one call is an implementation trade-off (a ticket issued before conversion may expire during it) and is left to the slice.

4. Deduplication: client computes the hash, server verifies it

#411 duplicate detection is anchored on FileOrigin.ContentHash (SHA-256 of the original, ContentHasher.Sha256Hex). The client computes it locally, which costs nothing because it already holds the file.

Two constraints:

  • The server re-computes SHA-256 over the received bytes and rejects a mismatch with the declared value. Without this the anchor is decorative: a client could pre-check hash X and upload file Y. The upload path already computes this hash, so the check is free.
  • The pre-check is advisory, not authoritative. Two agents checking concurrently both see "absent". This inherits — and does not change — the race already accepted at DocumentAppService.cs:241-244 (Upload endpoint needs server-side file size and content-type validation #221 review follow-up 2: ContentHash carries only a non-unique index, check-then-act is deliberate, and making the losing side of the race a 500 was judged not worth it). Implementation must not present the pre-check as a stronger guarantee than the commit-time check.

Minor, recorded not blocking: a hash-existence tool is a small information-disclosure surface — a caller with a valid token can probe whether an exact file exists in its own tenant. Within a tenant the caller can already search, so the marginal leak is low.

5. One pipeline entry point

Client-supplied Markdown must resolve through the same stage-completion path as server-produced Markdown. Today Document.SetMarkdown is internal and write-once (Document.cs:285), with exactly one production caller, DocumentPipelineRunManager.CompleteParseAsync (DocumentPipelineRunManager.cs:129).

This is not a security constraint and cannot be dissolved by "opening up the API": two entry points mean two lifecycle state machines, two DocumentPipelineRun histories, and two possible event orderings for downstream consumers. However open the channel becomes, there must remain exactly one place where a Markdown body becomes a document's text.

#555 has already decided to relax the write-once invariant (Option B). This epic depends on that, and should reuse its entry point rather than introduce a parallel one.

6. Events: skipped stages still fire

A client-converted document skipped the server's parse stage but must still emit the corresponding stage event, carrying provenance. Suppressing it would force every downstream consumer to handle two different event sequences for the same logical outcome, which contradicts the thin-payload, at-least-once contract in .claude/rules/integration-events.md.

7. Provenance records the conversion contract version, not just "a client"

DocumentParseMetadata.ProviderName (#210) already exists as the "who produced this Markdown" field. For this path it must record the skill/contract version, e.g. claude-code/vault-extract-md@1.2.0, not merely client.

This is what makes the whole approach operable rather than a black box: a systematic defect in one skill version can be scoped to exactly the affected documents and re-converted from the archived originals (decision 2). Provenance must reach the egress — DTO, ETOs, and the MCP read tools — so downstream consumers and operators can both tell.

8. ClientSuppliedContent review reason, non-blocking by default

Add a review reason for client-converted content, defaulting to non-blocking and host-configurable to blocking, reusing the existing ReviewReasonPolicy declaration point. A compliance deployment sets it blocking (a human sees every agent-converted document before Ready); a knowledge-base deployment leaves it non-blocking. Non-blocking is defensible as the default only because decision 2 makes the conversion reversible.

9. The skill is a first-class deliverable

The objection that client-side conversion has unbounded quality variance is answered by shipping a skill that encodes the conversion contract — Markdown conventions, table handling, completeness self-check — so output is reproducible across clients and versionable over time. Combined with decision 7 this turns "the client converted it" from an unauditable claim into a versioned, attributable artifact.

It is also the distribution mechanism: installing the skill is the act of adopting the channel. It belongs in the epic as a peer of the MCP tools, not as documentation.

10. The review closed-loop is not optional

Today the loop is: upload -> pipelines -> blocked by a ReviewReasonPolicy.Blocking reason -> a human resolves it in the Angular UI -> Ready fires. DocumentLifecycleStatus.PendingReview (#510, shipped in v0.3.0) already names that state precisely.

If only submission moves to MCP, the user experience is: submit from the agent, then get sent back to the admin UI to click confirm. That is not "guided away from the back office", that is one more entry point.

The write surface therefore has to cover the loop. The application-layer methods all exist already, so the MCP side stays a thin adapter: ConfirmClassificationAsync, ReclassifyAsync, ResolveFieldValidationWarningsAsync (#527), AllowDuplicateAsync (#411). What is missing on the read side is a structured rendering of why a document is blocked — get_document exposes LifecycleStatus and FieldExtractionDeclined but not the blocking reasons in a form an agent can act on.

Review is also a genuinely better fit for a conversation than for a list page: "this looks like a purchase contract but confidence is 0.6, confirm?" is one exchange in an agent and three clicks plus a filtered list in the back office.

Rejected alternatives

Server-side fetch of a client-supplied URL

Proposed during discussion as a complementary path for documents already addressable in SharePoint / S3 / an intranet system, then rejected. Recorded here so it is not re-proposed:

  1. It breaks the hash guarantee of decision 4. The client's SHA-256 is computed over what the client read; the server would fetch whatever exists at fetch time. In systems like SharePoint, edits between the two are routine. Either the ingest fails on mismatch (unreliable path) or the check is skipped — in which case the Markdown describes v1 while the archived original is v2, with no signal. That is precisely the silent corruption decision 2 exists to prevent.
  2. Authentication makes it a connector project. Enterprise documents are not anonymously retrievable. Either the host is configured with per-customer credentials for each source system — which is "business-system-specific connectors", explicitly listed under OUT of scope in CLAUDE.md — or the client mints a pre-signed URL, which requires capabilities that would let it upload the bytes directly anyway, or the client forwards its own credential to the server.
  3. Confused deputy. A server fetching with host-level credentials can retrieve documents the requesting principal is not entitled to. A URL allow-list does not help: the failure shape is an in-allow-list URL with out-of-policy authorization.
  4. The stated benefit is self-contradictory. It was proposed as a path for clients lacking outbound HTTP, but a client that cannot retrieve the document cannot convert it to Markdown either. The only case that survives is a client reading through a connector that also surfaces a canonical URL — too narrow to justify an ingestion path.
  5. SSRF defense was understated. A real implementation needs redirect handling (or refusal), DNS-rebinding defense, IP-encoding normalization, and awareness that an allow-listed host may itself proxy onward. Not a configuration line.
  6. Failures move to the wrong place. Direct upload fails synchronously and the agent can react in-conversation; server-side fetch fails asynchronously in a background job, sending the user back to a status page — against the point of the epic.

Base64 originals in MCP tool arguments

Tool arguments are model-generated token by token. Even a few hundred KB is tens of thousands of output tokens: slow, expensive, error-prone. Only viable for files of a few tens of KB, a band too narrow to justify a second ingestion path.

Markdown-only submission, without the original

Rejected by decision 2. It also silently disables #411 deduplication (no original, no anchor), and makes any conversion defect permanent.

Scope boundary

Full ingestion requires a client capable of outbound HTTP. This follows from "the original is mandatory" plus "binary cannot travel over MCP", and there is deliberately no alternative channel — a fallback with weaker guarantees would dilute the main path's guarantees.

The boundary is a capability, not a product name: agents with shell or fetch access (Claude Code, Cursor, custom agents, and clients with a suitable connector installed) can perform full ingestion; clients without it use the read and review surface, which is unaffected and remains available everywhere.

This is in tension with the CLAUDE.md product stance that customers are business users rather than technical users, and should be recorded as a known limitation rather than discovered during implementation.

Open questions — resolve before implementation

  • Identity on the ingest path (will crash as written). FileOrigin's constructor calls Check.NotNullOrWhiteSpace(uploadedByUserName, ...) (core/src/Dignite.Vault.Extract.Domain/Documents/FileOrigin.cs:41) while its only caller passes CurrentUser.UserName ?? string.Empty (DocumentAppService.cs:265). This cannot throw today because the sole entry point is REST upload behind [Authorize(VaultExtractPermissions.Documents.Upload)] with a user-delegated token. An MCP ingest authenticated by a client-credentials token has no user principal, so the empty string reaches Check.NotNullOrWhiteSpace and it throws ArgumentException. Decide: user-delegated tokens for MCP ingest (nothing to change, and a better fit for the review loop, where "who confirmed this classification" should be a person), or a machine-token identity representation on FileOrigin.
  • Two allow-lists. IsAllowedUploadType currently means both "the server can parse this" and "this may be stored". Consequence 3 requires splitting them: the archival allow-list can be much wider than the processing allow-list. Where the boundary sits, and whether the archival list is host-configurable, needs deciding.
  • Inbound Markdown ceiling. Needs a compile-time const cap symmetric with the outbound VaultExtractMcpConsts.MaxDocumentMarkdownChars (200_000). Per .claude/rules/llm-call-anti-patterns.md, a ceiling that would silently corrupt the result must gate rather than truncate: an over-cap submission is rejected, not clipped.
  • Ticket design. Lifetime, storage, single-use enforcement, and what happens when complete_ingest never arrives (orphaned blob cleanup).
  • Permission. "Submit already-processed content" is a different trust level from "upload an original", so it likely warrants its own permission rather than reusing Documents.Upload. Review-loop tools map to existing permissions (ConfirmClassification, etc.).
  • Rate limiting on writes. McpRateLimiterOptions exists for reads; write quotas govern storage and background-job consumption and probably need their own semantics.
  • Content with no source file. Meeting notes, scraped pages, agent-authored summaries — content the channel cannot accept today because it only accepts files. This is arguably the largest new capability the epic unlocks, but it has no original and therefore no hash, so it cannot use the decision-2 / decision-4 path. It needs either its own explicitly-scoped entry point or an explicit deferral. Do not let it in through the same door by making the original optional.
  • CLAUDE.md and rules updates. Enumerated in "Documentation changes" below; the positioning rewrite there is the substantive one and should be agreed before Slice 1 lands, not after.

Documentation changes

The positioning sentence (CLAUDE.md:3-4)

This is the substantive one. The current sentence lets trustworthiness rest on an unstated premise — that the channel performed the conversion. Once an agent can submit the Markdown, that premise is false, and leaving the sentence as-is would make every later reader assume a guarantee the code no longer provides.

Current:

Positioning (one sentence): Dignite Vault Extract = the channel layer that turns any content requiring IDP (Intelligent Document Processing) — scans, photos, PDF images, Office files, and other document content — into trustworthy structured data.
It does not consume, own, or reach into business logic — it exposes outputs to downstream consumers: RAG platforms, business systems, AI clients, etc.

Proposed:

Positioning (one sentence): Dignite Vault Extract = the channel layer that turns any content requiring IDP (Intelligent Document Processing) — scans, photos, PDF images, Office files, and other document content — into trustworthy structured data, whether the conversion runs inside the channel or is submitted by a client agent against the channel's contract.
Trustworthiness comes from the channel owning the document type system, the field schema, the Ready gate, and the downstream event contract — not from the channel having performed the conversion itself. Client-submitted conversions are accepted only with their original archived and their provenance recorded, so any conversion remains attributable and re-derivable.
It does not consume, own, or reach into business logic — it exposes outputs to downstream consumers: RAG platforms, business systems, AI clients, etc.

The added second line is the load-bearing part: it names where trust actually comes from, and it ties the acceptance of client conversions to the two conditions that make them safe (decisions 2 and 7). Wording is a proposal, not settled — but the property it asserts should not be weakened, because several other decisions in this epic depend on it being true.

Other touchpoints

  • CLAUDE.md:36 — "REST (HttpApi) and MCP (Mcp) are parallel egress adapters". MCP becomes bidirectional; REST stays as-is. The clause that must survive verbatim is the one after the dash: protocol/transport concerns still do not leak into Application, so every write tool delegates to an existing application service exactly as the read tools do today.
  • CLAUDE.md:82 — the "Three live egress channels" enumeration needs MCP re-described as an ingress + egress channel rather than a third exit.
  • CLAUDE.md data-flow diagram (top) — currently shows a single one-way path into the channel. Needs a second inbound arrow for agent-submitted content.
  • CLAUDE.md:104, Markdown-first — "Providers must output Markdown ... implementations must not fall back to a plain-text path". Client submission is a third source of Markdown that is not an ITextExtractor / IMarkdownTextProvider / IOcrProvider implementation, so the rule needs restating in terms of the body that reaches Document.Markdown rather than in terms of provider implementations. The invariant itself is unchanged, and OcrResult / TextExtractionResult still expose no RawText.
  • .claude/rules/integration-events.md — provenance on the ETOs, and the fact that a stage skipped by client submission still fires its event (decision 6).
  • .claude/rules/text-extraction.md — the client-supplied provenance case, and its interaction with the re-extraction/re-recognition policy (client Markdown is authoritative but recomputable, decision 2).
  • .cursor/rules/project/*.mdc twins — both rule files above have twins that drift silently; update them in the same commit.

Dependencies

Slices

Deliberately not split into sub-issues yet. Following the #187 / #558 precedent this epic should eventually decompose into separate issues, but the split is held until implementation actually starts: each slice needs its own design discussion first (transport/ticket mechanics, the provenance format and the skill contract it has to agree with, the review-loop tool surface), and splitting now would fix those shapes before they have been worked out. Treat the list below as scope, not as a plan of record.

  • Slice 1 — Ingestion. check_duplicate + ticket-based original upload with server-side hash verification + Markdown submission + provenance with contract version + ClientSuppliedContent review reason + identity resolution + archival allow-list split.
  • Slice 2 — Review closed-loop. Structured blocking-reason exposure on the read side, plus write tools for confirm classification, reclassify, resolve field validation warnings, and allow duplicate.
  • Slice 3 — Conversion skill. The versioned conversion contract, aligned with the provenance format from Slice 1.
  • Slice 4 — Deferred. Client-side field extraction, gated on [Epic] Field architecture v3: adopt Dignite.Abp.FlexFields kernel #558/Implementation: field architecture v3 (flex-fields kernel adoption) #562 and on the Prompt-exposure decision.

Activity

  1. added this to the v0.6.0 milestone on Aug 30, 2026
  2. added
    enhancement
    severity:design
    area:mcp
    epic
    on Aug 30, 2026
  3. duguankui commented on Aug 30, 2026

    @duguankui
    MemberAuthor

    Depends on #555.

    Decision 5 ("one pipeline entry point") requires client-submitted Markdown to resolve through the same stage-completion path as server-produced Markdown (DocumentPipelineRunManager.CompleteParseAsync), never a second write path — that path only exists once SetMarkdown's write-once invariant is relaxed, which is #555's Option B. Slice 1 (ingestion) has no legal entry point to write into an existing Document.Markdown until #555 lands.

  4. modified the milestones: v0.6.0, v0.7.0 on Oct 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:mcpenhancementepicseverity:design

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions