Skip to content
Closed
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ All notable changes to this project will be documented in this file. The format

## [Unreleased]

## [0.3.2] - 2026-07-21

### Fixed

- [#106](https://github.com/mohanagy/miftah/issues/106) Miftah now recognizes the strict PostHog command-wrapper grammar only at the canonical official MCP endpoint, so documented read/discovery commands can run under destructive-routing safeguards without a per-user routing workaround. Generic `exec` tools, alternate origins, malformed commands, and unknown nested operations remain fail-closed; route preview now exposes the same local policy-enforcement block as a real call.
- [#112](https://github.com/mohanagy/miftah/issues/112) Shutdown now completes upstream process containment even when a downstream transport close rejects, then rethrows the original close error after cleanup.
- [#120](https://github.com/mohanagy/miftah/issues/120) The development build toolchain now resolves `esbuild` 0.28.1, removing the known low-severity development-server path-traversal advisory.

## [0.3.1] - 2026-07-18

### Fixed
Expand Down
2 changes: 1 addition & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ Before a configured local STDIO target starts, `ProfileRuntimeIsolation` derives

The metadata-only routing context collector is the sole source of workspace context, profile hints, preview evidence, and proxied-operation audit evidence. It reads only allowlisted bounded metadata: file roots, cwd, two environment selectors, strict project markers, package/workspace fields, and a local Git origin. It separately derives canonical GitHub repository identifiers from safe package/workspace metadata and supported local remote forms; it never passes a raw context object to a matcher. The runtime configuration file remains separate from that input. Once initialized, `MiftahServer` capability-gates `roots/list`, caches only root URIs per client connection, and refreshes only on an advertised roots-list-changed notification. Every proxied operation and route preview receives one immutable snapshot; it uses that snapshot for rule matching, hint selection, fixed and plugin matcher projection, and redacted evidence so routing cannot change between those steps.

Every supported MCP request enters one outer audit scope. The scope records one terminal operation event on success or safe failure and also covers discovery/list failures, unknown names, and management tools that do not enter the proxy pipeline. `OperationPipeline` enriches proxied tool calls, resource reads, resource subscriptions, and prompt retrieval with captured source/target profile, upstream, routing, policy, risk, risk source/confidence, sanitized `routingEvidence`, and bounded `routingMatcherEvidence`; it does not emit its own record. It captures the source tool snapshot before awaiting policy work, normalizes only the four MCP behavioral booleans, and accepts them for classification only when the matching configured base upstream explicitly trusts tool annotations. The snapshot fingerprint includes client-visible annotations, so a routed profile with different metadata fails the same schema-compatibility guard as any other differing tool contract. It then captures the source profile state, resolves explicit hints and rules before the matcher band, runs the fixed in-tree registry and explicitly allowlisted routing plugins only through contained child hosts, uses `matcher:<provider>` or `matcher:plugin:<id>` only before fallback, evaluates the selected profile policy, and checks a captured lease and explicit-selection boundary before resolving the exact target upstream route. Matcher ambiguity carries only canonical bounded evidence and never resolves an upstream; a matcher reason cannot satisfy an explicit destructive-operation rule. It rechecks that captured lease immediately before execution, so a later renewal cannot authorize an old request and a different routed profile cannot borrow it. Route preview never forwards the hypothetical upstream operation, but it can invoke configured local routing plugins and therefore is not a permission-free operation. Tools retain their original upstream names for routing and policy compatibility while the matcher receives the client-visible name solely for exact provider-token recognition; resource reads and subscriptions use the stable policy name `resources/read`, while prompt retrieval uses the stable policy name `prompts/get`. Denied, blocked, and ambiguous operations never resolve or execute an upstream read/get route. Confirmation-required operations resolve only enough to bind the exact target, then enter a separate approval lifecycle before upstream session execution: state is connection-bound, the form-elicitation path carries only a generic boolean, and the default human mode fails closed when that form boundary is unavailable. An operator may explicitly select delegated-agent mode, which permits a bearer to approve only the exact bound operation once and is audited as delegated authorization rather than human proof. Approval audit records store lifecycle action, mechanism, and safe context, never the raw approval bearer or operation arguments. The management-tool contract supplies MCP behavioral annotations and exact client permission guidance, but those client hints do not replace server authorization. Upstream managers publish typed lifecycle transitions, which the server records as separate audit events without letting audit I/O interrupt cleanup or recovery.
Every supported MCP request enters one outer audit scope. The scope records one terminal operation event on success or safe failure and also covers discovery/list failures, unknown names, and management tools that do not enter the proxy pipeline. `OperationPipeline` enriches proxied tool calls, resource reads, resource subscriptions, and prompt retrieval with captured source/target profile, upstream, routing, policy, risk, risk source/confidence, sanitized `routingEvidence`, and bounded `routingMatcherEvidence`; it does not emit its own record. It captures the source tool snapshot before awaiting policy work, normalizes only the four MCP behavioral booleans, and accepts them for classification only when the matching configured base upstream explicitly trusts tool annotations. The snapshot fingerprint includes client-visible annotations, so a routed profile with different metadata fails the same schema-compatibility guard as any other differing tool contract. An origin-pinned adapter additionally parses the fixed PostHog `exec` command language only for `https://mcp.posthog.com/mcp`; it classifies bounded discovery commands and nested call names locally, while malformed or unknown commands remain destructive. It then captures the source profile state, resolves explicit hints and rules before the matcher band, runs the fixed in-tree registry and explicitly allowlisted routing plugins only through contained child hosts, uses `matcher:<provider>` or `matcher:plugin:<id>` only before fallback, evaluates the selected profile policy, and checks a captured lease and explicit-selection boundary before resolving the exact target upstream route. Matcher ambiguity carries only canonical bounded evidence and never resolves an upstream; a matcher reason cannot satisfy an explicit destructive-operation rule. It rechecks that captured lease immediately before execution, so a later renewal cannot authorize an old request and a different routed profile cannot borrow it. Route preview never forwards the hypothetical upstream operation, but it can invoke configured local routing plugins and therefore is not a permission-free operation. It shares the local policy-enforcement evaluator with a real call and returns an additive allowed/blocked result for that boundary without resolving a target. Tools retain their original upstream names for routing and policy compatibility while the matcher receives the client-visible name solely for exact provider-token recognition; resource reads and subscriptions use the stable policy name `resources/read`, while prompt retrieval uses the stable policy name `prompts/get`. Denied, blocked, and ambiguous operations never resolve or execute an upstream read/get route. Confirmation-required operations resolve only enough to bind the exact target, then enter a separate approval lifecycle before upstream session execution: state is connection-bound, the form-elicitation path carries only a generic boolean, and the default human mode fails closed when that form boundary is unavailable. An operator may explicitly select delegated-agent mode, which permits a bearer to approve only the exact bound operation once and is audited as delegated authorization rather than human proof. Approval audit records store lifecycle action, mechanism, and safe context, never the raw approval bearer or operation arguments. The management-tool contract supplies MCP behavioral annotations and exact client permission guidance, but those client hints do not replace server authorization. Upstream managers publish typed lifecycle transitions, which the server records as separate audit events without letting audit I/O interrupt cleanup or recovery.

When rotation or integrity is configured, the audit journal layer serializes same-host append, rotation, retention, and reader snapshots with a kernel-released local lock, so an abruptly terminated writer cannot leave a permanent lock artifact. A managed journal is local to one host and must not be shared for concurrent writes across machines. It rotates only between complete JSONL batches, creates a new restrictive active file before accepting the next batch, and limits retention to validated managed regular archives. Integrity transitions persist a restrictive pending intent, validate the next physical state, then persist a committed decision before cleanup; recovery can discard only a pending unacknowledged suffix, while a committed transition must verify or fail closed. Readers and exports copy a coherent retained-segment set into private staging before parsing, so output work does not hold the writer lock. The optional integrity mode calculates a continuing SHA-256 chain over already-redacted records and records segment/retention continuation metadata; verification replays that state and returns the first safe broken segment/record/reason rather than audit contents. This local state is deliberately not a public library API or a substitute for an independently protected archive.

Expand Down
9 changes: 6 additions & 3 deletions docs/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ Selection order is environment hint, project-marker hint, configured rule, the m

MCP roots are optional client metadata. After initialization, Miftah calls `roots/list` only when the client advertises `roots` capability, stores a URI-only snapshot for that connection, and refreshes it only on an advertised `notifications/roots/list_changed`. An unsupported or failed roots request yields an empty-root snapshot; Miftah does not poll roots or request them for every operation.

`miftah_route_preview` resolves against one collector snapshot using the same context inputs as a proxied operation. Its response contains the selected profile, reason, policy decision (including `riskSource` and `riskConfidence`), sanitized `evidence`, and `matcherEvidence` when a fixed or plugin matcher selected a profile. It never starts an upstream to inspect a tool: it uses only an already-cached compatible tool snapshot and otherwise reports the conservative heuristic or unknown classification. Proxied operation audit records carry the same snapshot as additive `routingEvidence` and carry canonical `routingMatcherEvidence` for a successful or ambiguous match. Evidence contains only allowlisted metadata and redacted URI components; it never contains arbitrary project file content or the raw `MIFTAH_PROJECT` value.
`miftah_route_preview` resolves against one collector snapshot using the same context inputs as a proxied operation. Its response contains the selected profile, reason, policy decision (including `riskSource` and `riskConfidence`), an additive local-policy `enforcement` result, sanitized `evidence`, and `matcherEvidence` when a fixed or plugin matcher selected a profile. It never starts an upstream to inspect a tool: it uses only an already-cached compatible tool snapshot, except for the fixed origin-pinned PostHog command adapter described below, which can classify its bounded command payload from configuration alone. For an ordinary unknown tool it reports the conservative heuristic or unknown classification. `enforcement.status: "blocked"` carries the same stable error code and safe message that a real call receives from the explicit-routing or policy-deny boundary; preview does not resolve a target, request approval, or perform identity verification. Proxied operation audit records carry the same snapshot as additive `routingEvidence` and carry canonical `routingMatcherEvidence` for a successful or ambiguous match. Evidence contains only allowlisted metadata and redacted URI components; it never contains arbitrary project file content or the raw `MIFTAH_PROJECT` value.

### Provider routing matchers

Expand Down Expand Up @@ -312,11 +312,14 @@ Policies classify operations as `read`, `write`, or `destructive` in this order:

1. an exact local `tooling.toolRiskOverrides` entry;
2. MCP tool annotations only when that exact base `upstream` or named `upstreams.<name>` declaration sets `trustToolAnnotations: true`;
3. conservative name heuristics; then
4. `tooling.unknownToolRisk`, which defaults to `"destructive"` and may be set only to `"write"` or `"destructive"`.
3. Miftah's fixed PostHog command adapter, only for an `exec` tool on the canonical official Streamable HTTP endpoint `https://mcp.posthog.com/mcp` (the version-1 `http` compatibility alias is equivalent);
4. conservative name heuristics; then
5. `tooling.unknownToolRisk`, which defaults to `"destructive"` and may be set only to `"write"` or `"destructive"`.

MCP annotations are hints, not authority. They cannot lower risk unless the operator explicitly trusts that configured upstream; profile-level upstream overrides cannot alter this trust boundary. A trusted `readOnlyHint: true` classifies as read, a trusted non-read-only `destructiveHint: false` classifies as write, and any contradictory `readOnlyHint`/`destructiveHint` combination classifies as destructive. `idempotentHint` and `openWorldHint` are retained as metadata but never lower mutation risk. Exact local overrides always win, including when an upstream annotation is incorrect.

The PostHog adapter reports `riskSource: "trusted-command-adapter"`; it is deliberately not a generic exception for tools named `exec`. It accepts only the official origin with no query, fragment, credentials, alternate path, or port; it then parses the entire bounded command language without executing a shell. `tools`, safe `search`, `info`, and `schema` discovery forms are read-only. A `call` command is classified from its canonical nested PostHog tool name; read-like names remain read, write-like names remain write, destructive names remain destructive, and unknown, malformed, multi-command, shell-like, or invalid-JSON forms are destructive. `--confirm` never lowers risk. A different origin, a local STDIO command wrapper, or any other generic `exec` tool keeps the normal conservative classification.

Every policy decision carries stable `riskSource` and `riskConfidence` values. Route previews and audit events expose only those enum values, never raw upstream annotations or tool output. `denyRisk` takes precedence over `allowRisk`; `requireConfirmation` returns a structured error instead of forwarding the operation.

### MCP approvals
Expand Down
2 changes: 1 addition & 1 deletion docs/presets-and-clients.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
This is the compatibility source of truth for generated `miftah init` configurations and client snippets.

- Catalog version: `1`
- Miftah package version: `0.3.1`
- Miftah package version: `0.3.2`
- Last tested / validation boundary: the catalog builds strict Miftah configuration that `validateConfig` accepts. The docs contract test checks generated configuration only; it does **not** construct a runtime, start, authenticate to, or smoke-test external providers.

Miftah itself requires Node.js `>=20`. That does not establish an upstream server's Node requirement.
Expand Down
2 changes: 1 addition & 1 deletion docs/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ Runtime profile locks and leases are connection-bound controls, not credentials

The explicit runtime configuration is trusted operator input; workspace routing metadata is not. Project markers cannot inject configuration because their only accepted shape maps the configured wrapper name to an already-known profile. They cannot add credentials, environment variables, headers, upstreams, policies, audit controls, or secret references. Miftah reads only named, bounded metadata files within the applicable working-directory/root boundary and does not scan arbitrary project content.

MCP `tools/list` annotations are behavioral hints supplied by the upstream, not proof of safety. Miftah ignores them by default. An operator may set `trustToolAnnotations: true` only on the exact base upstream declaration they trust; a profile override cannot change that decision. Even for a trusted upstream, missing or contradictory hints never reduce risk, and `idempotentHint`/`openWorldHint` never lower it. Miftah records only the resulting classification source and confidence in route preview and audit data, never raw annotation objects.
MCP `tools/list` annotations are behavioral hints supplied by the upstream, not proof of safety. Miftah ignores them by default. An operator may set `trustToolAnnotations: true` only on the exact base upstream declaration they trust; a profile override cannot change that decision. Even for a trusted upstream, missing or contradictory hints never reduce risk, and `idempotentHint`/`openWorldHint` never lower it. Miftah records only the resulting classification source and confidence in route preview and audit data, never raw annotation objects. Separately, the built-in `trusted-command-adapter` classification is limited to the canonical official PostHog endpoint `https://mcp.posthog.com/mcp` and its bounded command grammar; it does not trust arbitrary `exec` names, alternate URLs, local processes, provider descriptions, or raw command text. Invalid or unrecognized command forms remain destructive.

Routing evidence is deliberately narrower than routing context. It is passed through audit redaction before it reaches a client or JSONL record, strips URI userinfo/fragments and redacts URI query values, and never contains the raw `MIFTAH_PROJECT` value or arbitrary project file content. Fixed provider matchers receive only bounded top-level argument fields, canonical provider identifiers, and a separately normalized GitHub repository context; allowlisted routing plugins receive only a tool name and the same bounded canonical signal projection through a scrubbed child host. Neither receives nested arguments, the raw routing context, a raw provider URL, or secret-bearing URI components. `routingMatcherEvidence` records only a selected profile plus canonical provider/kind/value identifiers, and is structurally validated before an ambiguity is audited. An unrecognized environment profile, ambiguous matching rules, or ambiguous matcher bindings fails closed instead of selecting an account; standard project-marker discovery deterministically uses the nearest valid marker. Profile hints and matcher reasons also cannot satisfy an explicit-rule requirement for destructive operations.

Expand Down
Loading
Loading