Plugin SDK
Geprüfte Aktionen & Empfänger
Feste Empfänger, exakte Freigaben und getrennte Client-Zugänge.
Diese technische Anleitung wird derzeit auf Englisch gepflegt. Navigation und Nutzer-Anleitungen sind auf Deutsch verfügbar.
Experimental Host API 0.1. These are generic SDK contracts; the owning plugin defines what a message, request or commitment means. No generative AI runs in the platform; the one exception, a temporary test, is a small local search model in the worker that computes search vectors and decides nothing.
Two boundaries, both required
An authorization policy answers who may act now. An exact command approval answers which reviewed artifact this run may execute. Neither substitutes for the other.
Declare authorization.collectionAudience: "fixed" for collections with an immutable audience ceiling. Create the collection with audienceUserIds, including its custodian. This field is immutable in Postgres. Each participant still needs live resource access through explicit roles or a shared container. New bucket members do not enter an old audience; removed members lose access. All resource reads, projection counts, exports, descendants and replays intersect that ceiling with current policy. Creating a new channel is the way to choose a new audience.
Mark an action requiresApproval: true. Ordinary OAuth and org keys cannot invoke it directly. A plugin cannot approve its own command through PluginHostApi, a model-supplied boolean or an MCP tool.
A declarative definition's requiresApproval: true (definition version 5) is a different, stricter rule: the compiled runtime runs that command only for a person in the authenticated browser and refuses every MCP connection, controller and managed agent, and no command grant reaches it, because a declarative plugin has no fixed collection audience (DECLARATIVE-PLUGINS, "Steps only a person takes").
Collection initialization
createCollection accepts an optional initialCommand with the ordinary command
fields except collectionId, which the host supplies. The private collection,
creator binding and command effects commit together or all roll back. The first
command uses the same live authorization, approval, reference, secret and quota
checks as execute; initialization cannot approve its own action. The method
returns the new collection ID. Collection creation itself is not idempotent:
clients must reconcile an uncertain response before retrying.
Trusted client flow
- Obtain the plugin-authored command schema. Read current records and revisions through the normal authorized connection.
- Prepare the exact command outside the release loop. Show its content, audience, references, purpose and intended effect in a trusted review interface.
- After approval, call
withApprovedExecutionfrom@meinkontext/plugin-sdk/execution-clientusing the trusted user's OAuth token. Keep that full token outside the model's environment. - Pass only the limited connection to the run. Execute that same command through the plugin's declared tool or generic
plugin_command. The SDK/control API uses camelCase fields; the MCP tool usescollection_id,action_id,expected_revisionsandidempotency_key. Preserve their values and the exactinput; do not spread the SDK object directly into the tool arguments. Supply the canonical owner asowner_organization_idfor a shared scope. - The helper revokes the credential in
finally. Verify the result through the ordinary authorized connection.
import { withApprovedExecution } from "@meinkontext/plugin-sdk/execution-client";
// reviewedCommand is the exact object already approved by the trusted UI:
// { collectionId, actionId, input, expectedRevisions, idempotencyKey }
await withApprovedExecution({
endpoint, oauthToken, organizationId, command: reviewedCommand,
expiresIn: 300,
}, async ({ endpoint, token }) => {
// Connect the external MCP client with ONLY this restricted token.
// Run the already-reviewed command, without adding or changing fields.
return executeApprovedMcpCommand(endpoint, token, reviewedCommand);
});executeApprovedMcpCommand above is the caller's MCP transport integration, not an SDK export. The helper performs no inference and does not dispatch a domain tool itself.
The control endpoint is POST /mcp/command-grants with { organizationId, command, expiresIn? }. It returns { id, credential, expiresAt }. Expiry is 60–600 seconds, default 300. Revoke with DELETE /mcp/execution-grants/:id. Never log the returned credential. This endpoint is deliberately not an MCP tool. Existing create-only /mcp/execution-grants imports remain independent and cannot request an approval envelope.
Retries use the same operation key within the same grant. If a connection fails after a possible commit, read the result with the normal authorized connection before requesting a new grant. Operation receipts are credential-bound; do not switch to a new operation key merely to force a retry.
Choose the right authority
| Caller | Available role in the flow |
|---|---|
| Ordinary authorized MCP connection | Discover/read current records, prepare drafts and run permitted actions that do not require approval |
| Trusted OAuth control client | Review the exact artifact, issue its command grant and revoke it; keep its full token out of the restricted run |
| Restricted command connection | Execute only the bound action and exact payload while the grant and live rights remain valid |
| Authenticated web mutation | Invoke the generic reviewed-execution capability after the plugin's explicit review form |
A client that only exposes normal MCP tools cannot issue its own release approval. It can still prepare a draft for a trusted review flow. Installing a plugin or placing approval instructions in its context does not supply that client feature.
Failure and recovery
| Observation | Safe recovery |
|---|---|
| Source, draft, channel or policy changed | Fetch current state and construct a newly reviewed command; do not alter the old command under its existing grant |
| Audience needs another participant | Create a new fixed-audience collection and obtain required access/consent; do not widen history access |
| Write response was lost | Read back under normal current rights; retry the exact operation only within its original valid grant |
| Grant expired or was revoked | Stop using it; establish whether the original operation committed before requesting fresh approval |
| Optional provider disappeared or source access was revoked | Respect the unavailable feature; remove a reference only through the consumer's permitted workflow |
| Recipient has not processed an outbox hint | Preserve the durable notification; do not infer model execution, a read receipt or a domain commitment |
What is bound and rechecked
The server hashes the complete validated command: action, collection, payload, revisions, protection parent and operation key. It binds that hash to the authenticated principal, immutable audience, live policy epoch and short-lived credential. Other tool methods, other actions, changed text and alternate operation keys are denied. Current RBAC, plugin activation, optional contracts and live source access are checked before execution and replay. A policy change invalidates an existing approval. Expired or revoked credentials never return cached results.
Use DomainRuntime.requirements().documents for same-plugin read dependencies. Their IDs must have exact expectedRevisions, checked before replay. Use references and features for compatible optional contracts. Those references are live and do not freeze a source's future content. If a workflow approves specific source bytes, include a plugin-owned version/digest assertion as well.
A domain may implement authorize(action, input, context) for pure admission checks before replay, such as a channel's revocation. plan() still validates the transition. Use readScope to declare bounded document reads, including projection queries for receipts; queries never bypass authorization.
Mutations, derived projections, audit entries, idempotency receipts and notification-outbox entries commit together. Blob persistence may leave unreferenced blobs after a rollback, handled by existing storage maintenance. Notifications are stored IDs with access rechecks, not a guarantee of email, client push or agent execution.
Web adapter
A reviewed plugin may use ProcedureContext.executeReviewed only inside a mutation procedure and only for its own requiresApproval actions (AV05-S03e, API reference). The platform binds the authenticated session, exact same-origin POST and current command; read procedures and MCP contexts never receive the capability. Plugins must show a real review step and require explicit submission. The platform has no domain-specific approval form or domain imports. The old stack's PluginRequestContext.executeReviewed was removed with the old React Router app (AV07-S04).
Trust limits and verification
This protects an untrusted model loop using the restricted credential. It does not prove a human's mental intent or sandbox an arbitrary program holding full OAuth. A compromised trusted client can request grants as its user. Keep credentials separated, review the client, and never place the full token in a model's shell/tools. Topic keys select workflows; they do not classify or redact free text.
Permanent gates cover changed payload/key/identity, self-issuance, policy/revision changes, expired/revoked keys, unauthorized reads and exports, fixed-audience bucket growth, cross-account data and transaction rollback. External model evaluations are additional behavioral evidence, not an authorization mechanism. Langfuse may hold sanitized evaluation traces; it must never be the authority for allowing a release.
See API, optional contracts and testing.
Additional resource permissions
permissionRequirements(action, input, context) may derive additional permissions
from the authorized command documents. It returns { resourceId, permission }
entries for records in the same plugin collection. The host requires live read
access, the declared permission and, by default, an unarchived target before execution and
before returning a cached receipt. These requirements are also persisted with the
operation's effect permissions, so later runtime changes cannot weaken old replay
requirements. They grant no authority. Restricted create-only grants cannot use
these dependencies; reviewed approvals remain intersected with live policy.
Committed identities in a plan
DomainChange.versionBindings and revisionBindings map data fields to records
committed earlier in the same atomic plan. DomainPlan.resultVersions and
resultRevisions bind the returned result in the same way. A no-op with
skipUnchanged binds its existing version and revision. Forward references,
unknown records and a field bound as both a version and a revision are invalid;
any failure rolls back the whole command. Bound data still passes schema,
projection and secret validation. These bindings supply identities, never rights.
A reviewed runtime may set allowArchived: true on an additional permission
requirement for a workflow that deliberately operates on archived records. This
only removes the archive-state veto; live read/write authority, scope and protected
parents remain mandatory. The host retains the explicit archive allowance with
all matching effect permissions in the operation receipt. Old receipts without
this flag remain denied for archived targets, even if a newer runtime opts in.
A change may also set replayArchived: true to retain its own effect permission
for replay after archival. This never authorizes the mutation: existing records
still require the normal explicit archive/restore transition and live write
permission. For newly created records, a plugin can set permission to retain
that record's future replay authority in addition to the collection creation
permission. Wiki source authorship and article publication use this binding.
Direct record grants
A reviewed runtime may opt a format into recordGrantPolicy. The mapping owns
three distinct read/write/publish role IDs for each user, group and service
subject family. These labels describe grant metadata; the declared role permissions
remain authoritative. Service mappings must contain no permissions. This contract
does not opt a plugin into managed-agent execution.
host.recordGrants lists, ensures and revokes direct bindings under the owner
organization's policy lock. It requires an ordinary human member, current record
visibility and the declared management permission. An explicit
organizationAdmins policy may supply management authority to an already-visible
organization admin; it supplies no read authority and still evaluates exclusions,
protected parents and read constraints. Installation administration alone is not
content authority. Disabled or unavailable runtimes refuse these methods.
Metadata access does not depend on the caller's selected edition. Ensure rejects archived records; list and revoke remain available for cleanup. Ensure is additive and leaves existing role bindings, dates and validity windows unchanged. Revoke removes all mapped levels for the named principal, including departed principals. Creation dates may be null for historical bindings whose date is unknown. Only actual changes advance the policy epoch and write an audit event.
Organization/team ensures require an advisory-passed version on the policy's publication channel, or a nonempty, secret-scanned, audited override reason. The published channel is checked inside the same transaction; personal pins never substitute a different version for this gate. The runtime's mapping is validated against the installed policy and cannot grant permissions on another resource type.
Bulk record metadata
Optional host.recordIndex({ pluginId, formatId }) returns authorized metadata for
one installed format under one live owner-policy snapshot. It uses the caller's
selected editions, including their projection metadata and file paths, and omits
archived or unreadable records. Collection visibility, protected parents,
contributor ceilings and explicit exclusions remain in force. Disabled or absent
providers refuse the request. The index does not read content blobs or return
manifest hashes; it is not an alternative content-delivery API.
The result includes record/collection/package identity, canonical catalog name and source, description, selected version, revision, file paths and the plugin's projection data. Callers must not retain it as an authorization cache between requests. A plugin owns its conversion into domain catalog rows; the platform must not infer domain semantics from this generic metadata. This bulk method avoids repeated policy/edition scans when a complete metadata catalog is needed.
Optional query and textSearch use the same search contract as host.query.
Filtering, rank and snippets use the authorized selected edition's projection.
When requested, each hit includes numeric rank and plain-text snippet; a
request without a query retains the metadata-only result shape. Search does not
fetch content blobs or widen the readable record/version set.