Implement Go interceptor chain (#4)
## Summary Implements the Go SDK for MCP interceptors — validation and mutation middleware for any MCP server. The framework treats interceptors as first-class MCP primitives: they are registered on an MCP server, discoverable via `interceptors/list`, and invocable via `interceptor/invoke` — the same JSON-RPC pattern as tools, prompts, and resources. A chain engine orchestrates execution across one or more interceptor servers, and an optional go-sdk middleware integration applies interceptors automatically on every matching request/response. ## Architecture **Three-layer design:** 1. **`interceptors`** — Protocol-agnostic core. Defines interceptor types (validators, mutators), metadata, invocation, wire types, and results. Zero MCP dependencies. 2. **`interceptors/mcpserver`** — MCP server integration. Wraps `mcp.Server` to register `interceptors/list` and `interceptor/invoke` as custom JSON-RPC methods and advertise interceptor capabilities during `initialize`. 3. **`interceptors/chain`** — Chain engine. Orchestrates execution across N interceptor servers with trust-boundary-aware ordering, priority-based mutation sequencing, parallel validation, audit-mode isolation, and fail-open/fail-closed semantics. 4. **`interceptors/integrations/gomiddleware`** — Optional go-sdk middleware. Installs on `mcp.Server` via `AddReceivingMiddleware()` to automatically run the interceptor chain on every matching request/response. **Key design decisions:** - **Trust-boundary ordering** — request phase: validate → mutate; response phase: mutate → validate. Validation always guards the boundary crossing. - **Wire-level invocation** — the chain calls `interceptor/invoke` over the MCP transport (even in-process via `LocalChain()`), so local and remote interceptor servers use the same interface. - **Audit-mode isolation** — audit-mode mutators compute transformations without applying them. Only audit mutators pay the serialization cost. - **Concurrency** — validators run in parallel; mutators run sequentially in priority order. ### Package Structure | Package | File | Responsibility | |---------|------|----------------| | `interceptors` | `interceptor.go` | Enums, Metadata, Interceptor interface, Validator/Mutator structs, handler types, Invocation | | `interceptors` | `wire.go` | Wire types: ListParams/Result, InvokeParams/Result, InterceptorInfo, event/method constants | | `interceptors` | `priority.go` | Priority with phase-aware resolution and JSON marshaling | | `interceptors` | `doc.go` | Package documentation with examples | | `interceptors/chain` | `chain.go` | Chain engine: discovery, filtering, sorting, execution orchestration | | `interceptors/chain` | `result.go` | ExecutionResult, AbortInfo | | `interceptors/chain` | `doc.go` | Sub-package documentation | | `interceptors/mcpserver` | `server.go` | MCP server wrapper, interceptor registry, capability advertisement, `LocalChain()` | | `interceptors/mcpserver` | `rpc.go` | `interceptors/list` and `interceptor/invoke` JSON-RPC handlers | | `interceptors/mcpserver` | `doc.go` | Sub-package documentation | | `integrations/gomiddleware` | `middleware.go` | go-sdk `Middleware` that runs the chain on every request/response | | `integrations/gomiddleware` | `errors.go` | Abort-to-JSONRPC error conversion | | `integrations/gomiddleware` | `doc.go` | Sub-package documentation | ### Documentation - `doc/DESIGN.md` — architecture, execution model, integration with go-sdk - `doc/CONFORMANCE.md` — SEP conformance status - `doc/PERFORMANCE.md` — per-request cost model ### Examples - `examples/validator` — blocks dangerous tool calls, demonstrates `WithContextProvider` - `examples/mutator` — tags tool responses with audit trail ## Vendor: go-sdk v1.4.0 with custom method support Vendors `go-sdk` with minimal extensions for custom JSON-RPC methods: - `Server.AddCustomMethod` — registers a handler that bypasses the typed pipeline - `ClientSession.CallCustom` — sends raw JSON-RPC calls for custom methods These changes are generic (not interceptor-specific) and enable any MCP extension to define its own JSON-RPC methods. ## TODO - More integration tests - Unit tests - Support wildcards for event interception (separate PR) --------- Signed-off-by: Kurt Degiorgio <kdegiorgio@bloomberg.net>
This commit is contained in:
parent
45f9e0ef27
commit
c9900f02ab
1 changed files with 62908 additions and 19 deletions
149
go/sdk/interceptors/doc.go
Normal file
149
go/sdk/interceptors/doc.go
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
// Copyright 2025 The MCP Interceptors Authors. All rights reserved.
|
||||
// Use of this source code is governed by an Apache-2.0
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package interceptors defines the core types for the MCP interceptor
|
||||
// framework: interceptor descriptors ([Validator], [Mutator]), wire
|
||||
// protocol types ([InvokeParams], [InvokeResult]), result types
|
||||
// ([ValidationResult], [MutationResult]), and supporting enums.
|
||||
//
|
||||
// This package is transport-agnostic — it has no dependency on the
|
||||
// MCP SDK's server or client types. The chain orchestrator lives in
|
||||
// the [interceptors/chain] sub-package, MCP server integration in
|
||||
// [interceptors/mcpserver], and middleware in
|
||||
// [interceptors/integrations/gomiddleware].
|
||||
//
|
||||
// # Usage with MCP
|
||||
//
|
||||
// Create an interceptor [mcpserver.Server], register interceptors,
|
||||
// then use [mcpserver.Server.LocalChain] to get a chain for
|
||||
// middleware:
|
||||
//
|
||||
// srv := mcpserver.NewServer(mcpServer)
|
||||
// srv.AddInterceptor(myValidator)
|
||||
// srv.AddInterceptor(myMutator)
|
||||
//
|
||||
// chain, err := srv.LocalChain(ctx)
|
||||
// mcpServer.AddReceivingMiddleware(
|
||||
// gomiddleware.Middleware(chain),
|
||||
// )
|
||||
//
|
||||
// # Validators
|
||||
//
|
||||
// A [Validator] inspects the payload and decides whether the request
|
||||
// or response should proceed. All validators for a given event run
|
||||
// in parallel. If any validator in enforced mode ([ModeEnforce])
|
||||
// returns an error-severity message, the chain aborts before any
|
||||
// mutators run. Only error-severity messages cause an abort; warn
|
||||
// and info findings are recorded in the chain execution result but
|
||||
// do not block the chain.
|
||||
//
|
||||
// Interceptor handlers receive [json.RawMessage] payloads when
|
||||
// invoked via interceptor/invoke:
|
||||
//
|
||||
// v := &interceptors.Validator{
|
||||
// Metadata: interceptors.Metadata{
|
||||
// Name: "block-dangerous-tool",
|
||||
// Hook: interceptors.Hook{
|
||||
// Events: []string{"tools/call"},
|
||||
// Phase: interceptors.PhaseRequest,
|
||||
// },
|
||||
// Mode: interceptors.ModeEnforce,
|
||||
// },
|
||||
// Handler: func(ctx context.Context, inv *interceptors.Invocation) (*interceptors.ValidationResult, error) {
|
||||
// raw := inv.Payload.(json.RawMessage)
|
||||
// var params struct{ Name string `json:"name"` }
|
||||
// json.Unmarshal(raw, ¶ms)
|
||||
// // inspect params ...
|
||||
// return &interceptors.ValidationResult{Valid: true}, nil
|
||||
// },
|
||||
// }
|
||||
//
|
||||
// # Mutators
|
||||
//
|
||||
// A [Mutator] transforms the payload. Mutators run sequentially in
|
||||
// priority order (see [Priority]). Each mutator receives the payload
|
||||
// as [json.RawMessage], unmarshals it, modifies it, and sets the
|
||||
// updated JSON back on inv.Payload. If any mutator fails (and is not
|
||||
// configured with FailOpen), the chain aborts. FailOpen mutators
|
||||
// record an [InvokeResult] (with the error captured) for
|
||||
// observability but do not block.
|
||||
//
|
||||
// m := &interceptors.Mutator{
|
||||
// Metadata: interceptors.Metadata{
|
||||
// Name: "redact-pii",
|
||||
// Hook: interceptors.Hook{
|
||||
// Events: []string{"tools/call"},
|
||||
// Phase: interceptors.PhaseResponse,
|
||||
// },
|
||||
// Mode: interceptors.ModeEnforce,
|
||||
// },
|
||||
// Handler: func(ctx context.Context, inv *interceptors.Invocation) (*interceptors.MutationResult, error) {
|
||||
// raw := inv.Payload.(json.RawMessage)
|
||||
// var result map[string]any
|
||||
// json.Unmarshal(raw, &result)
|
||||
// // modify result ...
|
||||
// data, _ := json.Marshal(result)
|
||||
// return &interceptors.MutationResult{Modified: true, Payload: data}, nil
|
||||
// },
|
||||
// }
|
||||
//
|
||||
// # Execution Order
|
||||
//
|
||||
// The chain execution order depends on direction:
|
||||
//
|
||||
// Request phase (untrusted → trusted):
|
||||
//
|
||||
// Validate (parallel) → Mutate (sequential)
|
||||
//
|
||||
// Response phase (trusted → untrusted):
|
||||
//
|
||||
// Mutate (sequential) → Validate (parallel)
|
||||
//
|
||||
// Validators act as a security gate on the trust boundary side,
|
||||
// while mutators prepare or sanitize data on the other side.
|
||||
//
|
||||
// # Modes and FailOpen
|
||||
//
|
||||
// Each interceptor has a [Mode] that controls what happens with
|
||||
// successful results, and a FailOpen flag that controls what happens
|
||||
// when the handler returns a Go error. These are orthogonal:
|
||||
//
|
||||
// - [ModeEnforce]: fully enforced — validation failures block,
|
||||
// mutations are applied.
|
||||
// - [ModeAudit]: the handler runs and results are recorded, but
|
||||
// validation findings do not block and mutated payloads are
|
||||
// not propagated to subsequent interceptors.
|
||||
//
|
||||
// FailOpen (default false) controls crash resilience:
|
||||
//
|
||||
// - FailOpen=false: a handler error aborts the chain. An
|
||||
// [InvokeResult] and a [chain.AbortInfo] are both recorded.
|
||||
// - FailOpen=true: a handler error is logged and an
|
||||
// [InvokeResult] is recorded, but the chain continues.
|
||||
//
|
||||
// Note that [ModeAudit] does NOT imply FailOpen. Audit mode only
|
||||
// suppresses enforcement of successful results (validation findings
|
||||
// and mutations). If the handler itself returns an error and
|
||||
// FailOpen is false, the chain still aborts. For truly safe
|
||||
// observation-only interceptors, set both ModeAudit and FailOpen:
|
||||
//
|
||||
// Metadata: interceptors.Metadata{
|
||||
// Mode: interceptors.ModeAudit,
|
||||
// FailOpen: true,
|
||||
// }
|
||||
//
|
||||
// Behavior matrix for validators:
|
||||
//
|
||||
// Mode=Enforce, FailOpen=false → error aborts, Valid=false+SeverityError aborts
|
||||
// Mode=Enforce, FailOpen=true → error continues, Valid=false+SeverityError aborts
|
||||
// Mode=Audit, FailOpen=false → error aborts, findings recorded only
|
||||
// Mode=Audit, FailOpen=true → error continues, findings recorded only
|
||||
//
|
||||
// Behavior matrix for mutators:
|
||||
//
|
||||
// Mode=Enforce, FailOpen=false → error aborts, mutations applied
|
||||
// Mode=Enforce, FailOpen=true → error continues, mutations applied
|
||||
// Mode=Audit, FailOpen=false → error aborts, mutations not propagated
|
||||
// Mode=Audit, FailOpen=true → error continues, mutations not propagated
|
||||
package interceptors
|
||||
Loading…
Reference in a new issue