MCP gateway and content controls
Tirith places a policy boundary between an MCP client and an upstream MCP server. It accepts JSON-RPC traffic, checks requests and server responses, and forwards only traffic that meets the active content and execution rules. The page Agent and MCP protection gives the wider protection model. Agent context and prompt safety covers the related agent and prompt controls.
System boundary
Gateway role
The MCP gateway is a local proxy for an existing MCP server. It preserves the client-facing MCP connection while adding command checks, request tracking, response checks, audit records, and optional upstream containment. The gateway treats both client input and upstream output as untrusted at the boundary.
The gateway can run in a permissive compatibility mode or a stricter mode. The secure gateway profile enables the output protections and requires a contained upstream. Explicit gateway settings can still select the behavior for individual policy controls.
References: crates/…/gateway.rs• L27-46 crates/…/gateway.rs• L2766-2797 crates/…/gateway.rs• L2986-3115
MCP server role
The tirith mcp-server command exposes Tirith's own checks as MCP tools and exposes a project safety report as an MCP resource. It speaks JSON-RPC over standard input and output. Its output sanitizer is enabled by default and protects results that Tirith sends to the calling agent; an explicit compatibility choice can disable it.
The gateway and the MCP server are separate use cases. The gateway protects traffic to another server. The MCP server provides Tirith capabilities directly to a client.
References: crates/…/dispatcher.rs• L14-40 crates/…/dispatcher.rs• L293-355 crates/…/main.rs• L1046-1068
Request and response flow
Gateway message flow
The gateway reads one JSON-RPC message at a time from the client and from the upstream process. It rejects malformed, ambiguous, or duplicate-key messages before policy evaluation, then validates the message shape before it applies a tool rule or forwards canonical bytes. Batch requests are denied until the gateway can intercept each item with the same controls.
The diagram shows the main path from a client request to a checked response.
flowchart LR
C[MCP client] --> V[Validate JSON-RPC boundary]
V --> R[Classify request]
R --> G[Check tool and schema policy]
G --> A[Analyze guarded command]
A --> U[Forward to upstream MCP server]
U --> M[Match response to pending request]
M --> I[Inspect or filter response]
I --> O[Restore client id and forward]
O --> C
G --> D[Return a deny response]
I --> D
Requests without a command guard still use the request and response boundary when output protection is active. This keeps an unsolicited or unknown upstream response from becoming a client-visible message without an owned request.
References: crates/…/gateway.rs• L79-97 crates/…/gateway.rs• L5453-5520 crates/…/gateway.rs• L5884-5999 crates/…/gateway.rs• L6235-6287
Request correlation
The pending-request record is the gateway's proof that a response belongs to a client request. It stores the original client id and the checks selected for that request. The upstream sees a random proxy id. The client sees its original id again after the response passes the gateway.
The record remains present after a timeout or cancellation as a tombstone. A late response is therefore recognized as late instead of becoming an untracked response. Closed failure mode blocks it. Open failure mode drops it. Neither path forwards the late upstream bytes.
References: crates/…/gateway.rs• L793-810 crates/…/gateway.rs• L828-902 crates/…/gateway.rs• L1154-1213 crates/…/gateway.rs• L6649-6685
Tool and resource surfaces
Tool dispatch
The MCP server maps a tool name to one of Tirith's safety actions. These actions check commands, URLs, pasted text, files, directories, and MCP configuration. A tool returns an MCP tool result with readable content and, where useful, structured data.
The gateway applies an additional command guard to selected upstream tools. A guard matches a tool name and extracts a command from its parameters. The extracted command goes through the command safety engine before the request can reach the upstream server.
References: crates/…/tools.rs• L34-183 crates/…/gateway.rs• L5390-5450 mcp/tirith-gateway.yaml• L10-24
Resource handling
The MCP server provides a project safety resource. Reading it scans the current working area and returns a report with scan counts, findings, and any incomplete-coverage signal. The resource uses an internal tirith:// URI and does not ask the client to fetch a network resource.
The gateway does not treat resources as harmless metadata. It inspects resource listings, resource reads, resource templates, and resources embedded in other MCP content before forwarding them. It also checks network-capable URLs hidden in response metadata.
References: crates/…/resources.rs• L7-19 crates/…/resources.rs• L37-106 crates/…/response_inspect.rs• L454-533 crates/…/response_inspect.rs• L536-679
MCP session lifecycle
The MCP server starts in an uninitialized state. It accepts initialize, negotiates a supported protocol version, and then serves tools and resources. It treats notifications/initialized as the transition to the ready state. Invalid messages receive JSON-RPC errors rather than entering the dispatch path.
The gateway preserves this protocol boundary while it proxies the upstream session. It also handles notifications and server-initiated messages separately because they do not have the same request-response ownership as a normal client call.
References: crates/…/dispatcher.rs• L7-13 crates/…/dispatcher.rs• L154-239 crates/…/dispatcher.rs• L243-346 crates/…/gateway.rs• L6001-6110
Origin resolution
MCP client origin
An MCP origin identifies the client that opened an MCP server session. The dispatcher reads initialize.clientInfo and records a sanitized client name and optional version. If the client omits or sends invalid identity data, Tirith records unknown-mcp-client rather than treating the call as a human CLI call.
The origin is caller-claimed and supports audit and policy decisions. It is not proof against a hostile client. Tool verdicts carry the MCP origin so agent rules and audit consumers can distinguish MCP calls from other Tirith entry points.
References: crates/…/dispatcher.rs• L362-387 crates/…/origin.rs• L16-57 crates/…/agent_origin.rs• L36-80
Gateway origin
A verdict created while the gateway checks an upstream command is marked with the gateway origin. Gateway audit events use the same origin marker. This separates a policy decision made at the proxy from a decision made by the MCP server or by a direct CLI call.
Origin labels are bounded and sanitized before they enter audit data. This limits the effect of hostile names or versions on logs, but it does not make the caller identity trustworthy.
References: crates/…/gateway.rs• L630-710 crates/…/gateway.rs• L6137-6147 crates/…/agent_origin.rs• L162-189
Content inspection
Tool result typing
Tool results can contain text, images, audio, resource links, embedded resources, structured content, and fields added by a server. Tirith types the content it knows and preserves unknown content instead of silently dropping or converting it to text. This keeps the response lossless while still giving the filter a view of all string data.
The default compatibility mode keeps unknown blocks. Strict typing is available to callers that require complete coverage. A malformed result shape is not quietly treated as an empty result.
References: crates/…/content.rs• L1-35 crates/…/content.rs• L41-119 crates/…/content.rs• L178-240 crates/…/content.rs• L270-307
Tool schema checks
When output protection is active, the gateway learns each tool's input and output contract from tools/list. It checks call arguments against inputSchema before forwarding a call. It checks structuredContent against the pinned outputSchema before forwarding the response.
A declared schema that cannot compile suspends the tool. A valid schema with invalid data blocks the affected call. The gateway also rechecks the exact sanitized response because sanitization can change structured keys or values.
References: crates/…/content.rs• L311-468 crates/…/gateway.rs• L1478-1513 crates/…/gateway.rs• L1635-1697 crates/…/gateway.rs• L1901-1971 crates/…/gateway.rs• L6522-6645
Listing and reading inspection
The gateway inspects tools/list, resource lists and reads, resource templates, and prompt lists and reads. It scans every string leaf, including object keys, for unsafe output. It also checks network-capable resource links and metadata against the fetch URL policy.
Inline resource blobs receive a second check. Tirith bounds the decoded data, checks strict base64 decoding, and compares leading bytes with the declared MIME type. An unsafe URI, an oversized blob, an undecodable blob, or a MIME mismatch blocks the response.
References: crates/…/response_inspect.rs• L171-220 crates/…/response_inspect.rs• L358-452 crates/…/response_inspect.rs• L1350-1479 crates/…/response_inspect.rs• L1628-1669
Generic response inspection
Responses outside the typed listing and tool-result families still cross a generic text boundary when output protection is active. This covers server-provided text such as initialization instructions and completion results. JSON-RPC error objects are also checked, including nested data and extension fields.
This broad boundary prevents a server from moving unsafe content into a response field that has no dedicated MCP shape. Server-initiated requests remain denied until the gateway can prove that the client negotiated the needed capability. Under the hardened output posture, passive notifications are scanned and sanitized before forwarding.
References: crates/…/gateway.rs• L6001-6110 crates/…/gateway.rs• L6414-6647 crates/…/gateway.rs• L6825-6906
Output filtering
Filter decisions
The output filter analyzes tool text and structured string leaves before the result reaches the agent. It applies one of three outcomes:
- Allow: Forward the result after display-control sanitization.
- Warn: Keep the result shape, add a warning item, and sanitize forwarded strings.
- Block: Replace the result with a safe placeholder and set
isErrortotrue.
The filter checks built-in and operator-supplied injection seeds. An opt-in redaction setting can downgrade a block only when the finding is an injection seed that can be removed safely from text content. Other findings and uncertain cases remain blocks.
The block uses an MCP tool result rather than a JSON-RPC error because the request was handled at the protocol level. The result includes an event id that links the agent-facing placeholder to the audit record.
References: crates/…/output_filter.rs• L350-399 crates/…/output_filter.rs• L534-615 crates/…/output_filter.rs• L1899-1925
Display sanitization
Forwarded content is scrubbed for terminal controls and deceptive invisible characters. The scrub applies to text, structured data values, and structured object keys. Tirith rescans the rewritten value so that removing controls cannot join hidden text into a new unsafe phrase.
Unknown and non-text content is preserved in shape when the result is allowed or warned. A key collision caused by sanitization is treated as a block because choosing one of the colliding values would forward data that was not validated. A result that is too large for presentation is compacted only after the security scan completes.
References: crates/…/output_filter.rs• L581-614 crates/…/output_filter.rs• L617-730 crates/…/output_filter.rs• L831-865 crates/…/output_filter.rs• L1801-1897
Output filter surfaces
Output filtering is opt-in on the normal gateway. The gateway's --filter-output flag protects upstream responses. The MCP server enables its tool-result sanitizer by default; its explicit compatibility option can turn that protection off.
The gateway turns output protection on automatically for the secure profile and for descriptor approval or an active descriptor baseline. This keeps descriptor and schema checks from appearing enabled while their response path is inactive.
References: crates/…/dispatcher.rs• L20-33 crates/…/gateway.rs• L2786-2797 crates/…/gateway.rs• L3103-3133
Gateway integration
Configuration contract
Gateway configuration names the upstream tools that need command analysis and the parameter paths that contain their commands. The policy block controls warning behavior, failure behavior, message size, and pending-response lifetime. A warning can be forwarded with findings or treated as a denial. Analysis failures can be forwarded in open mode or denied in closed mode.
The sample configuration covers common POSIX, PowerShell, and generic execution tool names. Teams should treat these patterns and extraction paths as a contract with the upstream tool descriptions they deploy.
References: mcp/tirith-gateway.yaml• L1-68 crates/…/gateway.rs• L193-254 crates/…/gateway.rs• L303-394
Descriptor approval
An approved descriptor baseline records the exact tool surface that an operator reviewed for one source-qualified MCP server. During a later run, a changed or added tool is held out of tools/list and cannot be called until it is reviewed again. The live upstream launch must match the approved server and launch identity.
Descriptor approval is a one-shot capture of an inspected tools/list response. The gateway persists the approved set atomically, installs it in the live call gate, and then ends the capture session.
References: crates/…/gateway.rs• L2726-2764 crates/…/gateway.rs• L7064-7118 crates/…/gateway.rs• L7317-7394
Upstream containment
The gateway can start the upstream MCP server in an operating-system containment capsule. The contained launch denies network access, limits inherited environment and handles, and applies resource limits. If the host cannot enforce the requested containment, the gateway refuses to start the upstream.
The secure profile requires containment even when the operator does not pass the explicit capsule flag. This makes the profile's hardened promise apply to the upstream process as well as to message inspection.
References: crates/…/gateway.rs• L1997-2062 crates/…/gateway.rs• L2064-2095 crates/…/gateway.rs• L2766-2797 crates/…/gateway.rs• L3057-3092
Audit integration
Gateway decisions are emitted as JSON lines on the diagnostic stream. The events cover command decisions, response filtering, schema checks, descriptor drift, pending-request lifecycle, and server messages. Events carry stable reason or rule fields so operators can link a denial to the part of the boundary that made it.
The gateway uses an MCP-specific origin marker in its audit entries. Output-filter placeholders and descriptor or response blocks therefore provide both an agent-facing result and an operator-facing audit trail.
References: crates/…/gateway.rs• L610-710 crates/…/gateway.rs• L6701-6711 crates/…/gateway.rs• L6778-6789 crates/…/gateway.rs• L7119-7173
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the request method classification aligned with the response inspection families. A method added to one side can otherwise receive no inspection or the wrong response shape.
- Keep the tool descriptor cache, descriptor baseline, and call gate aligned. A live-list change must affect both what the client sees and what calls the gateway permits.
- Preserve the original-id and proxy-id contract when changing request handling. A response must never reach the client unless its proxy id maps to an owned request.
- Keep output sanitization and its final rescan aligned with schema validation. A rewritten structured result must be checked as the exact value that crosses the wire.
- Keep
--filter-output, the secure profile, descriptor approval, and descriptor-baseline loading consistent. Enabling one protected path must not leave its dependent response checks inactive. - Keep MCP origin stamping distinct from gateway origin stamping so audit and agent policy consumers do not misclassify the caller.
- Keep the JSON-RPC error path under the same content boundary as result responses. Error data and extension members are also upstream-controlled content.
- Keep compatibility typing lossless while ensuring every preserved string leaf and top-level extension still reaches inspection.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Upstream sends an unknown or duplicate response id | The gateway could create an unowned client-visible response | Pending-request correlation rejects the response before forwarding |
| A response arrives after its request deadline | Stale upstream content could bypass inspection | Timeout tombstones classify the response as late; closed mode blocks and open mode drops it |
| A declared tool schema cannot compile | The gateway cannot prove the tool contract | The tool is suspended and removed from the forwarded tool list |
| Tool arguments or structured output violate a valid schema | The call or response is off the server's declared contract | The gateway returns a keyed deny response |
| Resource URI resolves to a private, metadata, or forbidden target | The client may fetch an unsafe destination | URI inspection blocks the listing or read |
| Resource blob is too large, invalid base64, or MIME-spoofed | A client may materialize content that inspection did not safely classify | Bounded decoding and MIME checks block the response |
| Response structure exceeds the inspection work budget | Part of the response could remain unexamined or consume excessive resources | The gateway records an incomplete-analysis violation and blocks the response |
| Sanitization makes two structured keys equal | Forwarding either value would change unvalidated data | The gateway blocks on the key collision |
| Active server request lacks proven client capability | An upstream server could gain a direct user or model interaction channel | Hardened gateway handling drops the request |
| Secure or closed gateway cannot load its descriptor baseline or containment backend | The advertised protection cannot be established | Gateway startup fails before the upstream is launched |
Key files
| File | Why to read it |
|---|---|
| crates/…/gateway.rs | Main gateway lifecycle, request correlation, command gating, response routing, descriptor enforcement, and audit integration |
| crates/…/dispatcher.rs | MCP server session lifecycle, method dispatch, origin capture, and server-side output protection |
| crates/…/tools.rs | Tirith's MCP tool surface and tool-result production |
| crates/…/resources.rs | Project safety resource listing and report generation |
| crates/…/content.rs | Lossless tool-result typing and schema validation boundary |
| crates/…/response_inspect.rs | Inspection rules for listings, resources, prompts, URIs, templates, and blobs |
| crates/…/output_filter.rs | Allow, warn, block, display-sanitization, and bounded output behavior |
| crates/…/origin.rs | MCP client-origin capture and session attribution |
| crates/…/agent_origin.rs | Shared origin model and trust limits |
| mcp/tirith-gateway.yaml | Operator-facing gateway tool and policy contract |
| docs/mcp-output-filter.md | Wire behavior and audit contract for output filtering |