You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
C# SDK: SEP-2624 invoker policy, rejection handling, and two samples - #52
C# SDK: SEP-2624 invoker policy, rejection handling, and two samples
This brings the C# SDK in line with the current docs/sep.md and adds two samples that show interceptors as out-of-process middleware: a scripted demo for people new to interceptors, and a proxy you can put in front of an existing MCP server.
The library changes are large (40 files under src/). The commits are split by topic and can be reviewed one at a time.
SEP alignment
Chain removal (SEP: Remove the chain concept, keep the execution mechanics #44). Public types are renamed: InterceptorChain → InterceptorOrchestrator, ExecuteChainRequestParams → InterceptorExecutionRequest, InterceptorChainResult → InterceptorExecutionResult, ExecuteChainAsync → ExecuteInterceptorsAsync, and so on.
Invoker overrides.InterceptorOverrides (failOpen, priorityHint, mode, timeoutMs, hooks) is resolved per interceptor: override, then declared value, then SEP default. Hook overrides that widen the declared hooks are rejected. InterceptorPolicy adds which interceptors apply (Include, fail-closed if one is missing), per-interceptor config, and a default timeout.
Timeouts. A per-interceptor timeout is routed by fail-open. The aggregate timeout covers discovery and every invocation in a phase, and fails the operation when it elapses. Previously one chain-wide timeout was also sent as every interceptor's timeoutMs, and fail-open interceptors still failed the operation when they timed out.
Audit trail.InterceptorInvocation records each invocation's resolved mode and failOpen, and whether each came from an override, the declaration or the SEP default (Security Best Practice 3).
Behavior fixes
A tools/call blocked by the gateway reached clients as "An error occurred invoking 'fetch'." because the exception was not an McpException, so the SDK hid the message.
Rejections are now McpInterceptorException / McpInterceptorValidationException (-32602 with data.validationErrors).
By default, the gateway returns a rejected tools/call as an isError result whose text gives the reason, with the SEP details under _meta["io.modelcontextprotocol/interceptors"].
ToolCallRejection = ProtocolError returns the JSON-RPC error instead.
Sinks were awaited, so a slow sink delayed every call. They now run in the background on a snapshot of the payload.
The gateway sent interceptors/list in both phases of every request. Discovery is now cached per interceptor server (one minute by default) and follows nextCursor. A failing or stalled interceptor server rejects the operation (fail-closed).
Tools listed through InterceptingMcpClient were bound to the inner client, so calling them skipped the interceptors. This predates the branch. They are now InterceptedMcpClientTool, an AIFunction routed through the wrapper. List results also apply response mutations; before, those mutations were discarded.
Attribute-based interceptor servers reported "Exception has been thrown by the target of an invocation" for any failure. They now report the interceptor's own error.
The gateway strips per-request protocol _meta (protocolVersion, clientInfo, clientCapabilities, logLevel) before forwarding. The SDK merges capabilities, so a downstream client's capability opt-ins reached the backend.
The two hops of the gateway negotiate protocol versions independently. When the backend hop is on 2026-07-28 or later, the gateway now answers logging/setLevel itself instead of forwarding a method the backend no longer has. Found with the MCP Inspector CLI.
Seven copy-pasted proxy handlers are now one forwarding path. Completions, resource templates and unsubscribe are interceptable too.
Interoperability
A result's type no longer has to be the first JSON property. Before this, results from SDKs that serialize interceptor first failed to deserialize.
WhyInterceptorsDemo: a scripted terminal demo in four acts: one agent and one MCP server connected directly, then through an interceptor proxy, then with the guard in audit mode via an invoker override, then the recorded interceptor/invoke exchange. The agent's reasoning is scripted; every MCP message is real. Run dotnet run --project csharp/sdk/samples/WhyInterceptorsDemo.
InterceptorProxy: a JSON-configured stdio proxy, the "common interceptor sidecar" from the SEP's reference implementation section. The config's policy section mirrors InterceptorOverrides. --check validates the policy against the discovered interceptors. Verified with the MCP Inspector CLI as the client and with the reference filesystem server as the backend.
samples/README.md gives a start-here path. The C# README now opens with an overview.
Breaking changes
The chain renames above.
InterceptorExecutionRequest no longer has InterceptorNames or Config; use InterceptorPolicy.
InterceptorExecutionResult.FinalPayload is null when the operation is rejected.
InterceptingMcpClient.ListToolsAsync returns InterceptedMcpClientTool; ListPromptsAsync and ListResourcesAsync return protocol Prompt and Resource.
McpInterceptorValidationException is now an McpProtocolException.
ValidationMessage.Severity is nullable.
Questions for the SEP
These came up while implementing. The current choice is in parentheses.
How a gateway reports a blocked tools/call. The SEP shows a JSON-RPC error. Clients pass isError tool results to the model more reliably (an isError result by default, with a protocol-error option).
Audit mode vs. the aggregate timeout. The aggregate timeout says to treat the operation as timed out, while audit mode "MUST NOT block" (audit-mode interceptors cut off by the aggregate are logged and do not fail the operation).
Discovery has no expiry or list_changed notification (cached for one minute).
Whether proxies should be told to treat per-request protocol _meta as hop-by-hop (stripped).
Testing
105 → 186 tests (dotnet test in csharp/sdk). A clean Release build.
WhyInterceptorsDemo --fast runs end to end over real stdio processes.
InterceptorProxy was driven by the MCP Inspector CLI: tools/list, an allowed call, a blocked call returned as isError with the SEP details, and a redacted result. It also ran in front of @modelcontextprotocol/server-filesystem.
An independent review of the engine and gateway found the fail-open verdict, the listed-tool bypass, unbounded discovery and the audit timeout conflict. Those are fixed in the last commit, with tests.
…cept
The SEP no longer defines a chain (#44): executing several interceptors is
invoker-local orchestration over interceptors/list and interceptor/invoke.
Rename the public types so the reference implementation reads like the SEP:
InterceptorChain -> InterceptorOrchestrator
InterceptorChainEntry -> InterceptorBinding
ExecuteChainRequestParams -> InterceptorExecutionRequest
InterceptorChainResult -> InterceptorExecutionResult
InterceptorChainStatus -> InterceptorExecutionStatus
ChainAbortInfo -> InterceptorAbortInfo
ChainValidationSummary -> ValidationSummary
ExecuteChainAsync -> ExecuteInterceptorsAsync
Internal types follow (InterceptorExecutionEngine, InterceptorPhaseRunner).
No behavior change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MqPQYQw5XFogaX5P5KSth2
Execution model (InterceptorExecutionEngine):
- InterceptorOverrides (failOpen, priorityHint, mode, timeoutMs, hook
narrowing) resolved per interceptor: override -> declared -> SEP default.
Overrides that widen declared hooks are rejected.
- InterceptorPolicy: which interceptors apply (Include is fail-closed),
their overrides, per-interceptor config sent as `config`, and a default
per-interceptor timeout.
- Direction is explicit (Sending/Receiving) and derived from an
InterceptorInvokerRole rather than from phase alone (#29). Gateways
default to Client; Server validates requests before mutating them.
- Per-interceptor timeouts are routed by fail-open; the aggregate timeout
cancels the rest and fails the operation. Previously one chain-wide
timeout was also sent as every interceptor's timeoutMs, and a timeout
failed the operation even for failOpen interceptors.
- Every validator completes and every blocking error is reported
(ValidationErrors); previously only the first was.
- Mutations stay atomic; a result of the wrong type fails closed.
- Sinks are dispatched in the background on a payload snapshot. They were
awaited, so a slow sink delayed every call.
- InterceptorInvocation records each invocation's resolved mode/failOpen
and whether each came from an override or the declared default (SEP
Security Best Practice 3), plus its effect (blocked, would_block, ...).
- Verdict rule tracks #51 with the fail-secure reading in one place
(ValidationVerdict): top-level severity, else worst message, else block.
Gateway and InterceptingMcpClient:
- A blocked tools/call reached clients as "An error occurred invoking
'fetch'." because the exception was not an McpException. Rejections are
now McpInterceptorException/McpInterceptorValidationException
(McpProtocolException, -32602 with data.validationErrors per the SEP).
The gateway reports a rejected tools/call as an isError result with the
reason in its text and the SEP details under
_meta["io.modelcontextprotocol/interceptors"]; ToolCallRejection =
ProtocolError returns the JSON-RPC error instead.
- interceptors/list results are cached per interceptor server
(DiscoveryCacheDuration, default 1 minute) instead of re-listing in both
phases of every request, and discovery follows nextCursor.
- Seven copy-pasted proxy handlers become one raw-JSON forwarding path;
completions, resource templates and unsubscribe are now interceptable.
- Options gain Policy, InvokerRole, OnInterceptorsExecuted, LoggerFactory;
invocations carry a timestamp, trace, session and authenticated user.
- InterceptingMcpClient accepts several interceptor servers and applies
response mutations to list results (they were discarded).
Interop:
- Result `type` no longer has to be the first JSON property.
- durationMs/timeoutMs accept fractional numbers (#49).
- A result without `type` is read as the type declared in
interceptors/list (#50).
Tests: 105 -> 146.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MqPQYQw5XFogaX5P5KSth2
…hema
[McpServerInterceptor] gains Version and ConfigSchema (JSON text), so an
interceptor can advertise the config knobs invokers may pass per call.
Methods returning ValueTask<bool> now work; they previously failed to
convert their result.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MqPQYQw5XFogaX5P5KSth2
- Interceptor servers reported "Exception has been thrown by the target of
an invocation" for any failing attribute-based interceptor. Reflection
now invokes with DoNotWrapExceptions, so the invoker sees the real cause.
- The gateway strips per-request protocol metadata (protocolVersion,
clientInfo, clientCapabilities, logLevel) before forwarding to the
backend. It is hop-by-hop: the SDK overwrites version and client info
but merges capabilities, so a downstream client's capability opt-ins
reached the backend as if the gateway supported them. Interceptors
still see the metadata as received.
- InterceptorExecutionResult.OriginalPayload exposes the pre-mutation
payload to observers (for example to show what a redactor changed). It
is not serialized, so audit logs written from results do not capture
pre-redaction content.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MqPQYQw5XFogaX5P5KSth2
…CP middleware
A short terminal demo for people new to interceptors, based on the Dev
Summit exfiltration demo but run through the library's transparent proxy,
so the trace tables show what the proxy actually did.
Act 1 An agent connects to an MCP server with email, CRM and web tools.
It follows an instruction in a newsletter and sends contacts and
billing details to an outside URL.
Act 2 The same agent and server through an interceptor proxy:
pii-redactor removes the card number from the tool result and
exfiltration-guard blocks the outbound call. The agent gets the
reason as a tool error.
Act 3 The proxy runs the guard in audit mode through an invoker
override, without changing the interceptor server. The guard's
audit-trail interceptor has recorded every operation.
Act 4 The recorded interceptor/invoke exchange and the interceptor
that answered it.
The agent's reasoning is scripted for repeatability; every MCP message is
real (two stdio subprocesses plus the in-process proxy). Presenter mode
waits for Enter; --auto, --fast, --act N and --export-html are available.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MqPQYQw5XFogaX5P5KSth2
…07-28+
The gateway's two hops negotiate protocol versions independently. The MCP
Inspector CLI negotiates an older revision with the gateway and sends
logging/setLevel; forwarding it to a 2026-07-28 backend session, where the
method no longer exists (SEP-2577), failed the client's request and the
Inspector aborted. The gateway now accepts it itself in that case.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MqPQYQw5XFogaX5P5KSth2
A stdio MCP server that looks exactly like the server it wraps and runs
every request and response through interceptor servers: the "common
interceptor sidecar" from the SEP's reference implementation section,
built on McpInterceptorGateway. Register it in Claude Code, Claude Desktop
or VS Code in place of the server; neither side changes.
- Config: backend and interceptor servers (stdio or Streamable HTTP),
invokerRole, events, timeouts, tool-call rejection style, and a policy
section mirroring SEP InterceptorOverrides plus per-interceptor config.
${VAR} expansion; paths resolve against the config file.
- --check connects, binds the policy against what was discovered and
reports missing required interceptors or widening hook overrides.
- One stderr line per intercepted phase; optional JSON-lines audit log
with each invocation's resolved mode/failOpen and their sources
(SEP Security Best Practice 3), without payloads.
- demo.json wraps the WhyInterceptorsDemo servers; filesystem.json puts
the pii-redactor in front of the reference TypeScript filesystem server.
Verified with the MCP Inspector CLI as the client (tools/list, an allowed
call, a blocked exfiltration attempt returned as isError with the SEP
details, and a redacted result) and against the npm filesystem server.
The demo's servers now identify as acme-workspace and security-guard.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MqPQYQw5XFogaX5P5KSth2
- README opens with an overview and points to the two demos, then
documents the current API: writing interceptor servers, the three ways
to invoke them, the execution model (direction, atomic mutations,
verdict rule, failure routing), InterceptorPolicy, how rejections
surface, and interop notes. Drops a dead link to
docs/SEP_PROPOSAL_NOTES.md.
- samples/README.md gives a start-here path (WhyInterceptorsDemo,
InterceptorProxy, InterceptorServerSample) and a table of the API samples.
- READMEs for WhyInterceptorsDemo and InterceptorProxy.
- CLAUDE.md and ARCHITECTURE_PHASES.md updated for the new engine, the
rejection handling and the removal of the chain concept; older samples
no longer call it a chain.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MqPQYQw5XFogaX5P5KSth2
…emo and docs
Rewrite the demo narration and READMEs in a plainer voice. Interceptors
are described as a standard way to build out-of-process middleware for
MCP clients, gateways and servers, with the exfiltration scenario as one
use case. Acts are renamed (Without middleware, With an interceptor proxy,
Policy set by the deployer, On the wire), and "attacker" identifiers
become ExternalDomain/ReceivedBy.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MqPQYQw5XFogaX5P5KSth2
- Fail-open verdict: ValidationMessage.Severity was a non-nullable enum
defaulting to info, so an invalid result whose messages carried no
severity passed. Severity is now nullable and a missing one counts as
error in an invalid result (ValidationVerdict.SeverityOf).
- Tools listed through InterceptingMcpClient were McpClientTools bound to
the inner client, so calling them (or handing them to an IChatClient)
skipped interceptors. ListToolsAsync now returns InterceptedMcpClientTool,
an AIFunction routed through the wrapper; prompts and resources are
returned as protocol definitions. This predates the branch.
- The aggregate timeout did not cover discovery, and a stalled
interceptors/list could hang an operation forever. Discovery now runs
under the aggregate budget, each shared discovery is capped at 30 s,
listing stops on a repeated cursor, and discovery failures are
reported as interceptor rejections (fail-closed) instead of leaking the
interceptor server's raw error to the downstream client.
- A slow audit-mode interceptor could fail an operation through the
aggregate timeout, contradicting "audit MUST NOT block". Audit-mode
invocations cut off by the aggregate are recorded as timed out.
- A rejected operation serialized its pre-redaction payload as
finalPayload. FinalPayload is now null on rejection.
- Background sinks could run against per-request interceptor clients the
gateway had already disposed; disposal now waits for them without
holding up the response.
- Non-positive timeouts are rejected (overrides, policy, engine, gateway
options, and on the interceptor server with -32602); the
string-based McpInterceptorValidationException sets data.validationErrors;
a gateway comment no longer claims unmodeled fields survive the hop.
Tests: 149 -> 158.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MqPQYQw5XFogaX5P5KSth2
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Unresolved critical issues allow uppercase URL schemes to bypass the destination allowlist and serialized execution results to expose pre-redaction payloads even when redaction fails closed.
This PR aligns the C# interceptor SDK with SEP-2624’s invoker-owned orchestration model and adds two samples showing out-of-process middleware for MCP traffic.
Changes:
Replaces chain APIs with orchestration, policy overrides, explicit direction, timeout handling, validation verdicts, and invocation records.
- Serialized execution results omit mutation payloads. Results and
Invocations[].Result carried each mutator's output, which is
pre-redaction content when a later mutator redacts, even when the
operation was rejected. The interceptor/invoke wire result is unchanged.
- The static InterceptorOrchestrator.ExecuteAsync starts the aggregate
timeout before discovery and gives the invocations what is left. A
timeout during discovery returns a Timeout result.
- Discovery with caching off is still bounded by the discovery timeout.
- Concurrent callers on a cold or expired discovery cache share one
listing; a failed entry is only removed if it has not been replaced.
- A positive fractional timeoutMs or durationMs never rounds to zero.
- InterceptorProxy expands ${VAR} after parsing the config, so values
with backslashes or quotes arrive unchanged.
- WhyInterceptorsDemo's exfiltration-guard matches URL schemes
case-insensitively.
Tests: 158 -> 164.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MqPQYQw5XFogaX5P5KSth2
The destination allowlist only sees HTTP(S) URLs. A tools/call argument such as ftp://evil.example/sync?contacts=dana%40acme.example produces no matches, so BlockUnapprovedDomains returns success despite the unapproved destination; even the sample's FetchUrl accepts that absolute URI. This also affects the guard reused by InterceptorProxy. Please inspect every URL scheme supported by the backend, or explicitly reject unsupported schemes rather than silently allowing them.
Reuse in-flight discoveries regardless of cache TTL
An entry expires even while its shared discovery is still running. For example, with a 1-second DiscoveryCacheDuration and a 5-second listing, a caller arriving after 2 seconds starts another interceptors/list instead of joining the first one. Further callers can keep launching overlapping discoveries, defeating coalescing precisely when the interceptor server is slow. Please reuse in-flight discoveries regardless of the result TTL, and apply expiry only to completed entries.
- A timeout budget used up by discovery now fails the operation. The
phase runner and the static InterceptorOrchestrator.ExecuteAsync gave
the interceptors at least 1 ms, so with no applicable interceptors an
operation could be forwarded after the deadline.
- The discovery cache always joins a listing in progress, and a result's
TTL counts from when its listing completed. A listing slower than the
TTL no longer causes overlapping listings.
- WhyInterceptorsDemo's exfiltration-guard blocks URLs with any scheme
other than http and https instead of skipping them, and fetch_url
accepts only absolute http and https URLs.
Tests: 164 -> 167.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MqPQYQw5XFogaX5P5KSth2
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Crafted URLs can bypass the destination allowlist to reach unapproved hosts, and config-relative executable paths can fail when launched from another directory.
The destination allowlist can be bypassed with https://acme.example'@evil.example/collect: the regex approves only https://acme.example, while FetchUrl parses the complete argument with evil.example as its host (runtime parsing rules, default branch). Mixed-slash URLs such as http:/\evil.example/collect are also accepted by Uri but missed entirely by this regex (runtime fixtures, default branch). Validate complete URL arguments with the same parser as the tool, fail closed for ambiguous embedded candidates, and add regression cases for both forms.
Resolve relative proxy commands against the config directory
A config containing "command": "./bin/guard" can fail on Unix when a desktop client launches the proxy from another directory: WorkingDirectory sets the child's directory, not executable lookup. The SDK transport (default branch) passes the command through to ProcessStartInfo.FileName, so this does not implement the documented config-relative paths. Resolve commands containing directory separators against baseDirectory, while preserving bare PATH commands such as dotnet.
- WhyInterceptorsDemo guard: read a URL argument whole with System.Uri,
the parser fetch_url uses. The regex approved "https://acme.example"
out of "https://acme.example'@evil.example/collect", whose host is
evil.example, and missed "http:/\evil.example/collect". URLs inside
longer text run to the next whitespace; one that does not parse is
blocked rather than skipped.
- InterceptorProxy: resolve a command path such as ./bin/guard against
the config file's directory. "cwd" sets the child's working
directory, not where its executable is looked up, so the proxy failed
when started from another directory. Bare names such as dotnet are
still looked up on PATH.
- SampleTests covers both; the test project compiles the three sample
files involved.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MqPQYQw5XFogaX5P5KSth2
Copilot's review of b34c161 says it found URL-allowlist bypasses that it
did not publish. One was still there: in text, a URL could hide another
written right after it, because only the first of them was checked.
"[a](https://acme.example/a),[b](https://evil.example/?d=secret)", a
comma-separated list and a JSON list in a string were all allowed.
The guard now checks every place a URL starts, including a redirect
target inside another URL, and also scans property names.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MqPQYQw5XFogaX5P5KSth2
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Human review is needed to assess URI-validation bypasses, preflight checks that accept invalid startup configurations, and audit serialization overhead for large payloads.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
C# SDK: SEP-2624 invoker policy, rejection handling, and two samples
This brings the C# SDK in line with the current
docs/sep.mdand adds two samples that show interceptors as out-of-process middleware: a scripted demo for people new to interceptors, and a proxy you can put in front of an existing MCP server.The library changes are large (40 files under
src/). The commits are split by topic and can be reviewed one at a time.SEP alignment
InterceptorChain→InterceptorOrchestrator,ExecuteChainRequestParams→InterceptorExecutionRequest,InterceptorChainResult→InterceptorExecutionResult,ExecuteChainAsync→ExecuteInterceptorsAsync, and so on.InterceptorOverrides(failOpen,priorityHint,mode,timeoutMs,hooks) is resolved per interceptor: override, then declared value, then SEP default. Hook overrides that widen the declared hooks are rejected.InterceptorPolicyadds which interceptors apply (Include, fail-closed if one is missing), per-interceptorconfig, and a default timeout.InterceptorInvokerRole(ClientorServer), instead of being inferred from phase.timeoutMs, and fail-open interceptors still failed the operation when they timed out.ValidationErrors. The verdict rule is in one place,ValidationVerdict, using the fail-secure reading of SEP: which severity decides blocking whenvalid,severityandmessages[].severitydisagree? #51.InterceptorInvocationrecords each invocation's resolvedmodeandfailOpen, and whether each came from an override, the declaration or the SEP default (Security Best Practice 3).Behavior fixes
tools/callblocked by the gateway reached clients as "An error occurred invoking 'fetch'." because the exception was not anMcpException, so the SDK hid the message.McpInterceptorException/McpInterceptorValidationException(-32602withdata.validationErrors).tools/callas anisErrorresult whose text gives the reason, with the SEP details under_meta["io.modelcontextprotocol/interceptors"].ToolCallRejection = ProtocolErrorreturns the JSON-RPC error instead.interceptors/listin both phases of every request. Discovery is now cached per interceptor server (one minute by default) and followsnextCursor. A failing or stalled interceptor server rejects the operation (fail-closed).InterceptingMcpClientwere bound to the inner client, so calling them skipped the interceptors. This predates the branch. They are nowInterceptedMcpClientTool, anAIFunctionrouted through the wrapper. List results also apply response mutations; before, those mutations were discarded._meta(protocolVersion,clientInfo,clientCapabilities,logLevel) before forwarding. The SDK merges capabilities, so a downstream client's capability opt-ins reached the backend.2026-07-28or later, the gateway now answerslogging/setLevelitself instead of forwarding a method the backend no longer has. Found with the MCP Inspector CLI.Interoperability
typeno longer has to be the first JSON property. Before this, results from SDKs that serializeinterceptorfirst failed to deserialize.timeoutMsanddurationMsaccept fractional numbers and are written as integers (SEP: say whetherdurationMsandtimeoutMsare integers; SDKs disagree and do not interoperate #49).typeis read as the type declared ininterceptors/list(SEP:interceptor/invokeresponse examples omit the requiredtype,interceptorandphasefields #50).Samples
WhyInterceptorsDemo: a scripted terminal demo in four acts: one agent and one MCP server connected directly, then through an interceptor proxy, then with the guard in audit mode via an invoker override, then the recordedinterceptor/invokeexchange. The agent's reasoning is scripted; every MCP message is real. Rundotnet run --project csharp/sdk/samples/WhyInterceptorsDemo.InterceptorProxy: a JSON-configured stdio proxy, the "common interceptor sidecar" from the SEP's reference implementation section. The config'spolicysection mirrorsInterceptorOverrides.--checkvalidates the policy against the discovered interceptors. Verified with the MCP Inspector CLI as the client and with the reference filesystem server as the backend.samples/README.mdgives a start-here path. The C# README now opens with an overview.Breaking changes
InterceptorExecutionRequestno longer hasInterceptorNamesorConfig; useInterceptorPolicy.InterceptorExecutionResult.FinalPayloadisnullwhen the operation is rejected.InterceptingMcpClient.ListToolsAsyncreturnsInterceptedMcpClientTool;ListPromptsAsyncandListResourcesAsyncreturn protocolPromptandResource.McpInterceptorValidationExceptionis now anMcpProtocolException.ValidationMessage.Severityis nullable.Questions for the SEP
These came up while implementing. The current choice is in parentheses.
valid,severityandmessages[].severitydisagree? #51: which signal decides blocking (the fail-secure reading: top-level severity, then the most severe message, and an invalid result with no severity blocks).tools/call. The SEP shows a JSON-RPC error. Clients passisErrortool results to the model more reliably (anisErrorresult by default, with a protocol-error option).list_changednotification (cached for one minute)._metaas hop-by-hop (stripped).Testing
dotnet testincsharp/sdk). A clean Release build.WhyInterceptorsDemo --fastruns end to end over real stdio processes.InterceptorProxywas driven by the MCP Inspector CLI:tools/list, an allowed call, a blocked call returned asisErrorwith the SEP details, and a redacted result. It also ran in front of@modelcontextprotocol/server-filesystem.🤖 Generated with Claude Code