|
| 1 | +# Go SDK Interceptors — Design Document |
| 2 | + |
| 3 | +## Integration Point: Receiving Middleware |
| 4 | + |
| 5 | +The go-sdk processes an incoming JSON-RPC message in this order: |
| 6 | + |
| 7 | +``` |
| 8 | +Transport (SSE / stdio) |
| 9 | + → JSON-RPC decode |
| 10 | + → Params deserialization (json.RawMessage → typed struct) |
| 11 | + → Receiving middleware chain ← we hook in here |
| 12 | + → Method handler (e.g. tool handler) |
| 13 | + → Result returned through middleware |
| 14 | + → JSON-RPC encode |
| 15 | + → Transport |
| 16 | +``` |
| 17 | + |
| 18 | +## Capability Declaration |
| 19 | + |
| 20 | +During initialization, the middleware intercepts the `"initialize"` response |
| 21 | +and injects interceptor metadata into |
| 22 | +`Capabilities.Experimental["io.modelcontextprotocol/interceptors"]`. This |
| 23 | +follows the same pattern as the variants extension |
| 24 | +(`io.modelcontextprotocol/server-variants`). |
| 25 | + |
| 26 | +The capability payload includes: |
| 27 | +- `supportedEvents` — deduplicated list of events with registered interceptors |
| 28 | +- `interceptors` — full metadata array in wire format |
| 29 | + |
| 30 | +## Request/Response Lifecycle |
| 31 | + |
| 32 | +When a JSON-RPC request arrives, `receivingMiddleware` in |
| 33 | +`mcpserver/server.go` runs the following sequence: |
| 34 | + |
| 35 | +``` |
| 36 | +0. If method == "initialize" → enrich result with capability declaration |
| 37 | +1. Assign typed params to Invocation inv.Payload = req.GetParams() |
| 38 | +2. Run request-phase chain (validate → mutate) |
| 39 | +3. If aborted → return error |
| 40 | +4. Params already modified in place — no unmarshal needed |
| 41 | +5. Call next handler next(ctx, method, req) |
| 42 | +6. Assign result to Invocation inv.Payload = result |
| 43 | +7. Run response-phase chain (mutate → validate) |
| 44 | +8. If aborted → return error |
| 45 | +9. Result already modified in place — no unmarshal needed |
| 46 | +10. Return result |
| 47 | +``` |
| 48 | + |
| 49 | +The JSON-RPC method name is used directly as the event name (e.g. `"tools/call"`). |
| 50 | + |
| 51 | +### Typed Payload — Zero JSON Operations |
| 52 | + |
| 53 | +`Invocation.Payload` is `any`, the live Go value from the go-sdk |
| 54 | +(e.g. `*mcp.CallToolParamsRaw`). Handlers type-assert directly, the |
| 55 | +same pattern as gRPC-Go interceptors (`req any`). No JSON marshaling |
| 56 | +or unmarshaling occurs in the normal path. |
| 57 | + |
| 58 | +```go |
| 59 | +// Validator — type-assert, inspect, return: |
| 60 | +params, ok := inv.Payload.(*mcp.CallToolParamsRaw) |
| 61 | +if !ok { |
| 62 | + return nil, fmt.Errorf("unexpected payload type %T", inv.Payload) |
| 63 | +} |
| 64 | + |
| 65 | +// Mutator — type-assert, modify in place, return: |
| 66 | +result, ok := inv.Payload.(*mcp.CallToolResult) |
| 67 | +if !ok { |
| 68 | + return nil, fmt.Errorf("unexpected payload type %T", inv.Payload) |
| 69 | +} |
| 70 | +result.Content[0] = &mcp.TextContent{Text: "modified"} |
| 71 | +return &MutationResult{Modified: true}, nil |
| 72 | +``` |
| 73 | + |
| 74 | +**Audit mode:** Audit-mode mutators receive a deep-copied payload (via |
| 75 | +`Invocation.withCopiedPayload()`) so their in-place modifications don't |
| 76 | +affect the real struct. The deep copy uses a JSON round-trip |
| 77 | +(`json.Marshal` → `reflect.New` → `json.Unmarshal`). Only audit-mode |
| 78 | +mutators pay this cost. |
| 79 | + |
| 80 | +### Limitations |
| 81 | + |
| 82 | +- **Params must round-trip through JSON faithfully** for audit-mode deep |
| 83 | + copy. All go-sdk param and result types use standard `encoding/json` |
| 84 | + tags, so this holds in practice. |
| 85 | +- **Type assertions require knowing the concrete type.** Interceptors must |
| 86 | + know which type to expect for a given event (e.g. `*mcp.CallToolParamsRaw` |
| 87 | + for `tools/call` requests). The `Events` field on `Metadata` narrows |
| 88 | + which events reach a handler, so single-event interceptors always see |
| 89 | + the expected type. |
| 90 | + |
| 91 | +--- |
| 92 | + |
| 93 | +## What Is and Is Not Intercepted |
| 94 | + |
| 95 | +### Intercepted |
| 96 | + |
| 97 | +All JSON-RPC **method calls** routed through the server's receiving middleware: |
| 98 | + |
| 99 | +| Method | Event | |
| 100 | +|--------|-------| |
| 101 | +| `tools/call` | `EventToolsCall` | |
| 102 | +| `tools/list` | `EventToolsList` | |
| 103 | +| `prompts/get` | `EventPromptsGet` | |
| 104 | +| `prompts/list` | `EventPromptsList` | |
| 105 | +| `resources/read` | `EventResourcesRead` | |
| 106 | +| `resources/list` | `EventResourcesList` | |
| 107 | +| `resources/subscribe` | `EventResourcesSubscribe` | |
| 108 | + |
| 109 | +Unknown methods pass through the middleware untouched. |
| 110 | + |
| 111 | +### Not Intercepted |
| 112 | + |
| 113 | +1. **Progress notifications.** During a tool call, a handler can call |
| 114 | + `session.NotifyProgress()`. These are JSON-RPC *notifications* sent |
| 115 | + directly over the transport — they do not flow through `MethodHandler` |
| 116 | + middleware. Interceptors never see them. |
| 117 | + |
| 118 | +2. **Transport-level SSE streaming.** The Streamable HTTP transport |
| 119 | + multiplexes multiple JSON-RPC messages over a single SSE connection. |
| 120 | + This is connection management, not per-message streaming. Each individual |
| 121 | + method call is still a single request → single response, which the |
| 122 | + middleware intercepts normally. |
| 123 | + |
| 124 | +3. **JSON-RPC notifications** (e.g. `notifications/initialized`, |
| 125 | + `notifications/cancelled`). The go-sdk routes notifications through a |
| 126 | + separate handler path, not through `MethodHandler` middleware. |
| 127 | + |
| 128 | +Notification interception is not defined by the proposal. |
| 129 | +If this becomes necessary, it would require a separate notification middleware |
| 130 | +hook in the go-sdk. |
| 131 | + |
| 132 | +--- |
| 133 | + |
| 134 | +## Chain Execution Model |
| 135 | + |
| 136 | +The `chainExecutor` in `chain_executor.go` implements trust-boundary-aware |
| 137 | +execution: |
| 138 | + |
| 139 | +**Request phase** (receiving data — untrusted → trusted): |
| 140 | +``` |
| 141 | +Validate (parallel) → Mutate (sequential) |
| 142 | +``` |
| 143 | +Validation acts as a security gate before mutations process the data. |
| 144 | + |
| 145 | +**Response phase** (sending data — trusted → untrusted): |
| 146 | +``` |
| 147 | +Mutate (sequential) → Validate (parallel) |
| 148 | +``` |
| 149 | +Mutations prepare/sanitize data, then validation verifies before sending. |
| 150 | + |
| 151 | +### Validator execution |
| 152 | +- All matching validators run in parallel (goroutines). |
| 153 | +- A validator returning `Valid: false` with `Severity: "error"` in enforced |
| 154 | + mode (`Mode: ModeOn`) aborts the chain. |
| 155 | +- `FailOpen: true` validators log errors and record an `ExecutionResult` |
| 156 | + (with `Error` populated) for observability, but don't abort. |
| 157 | + |
| 158 | +### Mutator execution |
| 159 | +- Mutators run sequentially, ordered by `PriorityHint.Resolve(phase)` |
| 160 | + (ascending), with alphabetical name tiebreak. |
| 161 | +- Each mutator modifies the typed payload in place via type assertion on `inv.Payload`. |
| 162 | +- If any mutator fails (and is not `FailOpen`), the chain aborts. |
| 163 | + `FailOpen` mutators record an `ExecutionResult` (with `Error` populated) |
| 164 | + and continue. |
| 165 | +- In `ModeAudit`, the mutator runs on a deep-copied payload and its result |
| 166 | + is recorded, but the real payload is not affected. |
| 167 | + |
| 168 | +### Filtering |
| 169 | +`newChainExecutor` filters the full interceptor set by: |
| 170 | +1. `Mode != ModeOff` |
| 171 | +2. Phase matches (or interceptor phase is `PhaseBoth`) |
| 172 | +3. Event matches (exact match only; wildcard support is planned via `matchesEvent`) |
| 173 | + |
| 174 | +--- |
| 175 | + |
| 176 | +## File Map |
| 177 | + |
| 178 | +### `interceptors/` — protocol-agnostic core (zero MCP imports) |
| 179 | + |
| 180 | +| File | Responsibility | |
| 181 | +|------|---------------| |
| 182 | +| `interceptor.go` | Types (Phase, Mode, InterceptorType, Priority, Severity, Compat), Metadata struct, Interceptor interface, Validator/Mutator structs and handler types | |
| 183 | +| `invocation.go` | Invocation (with audit-mode payload cloning), InvocationContext, Principal — the input to every handler | |
| 184 | +| `result.go` | All outcome types: ValidationResult, MutationResult, ExecutionResult, ChainResult, AbortInfo | |
| 185 | +| `chain.go` | `Chain` public API: `NewChain`, `Add`, `ExecuteForReceiving`, `ExecuteForSending`, `IsEmpty`, `Interceptors` | |
| 186 | +| `chain_executor.go` | `interceptorSnapshot` (atomic snapshot with lazy chain cache), `chainExecutor` struct, `newChainExecutor` (filtering + sorting), `executeForReceiving`, `executeForSending`, `timeoutResult`, `matchesPhase`, `matchesEvent` | |
| 187 | +| `chain_validate.go` | `validatorResult` struct, `runValidators` (parallel dispatch + N=1 fast path), `executeValidator`, `recordValidation` | |
| 188 | +| `chain_mutate.go` | `mutatorOutcome` type + constants, `runMutators` (sequential loop + audit-mode copy), `executeMutator` | |
| 189 | + |
| 190 | +### `interceptors/mcpserver/` — MCP server integration |
| 191 | + |
| 192 | +| File | Responsibility | |
| 193 | +|------|---------------| |
| 194 | +| `server.go` | `Server` wrapper, `receivingMiddleware`, `WithContextProvider`, capability declaration, `NewStreamableHTTPHandler`, `abortToJSONRPCError` | |
| 195 | +| `events.go` | Event name constants for standard MCP methods | |
0 commit comments