Introducing a new way to review your PRs.

Read the announcement

sheeki03 / tirith

Terminal security for developers and AI agents. Intercepts homograph URLs, pipe-to-shell, ANSI injection, obfuscated payloads, data exfiltration, and malicious AI skills/configs before they execute.

View on GitHub

19 documents · Updated Nov 23, 2026

docs / agent-and-mcp-protection

Agent and MCP protection

Tirith protects the path between an AI agent and the actions or information it can use. It identifies the caller, applies caller rules to safety verdicts, controls MCP tool and resource traffic, and records enough context for an operator to review the result. The system treats caller identity as useful attribution rather than proof of identity.

Protection model

The protection model uses separate controls for caller identity, requested actions, and returned content. This separation lets Tirith block an unsafe action even when the caller is allowed, while also stopping an MCP server from sending unsafe data back to the agent.

Caller origin

Caller origin is the category and optional name that Tirith assigns to a request. The main categories are human, agent, MCP client, gateway, CI, and IDE. CLI paths use the integration and CI signals available to the process. An MCP session uses initialize.clientInfo. The gateway uses its own fixed gateway origin.

Origin values are sanitized before they reach verdicts, audit records, or operator output. The sanitization also applies redaction before length limits and removes control or invisible characters. These values are still caller-claimed. A process that runs as the user can change its environment or MCP clientInfo, so origin rules support filtering and review but do not authenticate an agent.

The CLI can show the origin that it would assign to the current process with tirith agent current. This command helps an operator check integration and CI signals. It does not add trust to those signals.

References: crates/…/agent_origin.rs• L21-30 crates/…/agent_origin.rs• L36-90 crates/…/agent_origin.rs• L216-309 crates/…/agent.rs• L1043-1082

Agent policy

Agent policy adds a caller check after the safety engine creates a verdict. A deny matcher can force a Block and adds a high-severity finding. An allow matcher does not remove a block that another rule already caused. A missing origin or an unmatched rule leaves the verdict unchanged.

The policy matches a closed origin kind and, when present, an exact caller-claimed name. Deny rules take precedence over allow rules. This makes the policy useful for cases such as refusing all calls from an untrusted MCP client, while keeping action safety independent from caller labels.

The agent policy commands help operators create and inspect this control. tirith agent allow and tirith agent block validate and print policy snippets; they do not change the live policy file. The block command's command pattern is documentation only today. tirith agent policy init builds a commented example from observed audit origins, so an operator must review and enable each entry.

References: crates/…/policy.rs• L375-412 crates/…/policy.rs• L596-649 crates/…/escalation.rs• L391-450 crates/…/agent.rs• L541-705 crates/…/agent.rs• L838-1040

Verdict and audit flow

The caller-facing path stamps origin information after analysis and before policy post-processing or audit. The same effective verdict then reaches the agent and the audit record. This gives downstream review tools a view of which caller category produced each decision without making the core analysis engine depend on a transport.

The CLI groups verdict entries by origin and can explain entries by session ID, command text, or origin label. Unattributed entries remain visible in an unknown group. These views support review of caller behavior without turning audit data into an authentication source.

The flow below shows the shared relationship between caller identification, action checks, and audit output.

flowchart LR
    A[Human, agent, MCP client, gateway, CI, or IDE] --> B[Caller origin]
    B --> C[Safety analysis]
    C --> D[Agent policy and verdict processing]
    D --> E[Allow, warn, or block]
    D --> F[Audit record with origin]

References: crates/…/agent_origin.rs• L267-309 crates/…/escalation.rs• L698-779 crates/…/agent.rs• L162-234 crates/…/agent.rs• L328-435

MCP traffic boundary

MCP, or Model Context Protocol, carries structured requests and responses between an agent and a tool server. Tirith protects two related boundaries: its own MCP server exposes safety checks to a client, while its gateway proxies another MCP server and can inspect both requested calls and returned data.

MCP server path

The Tirith MCP server accepts a JSON-RPC session over standard input and output. It requires initialization before normal tool use, captures the client's origin from clientInfo, and applies that origin to later safety-check verdicts. Its tools return both readable findings and structured verdict data.

This path is mainly an agent-facing safety service. When tool-output sanitization is enabled, each tools/call result is scanned before it returns to the client. The default keeps this output protection opt-in for compatibility.

References: crates/…/dispatcher.rs• L7-40 crates/…/dispatcher.rs• L249-315 crates/…/dispatcher.rs• L327-370 crates/…/tools.rs• L186-260

Gateway path

The MCP gateway sits between an agent client and an upstream MCP server. It tracks requests so a response is tied to the request that caused it, applies configured command guards, and can reject malformed, late, unknown, or oversized traffic. A secure gateway profile turns on the hardened output and containment posture when the operator does not set a weaker explicit value.

The gateway can also launch the upstream server inside an execution capsule. This limits the upstream process and prevents a gateway configuration that promises a hardened posture from silently running an uncontained server.

References: crates/…/gateway.rs• L27-46 crates/…/gateway.rs• L123-180 crates/…/gateway.rs• L1847-1875 crates/…/gateway.rs• L1890-1953

MCP inventory and drift

MCP server configuration is treated as a reviewable surface. Tirith builds a repository-local inventory of servers, transports, and declared tools. The committed lock records that baseline without storing raw environment values or URL credentials. Later checks compare the live configuration with the baseline.

The lock workflow refuses to create a trusted baseline when supported configuration paths are malformed or rejected, unless the operator records an explicit incomplete-baseline exception. Verification still fails while that coverage gap remains. tirith mcp diff gives an informational view, while tirith mcp verify provides the CI gate.

The gateway can also compare live tools/list descriptors with an approved descriptor set. A new or changed tool surface is a post-approval change. Tirith reports it and holds the affected tools until an operator reviews and approves the new surface. Static server trust does not replace a per-tool allow-list when one is configured. Policy scaffolds use source-qualified server identities, so the same server name in a different configuration does not inherit an earlier review.

The tirith mcp permissions view groups the capabilities implied by each locked transport and environment declaration. It also calls out omitted tool lists and unknown transports as unbounded permissions. This gives review a broad view of server reach without exposing secret values.

For the traffic and content rules in this area, see MCP gateway and content controls.

References: crates/…/mcp_lock.rs• L1-19 crates/…/mcp_lock.rs• L470-479 crates/…/mcp_lock.rs• L815-875 crates/…/mcpdrift.rs• L95-107 crates/…/mcp.rs• L18-164 crates/…/mcp.rs• L632-714 crates/…/mcp.rs• L1070-1345 crates/…/mcp.rs• L1665-1801

Content protection

MCP content can influence what an agent does even when the original tool call was safe. Tirith therefore inspects text and structured values at the output boundary, and it applies stricter typed checks to resource links, resource data, and live tool descriptions in the gateway.

Tool result filtering

The tool-result filter scans text content and string leaves in structured content. It can allow clean data, warn on lower-severity content, or replace blocked content with one safe text item. A block clears structured content and sets MCP isError so the client sees a tool-level failure rather than a transport failure.

Forwarded text and structured strings are scrubbed for terminal-control and invisible display payloads. The final decision is made over the sanitized form, so a dangerous phrase that becomes visible only after scrubbing does not pass through. Each filter pass gets an event ID that joins the agent-facing notice to a JSONL audit record.

The output scanners share a structural depth ceiling. This keeps a value that is too deep for the result sanitizer from being accepted by the typed response inspector through a separate path.

The filter is enabled by tirith gateway run --filter-output or tirith mcp-server --sanitize-tool-output. A secure gateway profile enables the gateway output protections as part of its hardened posture.

References: crates/…/mod.rs• L1-17 crates/…/output_filter.rs• L1-28 crates/…/output_filter.rs• L128-208 crates/…/output_filter.rs• L223-235 crates/…/output_filter.rs• L824-850

Listing and resource inspection

The gateway inspects response families that can carry tools, resources, or prompts: tools/list, resources/list, resources/read, resource templates, prompts/list, and prompts/get. It scans every string leaf, checks resource URIs against the fetch safety rules, and checks inline blobs against their declared MIME type and size limit.

Any unsafe URI or MIME mismatch forces a block. This protects the agent from a server that hides an injection in a description, redirects a resource link to a private destination, or labels executable bytes as harmless text. Server-initiated request families are not treated as responses to a client request by this inspection path.

References: crates/…/response_inspect.rs• L1-48 crates/…/response_inspect.rs• L61-110 crates/…/response_inspect.rs• L155-224

Agent context and prompt safety

Agent-facing text needs context beyond the MCP wire format. Tirith uses origin, command context, prompt-injection findings, and warning or command-card signals to help decide whether an agent action should proceed. These checks complement MCP content inspection: one protects the returned content, while the other protects the action the agent may take after reading it.

Operational context is the active target selected by a supported cloud or cluster tool. Tirith uses that signal with operator-defined labels to identify critical targets for destructive commands. The detection path is bounded and cached for responsiveness, but changes to its inputs invalidate the cached result. Missing or failed provider signals remain distinct from a detected context.

For the detailed rules for origin detection, agent context, prompt injection, and agent warnings, see Agent context and prompt safety.

References: crates/…/context_detect.rs• L1-30 crates/…/context_detect.rs• L117-145 crates/…/context_detect.rs• L217-313 crates/…/output_filter.rs• L308-317 crates/…/output_filter.rs• L657-715 crates/…/policy.rs• L225-233

Protection flow

The complete protection flow links an agent identity to an action verdict and then checks the data that returns from the tool server. The gateway adds request correlation and typed response checks because an upstream server can be untrusted even when the client is known.

This sequence shows how caller origin, operational context, action policy, and returned MCP content work together.

sequenceDiagram
    participant A as Agent client
    participant T as Tirith MCP server or gateway
    participant U as Upstream MCP server
    participant O as Audit record

    A->>T: initialize with clientInfo
    T->>T: record caller origin
    A->>T: tools/call or MCP request
    T->>T: assess command, context, and agent policy
    T->>U: forward permitted gateway request
    U-->>T: tool, resource, or prompt response
    T->>T: inspect and sanitize response
    T-->>A: allow, warning, or safe block
    T->>O: record origin, decision, and filter event

The boundary has two different failure meanings. A JSON-RPC error means the protocol request could not be handled. A tool result with isError: true means the tool result was rejected or failed at the tool level. Content blocks use the second form so a client does not mistake a security decision for a transport fault and retry unsafe traffic.

References: crates/…/dispatcher.rs• L249-315 crates/…/output_filter.rs• L18-28 crates/…/gateway.rs• L4356-4433 crates/…/context_detect.rs• L234-313

Change checklist

When these files or sections are changed, remember to consider these:

  • Add the caller-origin stamp before every new analysis-to-audit path. An unstamped path becomes unknown and cannot match agent_rules.
  • Keep the MCP origin capture tied to initialize; do not fall back to a human origin when clientInfo is absent.
  • Keep origin constructor and matcher normalization aligned. A policy name must pass the same sanitization as the stored caller name.
  • Treat tirith agent allow and block as snippet generators. Do not describe their output as a live policy change, and do not claim that the block pattern is enforced until the matcher supports it.
  • When adding an MCP response method, decide whether it is a client-request response or a server-initiated request before adding it to response inspection.
  • Keep the shared structured-depth ceiling aligned across output filtering and typed response inspection.
  • When changing tool descriptors or launch state, update the lock and approval contract together. A descriptor allow-list needs an approved live baseline.
  • Keep filter_output, fail_mode, and secure-profile defaults aligned. Turning off the output boundary can also turn off descriptor and typed-response protection.
  • Preserve the distinction between a filtered tool result and a JSON-RPC transport error. Keep the filter event ID in both the agent-facing placeholder or warning and the audit record.
  • Treat origin names, MCP client names, tool names, and response text as hostile input at every human-readable output boundary.
  • Invalidate or fingerprint operational-context inputs when a command changes the selected provider context. A short cache must not reuse a context after the target changes.
  • Keep incomplete MCP coverage visible in both lock creation and verification. An explicitly recorded gap must not become a passing verification result.

Important failure modes

TriggerConsequenceGuard
TIRITH_INTEGRATION or MCP clientInfo is forgedAn origin rule can classify a hostile process as a named agent or clientTreat origin as caller attribution, not authentication; use execution isolation for a hard boundary
A new caller path audits without stamping agent_originThe record falls into unknown, and caller-specific deny rules do not matchStamp origin at the caller before post-processing and audit
A policy name uses different normalization from the stored originAn intended allow or deny matcher does not match the caller it namesUse the shared origin-label sanitization for policy input and stored origin data
An operator assumes tirith agent block <pattern> limits one commandThe current (kind, name) matcher blocks every action from the matching originTreat the pattern as a comment until per-command matching is supported
Gateway fail_mode: open sees an unknown, late, or timed-out responseUpstream bytes can reach the agent without the closed-path denialUse fail_mode: closed or the secure profile for an untrusted upstream
Output protection is not enabledTool results and many MCP listing or resource responses can pass without content inspectionEnable --filter-output, --sanitize-tool-output, or the secure gateway profile
A structured value exceeds the shared scanner depthOne scanner can reject the value while another path would otherwise inspect or forward itEnforce the common depth ceiling in every structured-content walker
A live tool descriptor is added or changed after approvalThe agent may see a capability or schema the operator did not reviewKeep descriptor protection enabled and re-approve the exact changed surface
A provider context changes while a stale detection result remains cachedA destructive command can be assessed against the wrong operational targetFingerprint provider inputs and invalidate the cache after context-changing commands
A repository MCP config is malformed or rejected during inventoryThe baseline does not prove complete server coverage; verification stays nonzeroFix the coverage gap before refreshing the lock, or record the explicit audited exception and resolve it before verification

Key files

FileWhy to read it
crates/…/agent_origin.rsDefines caller categories, signal precedence, normalization, and the trust limits of attribution
crates/…/context_detect.rsDefines the operational-context signals used by context-aware safety rules
crates/…/policy.rsDefines agent matchers and the deny-before-allow policy contract
crates/…/escalation.rsShows where caller policy changes a safety verdict
crates/…/agent.rsShows origin inspection, audit review, and policy snippet generation
crates/…/dispatcher.rsShows the MCP session lifecycle, origin capture, and tool dispatch boundary
crates/…/tools.rsShows how MCP safety tools create, stamp, and return verdicts
crates/…/gateway.rsShows the proxy boundary, request correlation, secure profile, and response routing
crates/…/mcp.rsShows MCP inventory, drift verification, policy scaffolds, and capability review
crates/…/output_filter.rsShows tool-result scanning, sanitization, warning, and block behavior
crates/…/response_inspect.rsShows inspection of MCP listings, resources, prompts, URIs, and blobs
crates/…/mcp_lock.rsShows the reviewed MCP baseline and live descriptor approval model
crates/…/mcpdrift.rsShows how incomplete coverage, static drift, and tool policy violations become findings