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
19 changed files with 62908 additions and 19 deletions
439
go/sdk/interceptors/chain/chain.go
Normal file
439
go/sdk/interceptors/chain/chain.go
Normal file
|
|
@ -0,0 +1,439 @@
|
|||
// 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 chain
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
|
||||
"github.com/modelcontextprotocol/ext-interceptors/go/sdk/interceptors"
|
||||
)
|
||||
|
||||
// ChainEntry pairs an interceptor descriptor with the MCP client
|
||||
// session that hosts it.
|
||||
type ChainEntry struct {
|
||||
Interceptor interceptors.InterceptorInfo
|
||||
Server *mcp.ClientSession
|
||||
}
|
||||
|
||||
// Chain is the SEP-compliant interceptor chain orchestrator. It holds
|
||||
// ChainEntry objects (interceptor descriptors + MCP server connections),
|
||||
// discovers interceptors via interceptors/list, and invokes them via
|
||||
// interceptor/invoke on the appropriate server.
|
||||
type Chain struct {
|
||||
mu sync.Mutex
|
||||
entries []ChainEntry
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
// ChainOption configures a Chain.
|
||||
type ChainOption func(*Chain)
|
||||
|
||||
// WithChainLogger sets the logger for chain execution.
|
||||
// If not set, slog.Default() is used.
|
||||
func WithChainLogger(l *slog.Logger) ChainOption {
|
||||
return func(c *Chain) {
|
||||
c.logger = l
|
||||
}
|
||||
}
|
||||
|
||||
// NewChain creates a new Chain with optional configuration.
|
||||
func NewChain(opts ...ChainOption) *Chain {
|
||||
c := &Chain{}
|
||||
for _, opt := range opts {
|
||||
opt(c)
|
||||
}
|
||||
if c.logger == nil {
|
||||
c.logger = slog.Default()
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// ExecutionParams configures a chain execution run. These are
|
||||
// SDK-level types used by Chain.Execute, not wire-protocol types.
|
||||
type ExecutionParams struct {
|
||||
Event string `json:"event"`
|
||||
Phase interceptors.InterceptionPhase `json:"phase"`
|
||||
Payload json.RawMessage `json:"payload"`
|
||||
Interceptors []string `json:"interceptors,omitempty"` // optional: restrict to named interceptors
|
||||
Config map[string]map[string]any `json:"config,omitempty"` // optional: per-interceptor config
|
||||
TimeoutMs int64 `json:"timeoutMs,omitempty"`
|
||||
Context *interceptors.InvocationContext `json:"context,omitempty"`
|
||||
}
|
||||
|
||||
// ExecutionResult aggregates results from executing the full
|
||||
// interceptor chain via interceptor/invoke RPCs.
|
||||
type ExecutionResult struct {
|
||||
Status ChainStatus `json:"status"`
|
||||
Event string `json:"event"`
|
||||
Phase interceptors.InterceptionPhase `json:"phase"`
|
||||
Results []interceptors.InvokeResult `json:"results"`
|
||||
FinalPayload json.RawMessage `json:"finalPayload,omitempty"`
|
||||
ValidationSummary ValidationSummary `json:"validationSummary"`
|
||||
TotalDurationMs int64 `json:"totalDurationMs"`
|
||||
AbortedAt []AbortInfo `json:"abortedAt,omitempty"`
|
||||
}
|
||||
|
||||
// AddMCPServer discovers interceptors from an MCP server via
|
||||
// interceptors/list and adds entries for each. The client session's
|
||||
// transport determines how interceptor/invoke calls are made
|
||||
// (in-memory, stdio, HTTP, etc.).
|
||||
func (c *Chain) AddMCPServer(ctx context.Context, cs *mcp.ClientSession) error {
|
||||
var result interceptors.ListResult
|
||||
if err := cs.CallCustom(ctx, interceptors.MethodList, nil, &result); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
for _, info := range result.Interceptors {
|
||||
c.entries = append(c.entries, ChainEntry{
|
||||
Interceptor: info,
|
||||
Server: cs,
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Execute runs the chain for a given event and phase per the SEP
|
||||
// execution model:
|
||||
//
|
||||
// - Filter entries by event + phase
|
||||
// - Separate into validators and mutators
|
||||
// - Sort mutators by priorityHint (ascending, alphabetical tiebreak)
|
||||
// - Request phase: validate (parallel) then mutate (sequential)
|
||||
// - Response phase: mutate (sequential) then validate (parallel)
|
||||
// - Call interceptor/invoke via CallCustom for each entry
|
||||
// - For mutators: pass mutated payload from previous to next
|
||||
// - Handle abort, timeout, fail-open
|
||||
func (c *Chain) Execute(ctx context.Context, params *ExecutionParams) (*ExecutionResult, error) {
|
||||
c.mu.Lock()
|
||||
entries := make([]ChainEntry, len(c.entries))
|
||||
copy(entries, c.entries)
|
||||
c.mu.Unlock()
|
||||
|
||||
// Apply timeout if specified.
|
||||
if params.TimeoutMs > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, time.Duration(params.TimeoutMs)*time.Millisecond)
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
|
||||
// Filter entries by event + phase, respecting optional name filter.
|
||||
nameFilter := make(map[string]bool, len(params.Interceptors))
|
||||
for _, n := range params.Interceptors {
|
||||
nameFilter[n] = true
|
||||
}
|
||||
|
||||
var validators []ChainEntry
|
||||
var mutators []ChainEntry
|
||||
|
||||
for _, e := range entries {
|
||||
if len(nameFilter) > 0 && !nameFilter[e.Interceptor.Name] {
|
||||
continue
|
||||
}
|
||||
if !matchesPhase(e.Interceptor.Hook.Phase, params.Phase) {
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(e.Interceptor.Hook.Events, params.Event) {
|
||||
continue
|
||||
}
|
||||
switch e.Interceptor.Type {
|
||||
case interceptors.TypeValidation:
|
||||
validators = append(validators, e)
|
||||
case interceptors.TypeMutation:
|
||||
mutators = append(mutators, e)
|
||||
default:
|
||||
c.logger.Warn("unknown interceptor type, skipping",
|
||||
"interceptor", e.Interceptor.Name,
|
||||
"type", e.Interceptor.Type,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Sort mutators by priority (ascending), alphabetical tiebreak.
|
||||
sort.Slice(mutators, func(i, j int) bool {
|
||||
pi := mutators[i].Interceptor.PriorityHint.Resolve(params.Phase)
|
||||
pj := mutators[j].Interceptor.PriorityHint.Resolve(params.Phase)
|
||||
if pi != pj {
|
||||
return pi < pj
|
||||
}
|
||||
return mutators[i].Interceptor.Name < mutators[j].Interceptor.Name
|
||||
})
|
||||
|
||||
cr := &ExecutionResult{
|
||||
Event: params.Event,
|
||||
Phase: params.Phase,
|
||||
Results: make([]interceptors.InvokeResult, 0, len(validators)+len(mutators)),
|
||||
}
|
||||
|
||||
// Empty chain fast path.
|
||||
if len(validators) == 0 && len(mutators) == 0 {
|
||||
cr.Status = ChainSuccess
|
||||
cr.TotalDurationMs = time.Since(start).Milliseconds()
|
||||
return cr, nil
|
||||
}
|
||||
|
||||
// Trust-boundary-aware ordering.
|
||||
switch params.Phase {
|
||||
case interceptors.PhaseRequest:
|
||||
// Request (receiving): validate → mutate
|
||||
c.runValidators(ctx, params, validators, cr)
|
||||
if len(cr.AbortedAt) > 0 {
|
||||
cr.Status = ChainValidationFailed
|
||||
cr.TotalDurationMs = time.Since(start).Milliseconds()
|
||||
return cr, nil
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
c.timeoutResult(cr, start)
|
||||
return cr, nil
|
||||
}
|
||||
c.runMutators(ctx, params, mutators, cr)
|
||||
if len(cr.AbortedAt) > 0 {
|
||||
cr.Status = ChainMutationFailed
|
||||
cr.TotalDurationMs = time.Since(start).Milliseconds()
|
||||
return cr, nil
|
||||
}
|
||||
|
||||
case interceptors.PhaseResponse:
|
||||
// Response (sending): mutate → validate
|
||||
c.runMutators(ctx, params, mutators, cr)
|
||||
if len(cr.AbortedAt) > 0 {
|
||||
cr.Status = ChainMutationFailed
|
||||
cr.TotalDurationMs = time.Since(start).Milliseconds()
|
||||
return cr, nil
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
c.timeoutResult(cr, start)
|
||||
return cr, nil
|
||||
}
|
||||
// Validators must see the post-mutation payload.
|
||||
valParams := *params
|
||||
if cr.FinalPayload != nil {
|
||||
valParams.Payload = cr.FinalPayload
|
||||
}
|
||||
c.runValidators(ctx, &valParams, validators, cr)
|
||||
if len(cr.AbortedAt) > 0 {
|
||||
cr.Status = ChainValidationFailed
|
||||
cr.TotalDurationMs = time.Since(start).Milliseconds()
|
||||
return cr, nil
|
||||
}
|
||||
}
|
||||
|
||||
cr.Status = ChainSuccess
|
||||
cr.TotalDurationMs = time.Since(start).Milliseconds()
|
||||
return cr, nil
|
||||
}
|
||||
|
||||
// runValidators invokes all validators in parallel via interceptor/invoke.
|
||||
func (c *Chain) runValidators(
|
||||
ctx context.Context,
|
||||
params *ExecutionParams,
|
||||
validators []ChainEntry,
|
||||
cr *ExecutionResult,
|
||||
) {
|
||||
if len(validators) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
mu sync.Mutex
|
||||
wg sync.WaitGroup
|
||||
)
|
||||
for _, v := range validators {
|
||||
wg.Add(1)
|
||||
go func(v ChainEntry) {
|
||||
defer wg.Done()
|
||||
result := c.callInvoke(ctx, params, v)
|
||||
mu.Lock()
|
||||
c.recordValidation(v, result, cr)
|
||||
mu.Unlock()
|
||||
}(v)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// recordValidation processes a validator's invoke result and updates the chain result.
|
||||
func (c *Chain) recordValidation(entry ChainEntry, result invokeOutcome, cr *ExecutionResult) {
|
||||
if result.err != nil {
|
||||
c.logger.Warn("validator invoke error",
|
||||
"interceptor", entry.Interceptor.Name,
|
||||
"error", result.err,
|
||||
)
|
||||
cr.Results = append(cr.Results, interceptors.InvokeResult{
|
||||
Interceptor: entry.Interceptor.Name,
|
||||
Type: interceptors.TypeValidation,
|
||||
Phase: cr.Phase,
|
||||
})
|
||||
if !entry.Interceptor.FailOpen {
|
||||
cr.AbortedAt = append(cr.AbortedAt, AbortInfo{
|
||||
Interceptor: entry.Interceptor.Name,
|
||||
Reason: result.err.Error(),
|
||||
Type: AbortValidation,
|
||||
Phase: string(cr.Phase),
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
cr.Results = append(cr.Results, result.result)
|
||||
|
||||
// Tally validation summary and check for abort in a single pass.
|
||||
if result.result.Validation != nil {
|
||||
shouldAbort := entry.Interceptor.Mode != interceptors.ModeAudit && !result.result.Validation.Valid
|
||||
aborted := false
|
||||
for _, msg := range result.result.Validation.Messages {
|
||||
switch msg.Severity {
|
||||
case interceptors.SeverityError:
|
||||
cr.ValidationSummary.Errors++
|
||||
if shouldAbort && !aborted {
|
||||
cr.AbortedAt = append(cr.AbortedAt, AbortInfo{
|
||||
Interceptor: entry.Interceptor.Name,
|
||||
Reason: msg.Message,
|
||||
Type: AbortValidation,
|
||||
Phase: string(cr.Phase),
|
||||
})
|
||||
aborted = true
|
||||
}
|
||||
case interceptors.SeverityWarn:
|
||||
cr.ValidationSummary.Warnings++
|
||||
case interceptors.SeverityInfo:
|
||||
cr.ValidationSummary.Infos++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// runMutators invokes mutators sequentially via interceptor/invoke,
|
||||
// passing the mutated payload from each mutator to the next.
|
||||
func (c *Chain) runMutators(
|
||||
ctx context.Context,
|
||||
params *ExecutionParams,
|
||||
mutators []ChainEntry,
|
||||
cr *ExecutionResult,
|
||||
) {
|
||||
if len(mutators) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
currentPayload := params.Payload
|
||||
mutated := false
|
||||
|
||||
for _, m := range mutators {
|
||||
if ctx.Err() != nil {
|
||||
cr.AbortedAt = append(cr.AbortedAt, AbortInfo{
|
||||
Reason: "context cancelled during mutation chain",
|
||||
Type: AbortTimeout,
|
||||
Phase: string(params.Phase),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Build invoke params with current payload.
|
||||
mutParams := *params
|
||||
mutParams.Payload = currentPayload
|
||||
|
||||
result := c.callInvoke(ctx, &mutParams, m)
|
||||
|
||||
if result.err != nil {
|
||||
c.logger.Warn("mutator invoke error",
|
||||
"interceptor", m.Interceptor.Name,
|
||||
"error", result.err,
|
||||
)
|
||||
cr.Results = append(cr.Results, interceptors.InvokeResult{
|
||||
Interceptor: m.Interceptor.Name,
|
||||
Type: interceptors.TypeMutation,
|
||||
Phase: params.Phase,
|
||||
})
|
||||
if !m.Interceptor.FailOpen {
|
||||
cr.AbortedAt = append(cr.AbortedAt, AbortInfo{
|
||||
Interceptor: m.Interceptor.Name,
|
||||
Reason: result.err.Error(),
|
||||
Type: AbortMutation,
|
||||
Phase: string(params.Phase),
|
||||
})
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
cr.Results = append(cr.Results, result.result)
|
||||
|
||||
// For audit-mode mutators, don't apply the mutated payload.
|
||||
if m.Interceptor.Mode == interceptors.ModeAudit {
|
||||
continue
|
||||
}
|
||||
|
||||
// Apply mutated payload for the next mutator.
|
||||
if result.result.Payload != nil {
|
||||
currentPayload = result.result.Payload
|
||||
mutated = true
|
||||
}
|
||||
}
|
||||
|
||||
if mutated {
|
||||
cr.FinalPayload = currentPayload
|
||||
}
|
||||
}
|
||||
|
||||
// invokeOutcome wraps the result of a single interceptor/invoke call.
|
||||
type invokeOutcome struct {
|
||||
result interceptors.InvokeResult
|
||||
err error
|
||||
}
|
||||
|
||||
// callInvoke calls interceptor/invoke on the appropriate server for
|
||||
// a single chain entry.
|
||||
func (c *Chain) callInvoke(
|
||||
ctx context.Context,
|
||||
params *ExecutionParams,
|
||||
entry ChainEntry,
|
||||
) invokeOutcome {
|
||||
invokeParams := &interceptors.InvokeParams{
|
||||
Name: entry.Interceptor.Name,
|
||||
Event: params.Event,
|
||||
Phase: params.Phase,
|
||||
Payload: params.Payload,
|
||||
Context: params.Context,
|
||||
}
|
||||
|
||||
// Apply per-interceptor config if provided.
|
||||
if cfg, ok := params.Config[entry.Interceptor.Name]; ok {
|
||||
invokeParams.Config = cfg
|
||||
}
|
||||
|
||||
var result interceptors.InvokeResult
|
||||
err := entry.Server.CallCustom(ctx, interceptors.MethodInvoke, invokeParams, &result)
|
||||
if err != nil {
|
||||
return invokeOutcome{err: err}
|
||||
}
|
||||
return invokeOutcome{result: result}
|
||||
}
|
||||
|
||||
// timeoutResult sets the chain result to timeout status.
|
||||
func (c *Chain) timeoutResult(cr *ExecutionResult, start time.Time) {
|
||||
cr.Status = ChainTimeout
|
||||
cr.TotalDurationMs = time.Since(start).Milliseconds()
|
||||
cr.AbortedAt = append(cr.AbortedAt, AbortInfo{
|
||||
Reason: "chain execution timeout exceeded",
|
||||
Type: AbortTimeout,
|
||||
Phase: string(cr.Phase),
|
||||
})
|
||||
}
|
||||
|
||||
// matchesPhase checks if an interceptor's configured phase covers the target
|
||||
// phase. An interceptor with PhaseBoth matches any target phase.
|
||||
func matchesPhase(interceptorPhase, targetPhase interceptors.InterceptionPhase) bool {
|
||||
return interceptorPhase == interceptors.PhaseBoth || interceptorPhase == targetPhase
|
||||
}
|
||||
239
go/sdk/interceptors/chain/chain_test.go
Normal file
239
go/sdk/interceptors/chain/chain_test.go
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
// 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 chain_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/modelcontextprotocol/ext-interceptors/go/sdk/interceptors"
|
||||
"github.com/modelcontextprotocol/ext-interceptors/go/sdk/interceptors/chain"
|
||||
)
|
||||
|
||||
// setupChainWithInterceptors creates an MCP server with the given
|
||||
// interceptors registered via custom methods, connects a chain via
|
||||
// in-memory transport, and returns the chain ready for testing.
|
||||
func setupChainWithInterceptors(t *testing.T, is ...interceptors.Interceptor) *chain.Chain {
|
||||
t.Helper()
|
||||
|
||||
mcpServer := mcp.NewServer(&mcp.Implementation{
|
||||
Name: "chain-test-server",
|
||||
Version: "0.1.0",
|
||||
}, nil)
|
||||
|
||||
// Register interceptors/list and interceptor/invoke handlers.
|
||||
registerInterceptorMethods(mcpServer, is)
|
||||
|
||||
serverTransport, clientTransport := mcp.NewInMemoryTransports()
|
||||
|
||||
ss, err := mcpServer.Connect(context.Background(), serverTransport, nil)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { ss.Close() })
|
||||
|
||||
client := mcp.NewClient(&mcp.Implementation{
|
||||
Name: "chain-test-client",
|
||||
Version: "0.1.0",
|
||||
}, nil)
|
||||
cs, err := client.Connect(context.Background(), clientTransport, nil)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { cs.Close() })
|
||||
|
||||
ch := chain.NewChain(chain.WithChainLogger(slog.Default()))
|
||||
err = ch.AddMCPServer(context.Background(), cs)
|
||||
require.NoError(t, err)
|
||||
|
||||
return ch
|
||||
}
|
||||
|
||||
// registerInterceptorMethods adds interceptors/list and interceptor/invoke
|
||||
// custom methods to the server, backed by the given interceptor list.
|
||||
func registerInterceptorMethods(server *mcp.Server, is []interceptors.Interceptor) {
|
||||
server.AddCustomMethod(interceptors.MethodList,
|
||||
func(_ context.Context, _ *mcp.ServerSession, raw json.RawMessage) (any, error) {
|
||||
var params interceptors.ListParams
|
||||
if len(raw) > 0 {
|
||||
if err := json.Unmarshal(raw, ¶ms); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
infos := make([]interceptors.InterceptorInfo, 0, len(is))
|
||||
for _, i := range is {
|
||||
if params.Event != "" {
|
||||
match := false
|
||||
for _, e := range i.GetMetadata().Hook.Events {
|
||||
if e == params.Event {
|
||||
match = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !match {
|
||||
continue
|
||||
}
|
||||
}
|
||||
infos = append(infos, interceptors.InfoFromInterceptor(i))
|
||||
}
|
||||
return &interceptors.ListResult{Interceptors: infos}, nil
|
||||
},
|
||||
)
|
||||
|
||||
server.AddCustomMethod(interceptors.MethodInvoke,
|
||||
func(ctx context.Context, _ *mcp.ServerSession, raw json.RawMessage) (any, error) {
|
||||
var params interceptors.InvokeParams
|
||||
if err := json.Unmarshal(raw, ¶ms); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var target interceptors.Interceptor
|
||||
for _, i := range is {
|
||||
if i.GetMetadata().Name == params.Name {
|
||||
target = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if target == nil {
|
||||
return nil, fmt.Errorf("interceptor %q not found", params.Name)
|
||||
}
|
||||
|
||||
inv := &interceptors.Invocation{
|
||||
Event: params.Event,
|
||||
Phase: params.Phase,
|
||||
Payload: params.Payload,
|
||||
Config: params.Config,
|
||||
Context: params.Context,
|
||||
}
|
||||
|
||||
result := &interceptors.InvokeResult{
|
||||
Interceptor: params.Name,
|
||||
Type: target.GetType(),
|
||||
Phase: params.Phase,
|
||||
}
|
||||
|
||||
switch v := target.(type) {
|
||||
case *interceptors.Validator:
|
||||
vr, err := v.Handler(ctx, inv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result.Validation = vr
|
||||
case *interceptors.Mutator:
|
||||
mr, err := v.Handler(ctx, inv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result.Mutation = mr
|
||||
result.Payload = mr.Payload
|
||||
}
|
||||
return result, nil
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func TestChain_FailOpenRecordsExecutionResult(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("fail-open validator error is recorded", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
failOpenValidator := &interceptors.Validator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "fo-validator",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{"test/event"},
|
||||
Phase: interceptors.PhaseRequest,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
FailOpen: true,
|
||||
},
|
||||
Handler: func(_ context.Context, _ *interceptors.Invocation) (*interceptors.ValidationResult, error) {
|
||||
return nil, fmt.Errorf("transient failure")
|
||||
},
|
||||
}
|
||||
passingValidator := &interceptors.Validator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "passing-validator",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{"test/event"},
|
||||
Phase: interceptors.PhaseRequest,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(_ context.Context, _ *interceptors.Invocation) (*interceptors.ValidationResult, error) {
|
||||
return &interceptors.ValidationResult{Valid: true}, nil
|
||||
},
|
||||
}
|
||||
|
||||
ch := setupChainWithInterceptors(t, failOpenValidator, passingValidator)
|
||||
|
||||
payload, _ := json.Marshal(map[string]any{"value": "hello"})
|
||||
cr, err := ch.Execute(context.Background(), &chain.ExecutionParams{
|
||||
Event: "test/event",
|
||||
Phase: interceptors.PhaseRequest,
|
||||
Payload: payload,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Chain should succeed — fail-open doesn't abort.
|
||||
assert.Equal(t, chain.ChainSuccess, cr.Status)
|
||||
assert.Empty(t, cr.AbortedAt)
|
||||
|
||||
// Both interceptors should have a result entry.
|
||||
require.Len(t, cr.Results, 2)
|
||||
})
|
||||
|
||||
t.Run("fail-open mutator error is recorded", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
failOpenMutator := &interceptors.Mutator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "fo-mutator",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{"test/event"},
|
||||
Phase: interceptors.PhaseResponse,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
FailOpen: true,
|
||||
PriorityHint: interceptors.NewPriority(10),
|
||||
},
|
||||
Handler: func(_ context.Context, _ *interceptors.Invocation) (*interceptors.MutationResult, error) {
|
||||
return nil, fmt.Errorf("transient failure")
|
||||
},
|
||||
}
|
||||
passingMutator := &interceptors.Mutator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "passing-mutator",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{"test/event"},
|
||||
Phase: interceptors.PhaseResponse,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
PriorityHint: interceptors.NewPriority(20),
|
||||
},
|
||||
Handler: func(_ context.Context, _ *interceptors.Invocation) (*interceptors.MutationResult, error) {
|
||||
return &interceptors.MutationResult{Modified: false}, nil
|
||||
},
|
||||
}
|
||||
|
||||
ch := setupChainWithInterceptors(t, failOpenMutator, passingMutator)
|
||||
|
||||
payload, _ := json.Marshal(map[string]any{"value": "hello"})
|
||||
cr, err := ch.Execute(context.Background(), &chain.ExecutionParams{
|
||||
Event: "test/event",
|
||||
Phase: interceptors.PhaseResponse,
|
||||
Payload: payload,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Chain should succeed — fail-open doesn't abort.
|
||||
assert.Equal(t, chain.ChainSuccess, cr.Status)
|
||||
assert.Empty(t, cr.AbortedAt)
|
||||
|
||||
// Both interceptors should have a result entry.
|
||||
require.Len(t, cr.Results, 2)
|
||||
})
|
||||
}
|
||||
39
go/sdk/interceptors/chain/doc.go
Normal file
39
go/sdk/interceptors/chain/doc.go
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
// 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 chain provides the SEP-compliant interceptor chain
|
||||
// orchestrator. It discovers interceptors from MCP servers via
|
||||
// "interceptors/list" and invokes them via "interceptor/invoke",
|
||||
// implementing trust-boundary-aware execution ordering.
|
||||
//
|
||||
// # Execution Model
|
||||
//
|
||||
// [Chain.Execute] filters registered interceptors by event and phase,
|
||||
// separates them into validators and mutators, and runs them in the
|
||||
// SEP-defined order:
|
||||
//
|
||||
// Request phase (untrusted → trusted):
|
||||
//
|
||||
// Validate (parallel) → Mutate (sequential)
|
||||
//
|
||||
// Response phase (trusted → untrusted):
|
||||
//
|
||||
// Mutate (sequential) → Validate (parallel)
|
||||
//
|
||||
// # Usage
|
||||
//
|
||||
// A [Chain] is created with [NewChain] and populated by adding MCP
|
||||
// servers via [Chain.AddMCPServer]:
|
||||
//
|
||||
// chain := chain.NewChain()
|
||||
// chain.AddMCPServer(ctx, clientSession)
|
||||
// mcpServer.AddReceivingMiddleware(
|
||||
// gomiddleware.Middleware(chain),
|
||||
// )
|
||||
//
|
||||
// For convenience, [mcpserver.Server.LocalChain] creates a chain
|
||||
// pre-configured with a local in-process MCP server:
|
||||
//
|
||||
// chain, err := srv.LocalChain(ctx)
|
||||
package chain
|
||||
39
go/sdk/interceptors/chain/result.go
Normal file
39
go/sdk/interceptors/chain/result.go
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
// 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 chain
|
||||
|
||||
// ChainStatus describes the outcome of a full interceptor chain execution.
|
||||
type ChainStatus string
|
||||
|
||||
const (
|
||||
ChainSuccess ChainStatus = "success"
|
||||
ChainValidationFailed ChainStatus = "validation_failed"
|
||||
ChainMutationFailed ChainStatus = "mutation_failed"
|
||||
ChainTimeout ChainStatus = "timeout"
|
||||
)
|
||||
|
||||
// AbortType classifies the reason an interceptor chain was aborted.
|
||||
type AbortType string
|
||||
|
||||
const (
|
||||
AbortValidation AbortType = "validation"
|
||||
AbortMutation AbortType = "mutation"
|
||||
AbortTimeout AbortType = "timeout"
|
||||
)
|
||||
|
||||
// ValidationSummary counts validation outcomes.
|
||||
type ValidationSummary struct {
|
||||
Errors int `json:"errors"`
|
||||
Warnings int `json:"warnings"`
|
||||
Infos int `json:"infos"`
|
||||
}
|
||||
|
||||
// AbortInfo describes where and why a chain was aborted.
|
||||
type AbortInfo struct {
|
||||
Interceptor string `json:"interceptor"`
|
||||
Reason string `json:"reason"`
|
||||
Type AbortType `json:"type"`
|
||||
Phase string `json:"phase,omitempty"` // phase at which the abort occurred
|
||||
}
|
||||
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
|
||||
33
go/sdk/interceptors/integrations/gomiddleware/doc.go
Normal file
33
go/sdk/interceptors/integrations/gomiddleware/doc.go
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
// 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 gomiddleware provides an optional MCP middleware that
|
||||
// automatically executes interceptors for every matching
|
||||
// request/response. It uses the [chain.Chain] from the
|
||||
// [interceptors/chain] package, which invokes interceptors via
|
||||
// interceptor/invoke RPCs per the SEP execution model.
|
||||
//
|
||||
// The middleware is installed on an [mcp.Server] via
|
||||
// [mcp.Server.AddReceivingMiddleware]. It marshals request params
|
||||
// and response results to [json.RawMessage], calls
|
||||
// [chain.Chain.Execute], and applies any mutated payloads back to
|
||||
// the request or response.
|
||||
//
|
||||
// # Usage
|
||||
//
|
||||
// // Create interceptor server (registers interceptors as resources)
|
||||
// srv := mcpserver.NewServer(mcpServer)
|
||||
// srv.AddInterceptor(myValidator)
|
||||
// srv.AddInterceptor(myMutator)
|
||||
//
|
||||
// // Create chain via in-memory transport
|
||||
// chain, err := srv.LocalChain(ctx)
|
||||
//
|
||||
// // Install middleware for automatic execution
|
||||
// mcpServer.AddReceivingMiddleware(
|
||||
// gomiddleware.Middleware(chain,
|
||||
// gomiddleware.WithLogger(logger),
|
||||
// ),
|
||||
// )
|
||||
package gomiddleware
|
||||
75
go/sdk/interceptors/integrations/gomiddleware/errors.go
Normal file
75
go/sdk/interceptors/integrations/gomiddleware/errors.go
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
// 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 gomiddleware
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/jsonrpc"
|
||||
|
||||
"github.com/modelcontextprotocol/ext-interceptors/go/sdk/interceptors/chain"
|
||||
)
|
||||
|
||||
type validationErrorData struct {
|
||||
ValidationErrors []chain.AbortInfo `json:"validationErrors"`
|
||||
}
|
||||
|
||||
type mutationErrorData struct {
|
||||
FailedInterceptor string `json:"failedInterceptor"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
type timeoutErrorData struct {
|
||||
Interceptor string `json:"interceptor"`
|
||||
TimeoutMs int64 `json:"timeoutMs,omitempty"`
|
||||
Phase string `json:"phase"`
|
||||
}
|
||||
|
||||
const codeServerError = -32000
|
||||
|
||||
// abortToJSONRPCError converts a list of abort infos into a *jsonrpc.Error.
|
||||
func abortToJSONRPCError(aborts []chain.AbortInfo) *jsonrpc.Error {
|
||||
first := aborts[0]
|
||||
|
||||
var code int64
|
||||
switch first.Type {
|
||||
case chain.AbortValidation:
|
||||
code = jsonrpc.CodeInvalidParams
|
||||
case chain.AbortTimeout:
|
||||
code = codeServerError
|
||||
default:
|
||||
code = jsonrpc.CodeInternalError
|
||||
}
|
||||
|
||||
var data json.RawMessage
|
||||
switch first.Type {
|
||||
case chain.AbortValidation:
|
||||
d, _ := json.Marshal(validationErrorData{ValidationErrors: aborts})
|
||||
data = d
|
||||
case chain.AbortTimeout:
|
||||
d, _ := json.Marshal(timeoutErrorData{
|
||||
Interceptor: first.Interceptor,
|
||||
Phase: first.Phase,
|
||||
})
|
||||
data = d
|
||||
default:
|
||||
d, _ := json.Marshal(mutationErrorData{
|
||||
FailedInterceptor: first.Interceptor,
|
||||
Reason: first.Reason,
|
||||
})
|
||||
data = d
|
||||
}
|
||||
|
||||
msg := "interceptor abort: " + first.Reason
|
||||
if len(aborts) > 1 {
|
||||
msg = "interceptor abort: multiple validation failures"
|
||||
}
|
||||
|
||||
return &jsonrpc.Error{
|
||||
Code: code,
|
||||
Message: msg,
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
176
go/sdk/interceptors/integrations/gomiddleware/middleware.go
Normal file
176
go/sdk/interceptors/integrations/gomiddleware/middleware.go
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
// 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 gomiddleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
|
||||
"github.com/modelcontextprotocol/ext-interceptors/go/sdk/interceptors"
|
||||
"github.com/modelcontextprotocol/ext-interceptors/go/sdk/interceptors/chain"
|
||||
)
|
||||
|
||||
// Option configures the middleware.
|
||||
type Option func(*config)
|
||||
|
||||
type config struct {
|
||||
logger *slog.Logger
|
||||
contextProvider ContextProviderFunc
|
||||
}
|
||||
|
||||
// ContextProviderFunc extracts an InvocationContext from an incoming MCP
|
||||
// request. This is called once per intercepted request and the result is
|
||||
// passed to all interceptor handlers via the chain execution params.
|
||||
//
|
||||
// Typical use: extract principal identity from OAuth tokens available on
|
||||
// the request's session (via RequestExtra.TokenInfo).
|
||||
type ContextProviderFunc func(ctx context.Context, req mcp.Request) *interceptors.InvocationContext
|
||||
|
||||
// WithLogger sets the logger for the middleware.
|
||||
// If not set, slog.Default() is used.
|
||||
func WithLogger(l *slog.Logger) Option {
|
||||
return func(c *config) {
|
||||
c.logger = l
|
||||
}
|
||||
}
|
||||
|
||||
// WithContextProvider sets a function that populates InvocationContext
|
||||
// for every intercepted request. Without this, the context is nil.
|
||||
func WithContextProvider(f ContextProviderFunc) Option {
|
||||
return func(c *config) {
|
||||
c.contextProvider = f
|
||||
}
|
||||
}
|
||||
|
||||
// skipMethods are methods that should not be intercepted to prevent
|
||||
// recursion when the chain connects back to the same server, plus
|
||||
// lifecycle methods that don't need interception.
|
||||
var skipMethods = map[string]bool{
|
||||
"initialize": true,
|
||||
"notifications/initialized": true,
|
||||
"notifications/cancelled": true,
|
||||
interceptors.MethodList: true,
|
||||
interceptors.MethodInvoke: true,
|
||||
}
|
||||
|
||||
// Middleware creates an [mcp.Middleware] that intercepts incoming requests
|
||||
// and outgoing responses, running the interceptor chain for each.
|
||||
//
|
||||
// The middleware calls chain.Execute() which invokes interceptors via
|
||||
// interceptor/invoke RPCs. Install it on an [mcp.Server] via
|
||||
// [mcp.Server.AddReceivingMiddleware]:
|
||||
//
|
||||
// chain, _ := srv.LocalChain(ctx)
|
||||
// mcpServer.AddReceivingMiddleware(
|
||||
// gomiddleware.Middleware(chain, gomiddleware.WithLogger(logger)),
|
||||
// )
|
||||
func Middleware(ch *chain.Chain, opts ...Option) mcp.Middleware {
|
||||
cfg := &config{}
|
||||
for _, opt := range opts {
|
||||
opt(cfg)
|
||||
}
|
||||
if cfg.logger == nil {
|
||||
cfg.logger = slog.Default()
|
||||
}
|
||||
|
||||
return func(next mcp.MethodHandler) mcp.MethodHandler {
|
||||
return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) {
|
||||
// Skip interceptor and lifecycle methods to prevent recursion.
|
||||
if skipMethods[method] {
|
||||
return next(ctx, method, req)
|
||||
}
|
||||
|
||||
event := method
|
||||
|
||||
// Extract invocation context from the request using the context provider, if set.
|
||||
var invCtx *interceptors.InvocationContext
|
||||
if cfg.contextProvider != nil {
|
||||
invCtx = cfg.contextProvider(ctx, req)
|
||||
}
|
||||
|
||||
// --- Request phase ---
|
||||
reqPayload, err := json.Marshal(req.GetParams())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
reqResult, err := ch.Execute(ctx, &chain.ExecutionParams{
|
||||
Event: event,
|
||||
Phase: interceptors.PhaseRequest,
|
||||
Payload: reqPayload,
|
||||
Context: invCtx,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(reqResult.AbortedAt) > 0 {
|
||||
logAborts(cfg.logger, "request", event, reqResult.AbortedAt)
|
||||
return nil, abortToJSONRPCError(reqResult.AbortedAt)
|
||||
}
|
||||
|
||||
// Apply mutated payload back to the request params if modified.
|
||||
if reqResult.FinalPayload != nil {
|
||||
if err := json.Unmarshal(reqResult.FinalPayload, req.GetParams()); err != nil {
|
||||
return nil, fmt.Errorf("interceptors: failed to apply mutated request payload: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Call the next handler.
|
||||
result, err := next(ctx, method, req)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
|
||||
// Notification methods return nil result — skip response phase.
|
||||
if result == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// --- Response phase ---
|
||||
respPayload, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("interceptors: failed to marshal response payload for interception: %w", err)
|
||||
}
|
||||
|
||||
respResult, err := ch.Execute(ctx, &chain.ExecutionParams{
|
||||
Event: event,
|
||||
Phase: interceptors.PhaseResponse,
|
||||
Payload: respPayload,
|
||||
Context: invCtx,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(respResult.AbortedAt) > 0 {
|
||||
logAborts(cfg.logger, "response", event, respResult.AbortedAt)
|
||||
return nil, abortToJSONRPCError(respResult.AbortedAt)
|
||||
}
|
||||
|
||||
// Apply mutated response payload if it was modified.
|
||||
if respResult.FinalPayload != nil {
|
||||
if err := json.Unmarshal(respResult.FinalPayload, result); err != nil {
|
||||
return nil, fmt.Errorf("interceptors: failed to apply mutated response payload: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// logAborts logs each abort entry at warn level.
|
||||
func logAborts(logger *slog.Logger, phase, event string, aborts []chain.AbortInfo) {
|
||||
for _, a := range aborts {
|
||||
logger.Warn("interceptors: "+phase+" aborted",
|
||||
"event", event,
|
||||
"interceptor", a.Interceptor,
|
||||
"reason", a.Reason,
|
||||
)
|
||||
}
|
||||
}
|
||||
344
go/sdk/interceptors/integrations/gomiddleware/middleware_test.go
Normal file
344
go/sdk/interceptors/integrations/gomiddleware/middleware_test.go
Normal file
|
|
@ -0,0 +1,344 @@
|
|||
package gomiddleware_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/modelcontextprotocol/ext-interceptors/go/sdk/interceptors"
|
||||
"github.com/modelcontextprotocol/ext-interceptors/go/sdk/interceptors/integrations/gomiddleware"
|
||||
"github.com/modelcontextprotocol/ext-interceptors/go/sdk/interceptors/mcpserver"
|
||||
)
|
||||
|
||||
// setup creates a test server with middleware installed and returns a connected client session.
|
||||
func setup(t *testing.T, is ...interceptors.Interceptor) *mcp.ClientSession {
|
||||
t.Helper()
|
||||
|
||||
mcpServer := mcp.NewServer(&mcp.Implementation{
|
||||
Name: "test-server",
|
||||
Version: "0.1.0",
|
||||
}, nil)
|
||||
|
||||
mcpServer.AddTool(&mcp.Tool{
|
||||
Name: "echo",
|
||||
Description: "echoes input",
|
||||
InputSchema: map[string]any{"type": "object"},
|
||||
}, func(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
return &mcp.CallToolResult{
|
||||
Content: []mcp.Content{&mcp.TextContent{Text: fmt.Sprintf("echo: %s", req.Params.Arguments)}},
|
||||
}, nil
|
||||
})
|
||||
|
||||
srv := mcpserver.NewServer(mcpServer)
|
||||
for _, i := range is {
|
||||
srv.AddInterceptor(i)
|
||||
}
|
||||
|
||||
// Create chain via LocalChain (in-memory transport).
|
||||
chain, err := srv.LocalChain(context.Background())
|
||||
require.NoError(t, err)
|
||||
|
||||
// Install the middleware.
|
||||
mcpServer.AddReceivingMiddleware(gomiddleware.Middleware(chain))
|
||||
|
||||
handler := mcpserver.NewStreamableHTTPHandler(srv, nil)
|
||||
httpServer := httptest.NewServer(handler)
|
||||
t.Cleanup(httpServer.Close)
|
||||
|
||||
client := mcp.NewClient(&mcp.Implementation{Name: "test-client", Version: "0.1.0"}, nil)
|
||||
cs, err := client.Connect(context.Background(), &mcp.StreamableClientTransport{
|
||||
Endpoint: httpServer.URL,
|
||||
}, nil)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { cs.Close() })
|
||||
|
||||
return cs
|
||||
}
|
||||
|
||||
func resultText(t *testing.T, result *mcp.CallToolResult) string {
|
||||
t.Helper()
|
||||
require.NotEmpty(t, result.Content)
|
||||
tc, ok := result.Content[0].(*mcp.TextContent)
|
||||
require.True(t, ok, "expected TextContent, got %T", result.Content[0])
|
||||
return tc.Text
|
||||
}
|
||||
|
||||
func TestMiddlewareBlocksOnValidationError(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
blocker := &interceptors.Validator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "block-echo",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseRequest,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(_ context.Context, inv *interceptors.Invocation) (*interceptors.ValidationResult, error) {
|
||||
raw, ok := inv.Payload.(json.RawMessage)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected type %T", inv.Payload)
|
||||
}
|
||||
var params struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, ¶ms); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if params.Name == "echo" {
|
||||
return &interceptors.ValidationResult{
|
||||
Valid: false,
|
||||
Messages: []interceptors.ValidationMessage{
|
||||
{Message: "echo is blocked", Severity: interceptors.SeverityError},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
return &interceptors.ValidationResult{Valid: true}, nil
|
||||
},
|
||||
}
|
||||
|
||||
cs := setup(t, blocker)
|
||||
|
||||
_, err := cs.CallTool(context.Background(), &mcp.CallToolParams{
|
||||
Name: "echo",
|
||||
Arguments: map[string]any{"text": "hello"},
|
||||
})
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestMiddlewarePassesOnSuccess(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
allow := &interceptors.Validator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "allow-all",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseRequest,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(_ context.Context, _ *interceptors.Invocation) (*interceptors.ValidationResult, error) {
|
||||
return &interceptors.ValidationResult{Valid: true}, nil
|
||||
},
|
||||
}
|
||||
|
||||
cs := setup(t, allow)
|
||||
|
||||
result, err := cs.CallTool(context.Background(), &mcp.CallToolParams{
|
||||
Name: "echo",
|
||||
Arguments: map[string]any{"text": "hello"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.True(t, strings.HasPrefix(resultText(t, result), "echo:"))
|
||||
}
|
||||
|
||||
func TestMiddlewareMutatesPayload(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mutator := &interceptors.Mutator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "add-prefix",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseResponse,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(_ context.Context, inv *interceptors.Invocation) (*interceptors.MutationResult, error) {
|
||||
raw, ok := inv.Payload.(json.RawMessage)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected type %T", inv.Payload)
|
||||
}
|
||||
var result mcp.CallToolResult
|
||||
if err := json.Unmarshal(raw, &result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, c := range result.Content {
|
||||
if tc, ok := c.(*mcp.TextContent); ok {
|
||||
tc.Text = "[mutated] " + tc.Text
|
||||
}
|
||||
}
|
||||
data, err := json.Marshal(&result)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &interceptors.MutationResult{Modified: true, Payload: json.RawMessage(data)}, nil
|
||||
},
|
||||
}
|
||||
|
||||
cs := setup(t, mutator)
|
||||
|
||||
result, err := cs.CallTool(context.Background(), &mcp.CallToolParams{
|
||||
Name: "echo",
|
||||
Arguments: map[string]any{"text": "hello"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.True(t, strings.HasPrefix(resultText(t, result), "[mutated] echo:"))
|
||||
}
|
||||
|
||||
func TestMiddlewareAuditModeNonBlocking(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// Audit-mode validator returns Valid=false but should NOT block the request.
|
||||
auditValidator := &interceptors.Validator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "audit-reject",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseRequest,
|
||||
},
|
||||
Mode: interceptors.ModeAudit,
|
||||
},
|
||||
Handler: func(_ context.Context, _ *interceptors.Invocation) (*interceptors.ValidationResult, error) {
|
||||
return &interceptors.ValidationResult{
|
||||
Valid: false,
|
||||
Messages: []interceptors.ValidationMessage{
|
||||
{Message: "would reject", Severity: interceptors.SeverityError},
|
||||
},
|
||||
}, nil
|
||||
},
|
||||
}
|
||||
|
||||
cs := setup(t, auditValidator)
|
||||
|
||||
result, err := cs.CallTool(context.Background(), &mcp.CallToolParams{
|
||||
Name: "echo",
|
||||
Arguments: map[string]any{"text": "hello"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.True(t, strings.HasPrefix(resultText(t, result), "echo:"))
|
||||
}
|
||||
|
||||
func TestMiddlewareWithContextProvider(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// Validator that checks the invocation context for a principal.
|
||||
principalCheck := &interceptors.Validator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "check-principal",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseRequest,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(_ context.Context, inv *interceptors.Invocation) (*interceptors.ValidationResult, error) {
|
||||
if inv.Context == nil || inv.Context.Principal == nil || inv.Context.Principal.ID != "test-user" {
|
||||
return &interceptors.ValidationResult{
|
||||
Valid: false,
|
||||
Messages: []interceptors.ValidationMessage{
|
||||
{Message: "missing or invalid principal", Severity: interceptors.SeverityError},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
return &interceptors.ValidationResult{Valid: true}, nil
|
||||
},
|
||||
}
|
||||
|
||||
// Setup with context provider.
|
||||
mcpServer := mcp.NewServer(&mcp.Implementation{
|
||||
Name: "test-server",
|
||||
Version: "0.1.0",
|
||||
}, nil)
|
||||
|
||||
mcpServer.AddTool(&mcp.Tool{
|
||||
Name: "echo",
|
||||
Description: "echoes input",
|
||||
InputSchema: map[string]any{"type": "object"},
|
||||
}, func(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
return &mcp.CallToolResult{
|
||||
Content: []mcp.Content{&mcp.TextContent{Text: fmt.Sprintf("echo: %s", req.Params.Arguments)}},
|
||||
}, nil
|
||||
})
|
||||
|
||||
srv := mcpserver.NewServer(mcpServer)
|
||||
srv.AddInterceptor(principalCheck)
|
||||
|
||||
chain, err := srv.LocalChain(context.Background())
|
||||
require.NoError(t, err)
|
||||
|
||||
mcpServer.AddReceivingMiddleware(gomiddleware.Middleware(chain,
|
||||
gomiddleware.WithContextProvider(func(_ context.Context, _ mcp.Request) *interceptors.InvocationContext {
|
||||
return &interceptors.InvocationContext{
|
||||
Principal: &interceptors.Principal{
|
||||
Type: "user",
|
||||
ID: "test-user",
|
||||
},
|
||||
}
|
||||
}),
|
||||
))
|
||||
|
||||
handler := mcpserver.NewStreamableHTTPHandler(srv, nil)
|
||||
httpServer := httptest.NewServer(handler)
|
||||
t.Cleanup(httpServer.Close)
|
||||
|
||||
client := mcp.NewClient(&mcp.Implementation{Name: "test-client", Version: "0.1.0"}, nil)
|
||||
cs, err := client.Connect(context.Background(), &mcp.StreamableClientTransport{
|
||||
Endpoint: httpServer.URL,
|
||||
}, nil)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { cs.Close() })
|
||||
|
||||
result, err := cs.CallTool(context.Background(), &mcp.CallToolParams{
|
||||
Name: "echo",
|
||||
Arguments: map[string]any{"text": "hello"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.True(t, strings.HasPrefix(resultText(t, result), "echo:"))
|
||||
}
|
||||
|
||||
func TestMiddlewareRequestMutatorModifiesArgs(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// Request mutator that adds a field to the arguments.
|
||||
reqMutator := &interceptors.Mutator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "inject-field",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseRequest,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(_ context.Context, inv *interceptors.Invocation) (*interceptors.MutationResult, error) {
|
||||
raw, ok := inv.Payload.(json.RawMessage)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected type %T", inv.Payload)
|
||||
}
|
||||
var params map[string]any
|
||||
if err := json.Unmarshal(raw, ¶ms); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
args, _ := params["arguments"].(map[string]any)
|
||||
if args == nil {
|
||||
args = map[string]any{}
|
||||
}
|
||||
args["injected"] = "yes"
|
||||
params["arguments"] = args
|
||||
data, err := json.Marshal(params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &interceptors.MutationResult{Modified: true, Payload: json.RawMessage(data)}, nil
|
||||
},
|
||||
}
|
||||
|
||||
cs := setup(t, reqMutator)
|
||||
|
||||
result, err := cs.CallTool(context.Background(), &mcp.CallToolParams{
|
||||
Name: "echo",
|
||||
Arguments: map[string]any{"text": "hello"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
text := resultText(t, result)
|
||||
assert.Contains(t, text, "injected")
|
||||
}
|
||||
|
|
@ -1,6 +1,173 @@
|
|||
// Copyright 2025 The MCP Interceptors Authors. All rights reserved.
|
||||
// Use of this source code is governed by a Apache-2.0
|
||||
// Use of this source code is governed by an Apache-2.0
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package interceptors implements MCP Interceptors based on [SEP-1763](https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1763).
|
||||
package interceptors
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
// Interceptor is the common interface for all interceptors. It is implemented by both Validator and Mutator.
|
||||
type Interceptor interface {
|
||||
GetMetadata() *Metadata
|
||||
GetType() InterceptorType
|
||||
}
|
||||
|
||||
// --- Enums ---
|
||||
|
||||
// InterceptionPhase determines when an interceptor runs.
|
||||
type InterceptionPhase string
|
||||
|
||||
const (
|
||||
PhaseRequest InterceptionPhase = "request"
|
||||
PhaseResponse InterceptionPhase = "response"
|
||||
PhaseBoth InterceptionPhase = "both"
|
||||
)
|
||||
|
||||
// InterceptionEvent identifies a lifecycle event that can be intercepted.
|
||||
type InterceptionEvent = string
|
||||
|
||||
// Mode controls enforcement behavior.
|
||||
type Mode string
|
||||
|
||||
const (
|
||||
ModeEnforce Mode = "enforce" // Enforced: validation failures block, mutations apply
|
||||
ModeAudit Mode = "audit" // Audit: log results but don't block or apply mutations
|
||||
)
|
||||
|
||||
// InterceptorType identifies the category of an interceptor.
|
||||
type InterceptorType string
|
||||
|
||||
const (
|
||||
TypeValidation InterceptorType = "validation"
|
||||
TypeMutation InterceptorType = "mutation"
|
||||
)
|
||||
|
||||
// Severity represents validation message severity.
|
||||
type Severity string
|
||||
|
||||
const (
|
||||
SeverityInfo Severity = "info"
|
||||
SeverityWarn Severity = "warn"
|
||||
SeverityError Severity = "error" // Only error blocks execution
|
||||
)
|
||||
|
||||
// --- Metadata ---
|
||||
|
||||
// Compat represents protocol version compatibility.
|
||||
type Compat struct {
|
||||
MinProtocol string `json:"minProtocol"`
|
||||
MaxProtocol string `json:"maxProtocol,omitempty"`
|
||||
}
|
||||
|
||||
// Hook defines which lifecycle events and phase trigger an interceptor.
|
||||
type Hook struct {
|
||||
Events []InterceptionEvent `json:"events"`
|
||||
Phase InterceptionPhase `json:"phase"`
|
||||
}
|
||||
|
||||
// Metadata holds all common interceptor metadata.
|
||||
type Metadata struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Type InterceptorType `json:"type"`
|
||||
Hook Hook `json:"hook"`
|
||||
PriorityHint Priority `json:"priorityHint,omitempty"`
|
||||
Compat *Compat `json:"compat,omitempty"`
|
||||
ConfigSchema json.RawMessage `json:"configSchema,omitempty"`
|
||||
Mode Mode `json:"mode"`
|
||||
FailOpen bool `json:"failOpen,omitempty"`
|
||||
}
|
||||
|
||||
// --- Validator ---
|
||||
|
||||
// ValidatorHandler is the function signature for validation handlers.
|
||||
//
|
||||
// Handlers MUST treat the Invocation and its Payload as read-only.
|
||||
// Multiple validators for the same event run concurrently and share
|
||||
// the same Invocation pointer, so any mutation of the Payload (or
|
||||
// other Invocation fields) is a data race.
|
||||
type ValidatorHandler func(ctx context.Context, inv *Invocation) (*ValidationResult, error)
|
||||
|
||||
// Validator is a validation interceptor.
|
||||
type Validator struct {
|
||||
Metadata
|
||||
Handler ValidatorHandler
|
||||
}
|
||||
|
||||
func (v *Validator) GetMetadata() *Metadata { return &v.Metadata }
|
||||
func (v *Validator) GetType() InterceptorType { return TypeValidation }
|
||||
|
||||
// --- Mutator ---
|
||||
|
||||
// MutatorHandler is the function signature for raw mutation handlers.
|
||||
type MutatorHandler func(ctx context.Context, inv *Invocation) (*MutationResult, error)
|
||||
|
||||
// Mutator is a mutation interceptor.
|
||||
type Mutator struct {
|
||||
Metadata
|
||||
Handler MutatorHandler
|
||||
}
|
||||
|
||||
func (m *Mutator) GetMetadata() *Metadata { return &m.Metadata }
|
||||
func (m *Mutator) GetType() InterceptorType { return TypeMutation }
|
||||
|
||||
// --- Invocation ---
|
||||
|
||||
// Invocation is the context passed to every interceptor handler.
|
||||
type Invocation struct {
|
||||
Event string // e.g. "tools/call"
|
||||
Phase InterceptionPhase // "request" or "response"
|
||||
Payload any // The payload (json.RawMessage when invoked via interceptor/invoke)
|
||||
Config map[string]any // Per-invocation config
|
||||
Context *InvocationContext // Optional caller context (identity, trace, etc.)
|
||||
}
|
||||
|
||||
// InvocationContext holds optional context passed to interceptors.
|
||||
type InvocationContext struct {
|
||||
Principal *Principal `json:"principal,omitempty"`
|
||||
TraceID string `json:"traceId,omitempty"`
|
||||
SpanID string `json:"spanId,omitempty"`
|
||||
Timestamp string `json:"timestamp,omitempty"`
|
||||
SessionID string `json:"sessionId,omitempty"`
|
||||
}
|
||||
|
||||
// Principal identifies the caller.
|
||||
type Principal struct {
|
||||
Type string `json:"type"`
|
||||
ID string `json:"id,omitempty"`
|
||||
Claims map[string]any `json:"claims,omitempty"`
|
||||
}
|
||||
|
||||
// --- Results ---
|
||||
|
||||
// ValidationMessage is a single validation finding.
|
||||
type ValidationMessage struct {
|
||||
Path string `json:"path,omitempty"`
|
||||
Message string `json:"message"`
|
||||
Severity Severity `json:"severity"`
|
||||
}
|
||||
|
||||
// ValidationSuggestion is an optional suggested correction.
|
||||
type ValidationSuggestion struct {
|
||||
Path string `json:"path"`
|
||||
Value any `json:"value"`
|
||||
}
|
||||
|
||||
// ValidationResult is returned by validation interceptors.
|
||||
type ValidationResult struct {
|
||||
Valid bool `json:"valid"`
|
||||
Severity Severity `json:"severity,omitempty"`
|
||||
Messages []ValidationMessage `json:"messages,omitempty"`
|
||||
Suggestions []ValidationSuggestion `json:"suggestions,omitempty"`
|
||||
}
|
||||
|
||||
// MutationResult is returned by mutation interceptors.
|
||||
type MutationResult struct {
|
||||
Modified bool `json:"modified"`
|
||||
Info map[string]any `json:"info,omitempty"`
|
||||
Payload json.RawMessage `json:"payload,omitempty"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,14 +0,0 @@
|
|||
// Copyright 2025 The MCP Interceptors Authors. All rights reserved.
|
||||
// Use of this source code is governed by a Apache-2.0
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package interceptors
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestPlaceholder(t *testing.T) {
|
||||
// Placeholder test to ensure go test runs successfully
|
||||
if false {
|
||||
t.Error("This should not happen")
|
||||
}
|
||||
}
|
||||
52
go/sdk/interceptors/mcpserver/doc.go
Normal file
52
go/sdk/interceptors/mcpserver/doc.go
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
// 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 mcpserver registers interceptors as first-class MCP
|
||||
// primitives. Adding an interceptor to the server makes it
|
||||
// discoverable via "interceptors/list" and invocable via
|
||||
// "interceptor/invoke", so any MCP client — local or remote — can
|
||||
// discover and call interceptors using standard JSON-RPC.
|
||||
//
|
||||
// # Getting Started
|
||||
//
|
||||
// Wrap an existing [mcp.Server] with [NewServer] and register
|
||||
// interceptors:
|
||||
//
|
||||
// srv := mcpserver.NewServer(mcpServer, mcpserver.WithLogger(logger))
|
||||
// srv.AddInterceptor(myValidator)
|
||||
// srv.AddInterceptor(myMutator)
|
||||
// srv.Run(ctx, transport)
|
||||
//
|
||||
// At this point any connected MCP client can call interceptors/list
|
||||
// and interceptor/invoke.
|
||||
//
|
||||
// For convenience, [Server.LocalChain] creates a [chain.Chain] wired
|
||||
// to the server over an in-memory transport, ready for use with the
|
||||
// gomiddleware package:
|
||||
//
|
||||
// chain, err := srv.LocalChain(ctx)
|
||||
// mcpServer.AddReceivingMiddleware(
|
||||
// gomiddleware.Middleware(chain,
|
||||
// gomiddleware.WithContextProvider(myProvider),
|
||||
// ),
|
||||
// )
|
||||
//
|
||||
// # JSON-RPC Methods
|
||||
//
|
||||
// The server registers two JSON-RPC methods:
|
||||
//
|
||||
// - "interceptors/list": Returns all registered interceptors,
|
||||
// optionally filtered by event name.
|
||||
// - "interceptor/invoke": Invokes a single interceptor by name
|
||||
// for a given event, phase, and payload.
|
||||
//
|
||||
// # Transports
|
||||
//
|
||||
// The server works with any transport supported by the go-sdk.
|
||||
// For stdio, use [Server.Run]. For HTTP, use
|
||||
// [NewStreamableHTTPHandler]:
|
||||
//
|
||||
// handler := mcpserver.NewStreamableHTTPHandler(srv, nil)
|
||||
// http.ListenAndServe(":8080", handler)
|
||||
package mcpserver
|
||||
113
go/sdk/interceptors/mcpserver/rpc.go
Normal file
113
go/sdk/interceptors/mcpserver/rpc.go
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
// 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 mcpserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/jsonrpc"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
|
||||
"github.com/modelcontextprotocol/ext-interceptors/go/sdk/interceptors"
|
||||
)
|
||||
|
||||
// handleList implements the "interceptors/list" JSON-RPC method.
|
||||
// It returns all registered interceptors, optionally filtered by event.
|
||||
func (s *Server) handleList(_ context.Context, _ *mcp.ServerSession, raw json.RawMessage) (any, error) {
|
||||
var params interceptors.ListParams
|
||||
if len(raw) > 0 {
|
||||
if err := json.Unmarshal(raw, ¶ms); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
all := s.getInterceptors()
|
||||
infos := make([]interceptors.InterceptorInfo, 0, len(all))
|
||||
for _, ri := range all {
|
||||
if params.Event != "" && !slices.Contains(ri.GetMetadata().Hook.Events, params.Event) {
|
||||
continue
|
||||
}
|
||||
infos = append(infos, interceptors.InfoFromInterceptor(ri))
|
||||
}
|
||||
|
||||
return &interceptors.ListResult{Interceptors: infos}, nil
|
||||
}
|
||||
|
||||
// handleInvoke implements the "interceptor/invoke" JSON-RPC method.
|
||||
// It invokes a single interceptor by name and returns its result.
|
||||
func (s *Server) handleInvoke(ctx context.Context, _ *mcp.ServerSession, raw json.RawMessage) (any, error) {
|
||||
var params interceptors.InvokeParams
|
||||
if err := json.Unmarshal(raw, ¶ms); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if params.Name == "" {
|
||||
return nil, &jsonrpc.Error{
|
||||
Code: jsonrpc.CodeInvalidParams,
|
||||
Message: "name is required",
|
||||
}
|
||||
}
|
||||
|
||||
// Look up the interceptor by name.
|
||||
i := s.findByName(params.Name)
|
||||
if i == nil {
|
||||
return nil, &jsonrpc.Error{
|
||||
Code: jsonrpc.CodeInvalidParams,
|
||||
Message: fmt.Sprintf("interceptor %q not found", params.Name),
|
||||
}
|
||||
}
|
||||
|
||||
// Apply timeout if specified.
|
||||
if params.TimeoutMs > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, time.Duration(params.TimeoutMs)*time.Millisecond)
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
inv := &interceptors.Invocation{
|
||||
Event: params.Event,
|
||||
Phase: params.Phase,
|
||||
Payload: params.Payload,
|
||||
Config: params.Config,
|
||||
Context: params.Context,
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
|
||||
result := &interceptors.InvokeResult{
|
||||
Interceptor: params.Name,
|
||||
Type: i.GetType(),
|
||||
Phase: params.Phase,
|
||||
}
|
||||
defer func() { result.DurationMs = time.Since(start).Milliseconds() }()
|
||||
|
||||
switch v := i.(type) {
|
||||
case *interceptors.Validator:
|
||||
vr, err := v.Handler(ctx, inv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result.Validation = vr
|
||||
|
||||
case *interceptors.Mutator:
|
||||
mr, err := v.Handler(ctx, inv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result.Mutation = mr
|
||||
result.Payload = mr.Payload
|
||||
|
||||
default:
|
||||
return nil, &jsonrpc.Error{
|
||||
Code: jsonrpc.CodeInternalError,
|
||||
Message: fmt.Sprintf("unsupported interceptor type %T", i),
|
||||
}
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
264
go/sdk/interceptors/mcpserver/rpc_test.go
Normal file
264
go/sdk/interceptors/mcpserver/rpc_test.go
Normal file
|
|
@ -0,0 +1,264 @@
|
|||
package mcpserver_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/modelcontextprotocol/ext-interceptors/go/sdk/interceptors"
|
||||
)
|
||||
|
||||
// --- interceptors/list tests ---
|
||||
|
||||
func TestListInterceptors(t *testing.T) {
|
||||
t.Parallel()
|
||||
cs := setupRPCServer(t,
|
||||
allowAllValidator("v1"),
|
||||
blockToolValidator("dangerous"),
|
||||
)
|
||||
|
||||
var result interceptors.ListResult
|
||||
err := cs.CallCustom(context.Background(), interceptors.MethodList, nil, &result)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Len(t, result.Interceptors, 2)
|
||||
names := make([]string, len(result.Interceptors))
|
||||
for i, info := range result.Interceptors {
|
||||
names[i] = info.Name
|
||||
}
|
||||
assert.Contains(t, names, "v1")
|
||||
assert.Contains(t, names, "block-dangerous")
|
||||
}
|
||||
|
||||
func TestListWithEventFilter(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
toolsValidator := allowAllValidator("tools-v")
|
||||
promptsValidator := &interceptors.Validator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "prompts-v",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventPromptsGet},
|
||||
Phase: interceptors.PhaseRequest,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(_ context.Context, _ *interceptors.Invocation) (*interceptors.ValidationResult, error) {
|
||||
return &interceptors.ValidationResult{Valid: true}, nil
|
||||
},
|
||||
}
|
||||
|
||||
cs := setupRPCServer(t, toolsValidator, promptsValidator)
|
||||
|
||||
// Filter for tools/call — should only return tools-v
|
||||
var result interceptors.ListResult
|
||||
err := cs.CallCustom(context.Background(), interceptors.MethodList,
|
||||
&interceptors.ListParams{Event: interceptors.EventToolsCall}, &result)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, result.Interceptors, 1)
|
||||
assert.Equal(t, "tools-v", result.Interceptors[0].Name)
|
||||
|
||||
// Filter for prompts/get — should only return prompts-v
|
||||
var result2 interceptors.ListResult
|
||||
err = cs.CallCustom(context.Background(), interceptors.MethodList,
|
||||
&interceptors.ListParams{Event: interceptors.EventPromptsGet}, &result2)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, result2.Interceptors, 1)
|
||||
assert.Equal(t, "prompts-v", result2.Interceptors[0].Name)
|
||||
|
||||
// Filter for non-existent event — empty
|
||||
var result3 interceptors.ListResult
|
||||
err = cs.CallCustom(context.Background(), interceptors.MethodList,
|
||||
&interceptors.ListParams{Event: "nonexistent/method"}, &result3)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, result3.Interceptors)
|
||||
}
|
||||
|
||||
// --- interceptor/invoke tests ---
|
||||
|
||||
func TestInvokeValidator(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cs := setupRPCServer(t, allowAllValidator("v1"))
|
||||
|
||||
payload, _ := json.Marshal(map[string]any{"name": "echo", "arguments": map[string]any{"text": "hello"}})
|
||||
var result interceptors.InvokeResult
|
||||
err := cs.CallCustom(context.Background(), interceptors.MethodInvoke,
|
||||
&interceptors.InvokeParams{
|
||||
Name: "v1",
|
||||
Event: interceptors.EventToolsCall,
|
||||
Phase: interceptors.PhaseRequest,
|
||||
Payload: payload,
|
||||
}, &result)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "v1", result.Interceptor)
|
||||
assert.Equal(t, interceptors.TypeValidation, result.Type)
|
||||
assert.Equal(t, interceptors.PhaseRequest, result.Phase)
|
||||
require.NotNil(t, result.Validation)
|
||||
assert.True(t, result.Validation.Valid)
|
||||
assert.Nil(t, result.Mutation)
|
||||
assert.Nil(t, result.Payload)
|
||||
}
|
||||
|
||||
func TestInvokeValidatorRejects(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
rejectAll := &interceptors.Validator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "reject-all",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseRequest,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(_ context.Context, _ *interceptors.Invocation) (*interceptors.ValidationResult, error) {
|
||||
return &interceptors.ValidationResult{
|
||||
Valid: false,
|
||||
Messages: []interceptors.ValidationMessage{
|
||||
{Message: "rejected", Severity: interceptors.SeverityError},
|
||||
},
|
||||
}, nil
|
||||
},
|
||||
}
|
||||
|
||||
cs := setupRPCServer(t, rejectAll)
|
||||
|
||||
payload, _ := json.Marshal(map[string]any{"name": "echo"})
|
||||
var result interceptors.InvokeResult
|
||||
err := cs.CallCustom(context.Background(), interceptors.MethodInvoke,
|
||||
&interceptors.InvokeParams{
|
||||
Name: "reject-all",
|
||||
Event: interceptors.EventToolsCall,
|
||||
Phase: interceptors.PhaseRequest,
|
||||
Payload: payload,
|
||||
}, &result)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "reject-all", result.Interceptor)
|
||||
assert.Equal(t, interceptors.TypeValidation, result.Type)
|
||||
require.NotNil(t, result.Validation)
|
||||
assert.False(t, result.Validation.Valid)
|
||||
assert.Len(t, result.Validation.Messages, 1)
|
||||
assert.Equal(t, "rejected", result.Validation.Messages[0].Message)
|
||||
}
|
||||
|
||||
func TestInvokeMutator(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mutator := &interceptors.Mutator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "add-field",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseRequest,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(_ context.Context, inv *interceptors.Invocation) (*interceptors.MutationResult, error) {
|
||||
raw, ok := inv.Payload.(json.RawMessage)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected payload type %T", inv.Payload)
|
||||
}
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m["injected"] = true
|
||||
data, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &interceptors.MutationResult{Modified: true, Info: map[string]any{"added": "injected"}, Payload: json.RawMessage(data)}, nil
|
||||
},
|
||||
}
|
||||
|
||||
cs := setupRPCServer(t, mutator)
|
||||
|
||||
payload, _ := json.Marshal(map[string]any{"name": "echo"})
|
||||
var result interceptors.InvokeResult
|
||||
err := cs.CallCustom(context.Background(), interceptors.MethodInvoke,
|
||||
&interceptors.InvokeParams{
|
||||
Name: "add-field",
|
||||
Event: interceptors.EventToolsCall,
|
||||
Phase: interceptors.PhaseRequest,
|
||||
Payload: payload,
|
||||
}, &result)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "add-field", result.Interceptor)
|
||||
assert.Equal(t, interceptors.TypeMutation, result.Type)
|
||||
require.NotNil(t, result.Mutation)
|
||||
assert.True(t, result.Mutation.Modified)
|
||||
assert.Equal(t, "injected", result.Mutation.Info["added"])
|
||||
|
||||
// Verify mutated payload contains the injected field.
|
||||
require.NotNil(t, result.Payload)
|
||||
var mutated map[string]any
|
||||
require.NoError(t, json.Unmarshal(result.Payload, &mutated))
|
||||
assert.Equal(t, true, mutated["injected"])
|
||||
assert.Equal(t, "echo", mutated["name"])
|
||||
}
|
||||
|
||||
func TestInvokeUnknownName(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cs := setupRPCServer(t, allowAllValidator("v1"))
|
||||
|
||||
payload, _ := json.Marshal(map[string]any{})
|
||||
var result interceptors.InvokeResult
|
||||
err := cs.CallCustom(context.Background(), interceptors.MethodInvoke,
|
||||
&interceptors.InvokeParams{
|
||||
Name: "nonexistent",
|
||||
Event: interceptors.EventToolsCall,
|
||||
Phase: interceptors.PhaseRequest,
|
||||
Payload: payload,
|
||||
}, &result)
|
||||
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "nonexistent")
|
||||
}
|
||||
|
||||
func TestInvokeTimeout(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
slowValidator := &interceptors.Validator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "slow-v",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseRequest,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(ctx context.Context, _ *interceptors.Invocation) (*interceptors.ValidationResult, error) {
|
||||
select {
|
||||
case <-time.After(5 * time.Second):
|
||||
return &interceptors.ValidationResult{Valid: true}, nil
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
cs := setupRPCServer(t, slowValidator)
|
||||
|
||||
payload, _ := json.Marshal(map[string]any{})
|
||||
var result interceptors.InvokeResult
|
||||
err := cs.CallCustom(context.Background(), interceptors.MethodInvoke,
|
||||
&interceptors.InvokeParams{
|
||||
Name: "slow-v",
|
||||
Event: interceptors.EventToolsCall,
|
||||
Phase: interceptors.PhaseRequest,
|
||||
Payload: payload,
|
||||
TimeoutMs: 50,
|
||||
}, &result)
|
||||
|
||||
require.Error(t, err)
|
||||
}
|
||||
232
go/sdk/interceptors/mcpserver/server.go
Normal file
232
go/sdk/interceptors/mcpserver/server.go
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
// 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 mcpserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
|
||||
"github.com/modelcontextprotocol/ext-interceptors/go/sdk/interceptors"
|
||||
"github.com/modelcontextprotocol/ext-interceptors/go/sdk/interceptors/chain"
|
||||
)
|
||||
|
||||
// extensionID is the capability key used in Capabilities.Experimental
|
||||
const extensionID = "io.modelcontextprotocol/interceptors"
|
||||
|
||||
// ServerOption configures a Server.
|
||||
type ServerOption func(*Server)
|
||||
|
||||
// WithLogger sets the logger for interceptor chain execution.
|
||||
// If not set, slog.Default() is used.
|
||||
func WithLogger(l *slog.Logger) ServerOption {
|
||||
return func(s *Server) {
|
||||
s.logger = l
|
||||
}
|
||||
}
|
||||
|
||||
// Server wraps an *mcp.Server with interceptor support. Interceptors are
|
||||
// registered as first-class MCP resources discoverable via the
|
||||
// "interceptors/list" JSON-RPC method and invocable via
|
||||
// "interceptor/invoke".
|
||||
type Server struct {
|
||||
inner *mcp.Server
|
||||
mu sync.RWMutex
|
||||
interceptors []interceptors.Interceptor
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
// NewServer creates a new interceptor server wrapping the given mcp.Server.
|
||||
// It registers the "interceptors/list" and "interceptor/invoke" JSON-RPC
|
||||
// methods and installs a receiving middleware to enrich the initialize
|
||||
// response with interceptor capabilities.
|
||||
func NewServer(server *mcp.Server, opts ...ServerOption) *Server {
|
||||
s := &Server{
|
||||
inner: server,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(s)
|
||||
}
|
||||
if s.logger == nil {
|
||||
s.logger = slog.Default()
|
||||
}
|
||||
|
||||
// Register JSON-RPC methods for interceptor discovery and invocation.
|
||||
server.AddCustomMethod(interceptors.MethodList, s.handleList)
|
||||
server.AddCustomMethod(interceptors.MethodInvoke, s.handleInvoke)
|
||||
|
||||
// Install lightweight middleware to enrich initialize responses.
|
||||
server.AddReceivingMiddleware(s.initMiddleware())
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
// AddInterceptor registers an interceptor. It panics if the interceptor
|
||||
// has a nil handler. Except for the panic it is safe to call while the server is running,
|
||||
// returns the receiver for chaining.
|
||||
func (s *Server) AddInterceptor(i interceptors.Interceptor) *Server {
|
||||
switch v := i.(type) {
|
||||
case *interceptors.Validator:
|
||||
if v.Handler == nil {
|
||||
panic("interceptors: validator " + v.Name + " has nil handler")
|
||||
}
|
||||
case *interceptors.Mutator:
|
||||
if v.Handler == nil {
|
||||
panic("interceptors: mutator " + v.Name + " has nil handler")
|
||||
}
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.interceptors = append(s.interceptors, i)
|
||||
s.mu.Unlock()
|
||||
return s
|
||||
}
|
||||
|
||||
// findByName returns the interceptor with the given name, or nil if not found.
|
||||
func (s *Server) findByName(name string) interceptors.Interceptor {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
for _, i := range s.interceptors {
|
||||
if i.GetMetadata().Name == name {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// getInterceptors returns a snapshot of the current interceptor list.
|
||||
func (s *Server) getInterceptors() []interceptors.Interceptor {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
cp := make([]interceptors.Interceptor, len(s.interceptors))
|
||||
copy(cp, s.interceptors)
|
||||
return cp
|
||||
}
|
||||
|
||||
// LocalChain creates an interceptor Chain connected to this server
|
||||
// via in-memory transport. This is the primary way to get a Chain
|
||||
// for use with middleware.
|
||||
//
|
||||
// The returned chain discovers interceptors from the server via
|
||||
// interceptors/list and invokes them via interceptor/invoke, exactly
|
||||
// as a remote chain would — but over an in-memory transport.
|
||||
func (s *Server) LocalChain(ctx context.Context) (*chain.Chain, error) {
|
||||
serverTransport, clientTransport := mcp.NewInMemoryTransports()
|
||||
|
||||
// Connect the server side.
|
||||
ss, err := s.inner.Connect(ctx, serverTransport, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Connect a client through the other end.
|
||||
client := mcp.NewClient(&mcp.Implementation{
|
||||
Name: "interceptor-chain-client",
|
||||
Version: "internal",
|
||||
}, nil)
|
||||
cs, err := client.Connect(ctx, clientTransport, nil)
|
||||
if err != nil {
|
||||
ss.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ch := chain.NewChain(chain.WithChainLogger(s.logger))
|
||||
if err := ch.AddMCPServer(ctx, cs); err != nil {
|
||||
cs.Close()
|
||||
ss.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
// MCPServer returns the underlying *mcp.Server. This is useful when
|
||||
// composing with other extensions (e.g., variants):
|
||||
//
|
||||
// is := mcpserver.NewServer(mcpServer)
|
||||
// is.AddInterceptor(myValidator)
|
||||
// vs.WithVariant(variant, is.MCPServer(), 0)
|
||||
func (s *Server) MCPServer() *mcp.Server {
|
||||
return s.inner
|
||||
}
|
||||
|
||||
// Run delegates to the inner server's Run method. Convenience for standalone
|
||||
// use (e.g., stdio).
|
||||
func (s *Server) Run(ctx context.Context, t mcp.Transport) error {
|
||||
return s.inner.Run(ctx, t)
|
||||
}
|
||||
|
||||
// initMiddleware returns a lightweight mcp.Middleware that enriches the
|
||||
// initialize response with interceptor capability metadata.
|
||||
func (s *Server) initMiddleware() mcp.Middleware {
|
||||
return func(next mcp.MethodHandler) mcp.MethodHandler {
|
||||
return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) {
|
||||
result, err := next(ctx, method, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if method == "initialize" {
|
||||
return s.enrichInitResult(result)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// enrichInitResult injects interceptor capability metadata into the
|
||||
// InitializeResult, following the same pattern as the variants extension.
|
||||
// The capability is declared under Capabilities.Experimental so it works
|
||||
// without upstream go-sdk changes.
|
||||
func (s *Server) enrichInitResult(result mcp.Result) (mcp.Result, error) {
|
||||
initResult, ok := result.(*mcp.InitializeResult)
|
||||
if !ok {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
if initResult.Capabilities == nil {
|
||||
initResult.Capabilities = &mcp.ServerCapabilities{}
|
||||
}
|
||||
if initResult.Capabilities.Experimental == nil {
|
||||
initResult.Capabilities.Experimental = make(map[string]any)
|
||||
}
|
||||
|
||||
all := s.getInterceptors()
|
||||
supportedEvents := map[string]bool{}
|
||||
for _, ri := range all {
|
||||
for _, e := range ri.GetMetadata().Hook.Events {
|
||||
supportedEvents[e] = true
|
||||
}
|
||||
}
|
||||
|
||||
events := make([]string, 0, len(supportedEvents))
|
||||
for e := range supportedEvents {
|
||||
events = append(events, e)
|
||||
}
|
||||
|
||||
initResult.Capabilities.Experimental[extensionID] = map[string]any{
|
||||
"supportedEvents": events,
|
||||
}
|
||||
|
||||
return initResult, nil
|
||||
}
|
||||
|
||||
// NewStreamableHTTPHandler returns a new [mcp.StreamableHTTPHandler] for
|
||||
// serving multiple concurrent clients over HTTP. It mirrors
|
||||
// [mcp.NewStreamableHTTPHandler].
|
||||
//
|
||||
// handler := mcpserver.NewStreamableHTTPHandler(srv, nil)
|
||||
// http.ListenAndServe(":8080", handler)
|
||||
func NewStreamableHTTPHandler(s *Server, opts *mcp.StreamableHTTPOptions) *mcp.StreamableHTTPHandler {
|
||||
if s == nil {
|
||||
panic("mcpserver: nil Server")
|
||||
}
|
||||
srv := s.MCPServer()
|
||||
return mcp.NewStreamableHTTPHandler(
|
||||
func(r *http.Request) *mcp.Server { return srv },
|
||||
opts,
|
||||
)
|
||||
}
|
||||
612
go/sdk/interceptors/mcpserver/server_integration_test.go
Normal file
612
go/sdk/interceptors/mcpserver/server_integration_test.go
Normal file
|
|
@ -0,0 +1,612 @@
|
|||
package mcpserver_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/modelcontextprotocol/ext-interceptors/go/sdk/interceptors"
|
||||
)
|
||||
|
||||
func TestServer_ValidatorRejectsBlockedTool(t *testing.T) {
|
||||
t.Parallel()
|
||||
cs := setup(t, blockToolValidator("echo"))
|
||||
|
||||
_, err := callEcho(t, cs)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestServer_ValidatorAllowsTool(t *testing.T) {
|
||||
t.Parallel()
|
||||
cs := setup(t, allowAllValidator("allow-all"))
|
||||
|
||||
result, err := callEcho(t, cs)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, strings.HasPrefix(resultText(t, result), "echo:"))
|
||||
}
|
||||
|
||||
func TestServer_MutatorModifiesResponse(t *testing.T) {
|
||||
t.Parallel()
|
||||
cs := setup(t, prefixMutator("prefix", "[mutated]", interceptors.PhaseResponse, 0, interceptors.ModeEnforce))
|
||||
|
||||
result, err := callEcho(t, cs)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, strings.HasPrefix(resultText(t, result), "[mutated] echo:"))
|
||||
}
|
||||
|
||||
func TestServer_ChainedMutatorsWithAuditMode(t *testing.T) {
|
||||
t.Parallel()
|
||||
// 5 response mutators in priority order. Mutator 3 (priority 30) is
|
||||
// audit-mode: its "[AUDIT]" prefix must NOT appear in the final output.
|
||||
// Expected final text (applied innermost-first by ascending priority):
|
||||
//
|
||||
// [M5] [M4] [M2] [M1] echo: ...
|
||||
cs := setup(t,
|
||||
prefixMutator("m1", "[M1]", interceptors.PhaseResponse, 10, interceptors.ModeEnforce),
|
||||
prefixMutator("m2", "[M2]", interceptors.PhaseResponse, 20, interceptors.ModeEnforce),
|
||||
prefixMutator("m3-audit", "[AUDIT]", interceptors.PhaseResponse, 30, interceptors.ModeAudit),
|
||||
prefixMutator("m4", "[M4]", interceptors.PhaseResponse, 40, interceptors.ModeEnforce),
|
||||
prefixMutator("m5", "[M5]", interceptors.PhaseResponse, 50, interceptors.ModeEnforce),
|
||||
)
|
||||
|
||||
result, err := callEcho(t, cs)
|
||||
require.NoError(t, err)
|
||||
|
||||
text := resultText(t, result)
|
||||
assert.True(t, strings.HasPrefix(text, "[M5] [M4] [M2] [M1] echo:"))
|
||||
assert.NotContains(t, text, "[AUDIT]")
|
||||
}
|
||||
|
||||
func TestServer_MutatorFailureAbortsChain(t *testing.T) {
|
||||
t.Parallel()
|
||||
// 3 response mutators. Mutator 2 (priority 20) returns an error
|
||||
// and is fail-closed. The chain aborts; client receives an error.
|
||||
cs := setup(t,
|
||||
prefixMutator("m1", "[M1]", interceptors.PhaseResponse, 10, interceptors.ModeEnforce),
|
||||
failMutator("m2-fail", interceptors.PhaseResponse, 20),
|
||||
prefixMutator("m3", "[M3]", interceptors.PhaseResponse, 30, interceptors.ModeEnforce),
|
||||
)
|
||||
|
||||
_, err := callEcho(t, cs)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestServer_ValidatorWarnDoesNotBlock(t *testing.T) {
|
||||
t.Parallel()
|
||||
// A validator returns Valid=false with only SeverityWarn messages.
|
||||
// The chain should continue — warn-only failures don't abort.
|
||||
warnValidator := &interceptors.Validator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "warn-only",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseRequest,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(_ context.Context, _ *interceptors.Invocation) (*interceptors.ValidationResult, error) {
|
||||
return &interceptors.ValidationResult{
|
||||
Valid: false,
|
||||
Messages: []interceptors.ValidationMessage{
|
||||
{Message: "something looks off", Severity: interceptors.SeverityWarn},
|
||||
},
|
||||
}, nil
|
||||
},
|
||||
}
|
||||
|
||||
cs := setup(t, warnValidator)
|
||||
|
||||
result, err := callEcho(t, cs)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, strings.HasPrefix(resultText(t, result), "echo:"))
|
||||
}
|
||||
|
||||
func TestServer_ValidationFailurePreventsM(t *testing.T) {
|
||||
t.Parallel()
|
||||
// A validator rejects the request. A mutator is also registered but
|
||||
// should never run because the chain aborts before mutators.
|
||||
mutatorRan := atomic.Bool{}
|
||||
spy := &interceptors.Mutator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "spy-mutator",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseRequest,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(_ context.Context, _ *interceptors.Invocation) (*interceptors.MutationResult, error) {
|
||||
mutatorRan.Store(true)
|
||||
return &interceptors.MutationResult{Modified: false}, nil
|
||||
},
|
||||
}
|
||||
|
||||
cs := setup(t, blockToolValidator("echo"), spy)
|
||||
|
||||
_, err := callEcho(t, cs)
|
||||
assert.Error(t, err)
|
||||
assert.False(t, mutatorRan.Load(), "mutator should not run after validation failure")
|
||||
}
|
||||
|
||||
func TestServer_ValidatorTimeoutAbortsChain(t *testing.T) {
|
||||
t.Parallel()
|
||||
slowValidator := &interceptors.Validator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "slow-validator",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseRequest,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(ctx context.Context, _ *interceptors.Invocation) (*interceptors.ValidationResult, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
return &interceptors.ValidationResult{Valid: true}, nil
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
cs := setup(t, slowValidator)
|
||||
|
||||
// Per-invocation timeout: context expires before the 100ms handler completes.
|
||||
_, err := callEchoWithTimeout(t, cs, 5*time.Millisecond)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "context deadline exceeded")
|
||||
}
|
||||
|
||||
func TestServer_MutatorTimeoutAbortsChain(t *testing.T) {
|
||||
t.Parallel()
|
||||
// 3 response mutators. Mutator 2 (priority 20) blocks longer than
|
||||
// the invocation timeout. The chain aborts; client receives an error.
|
||||
slowMutator := &interceptors.Mutator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "m2-slow",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseResponse,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
PriorityHint: interceptors.NewPriority(20),
|
||||
},
|
||||
Handler: func(ctx context.Context, _ *interceptors.Invocation) (*interceptors.MutationResult, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
return &interceptors.MutationResult{Modified: false}, nil
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
cs := setup(t,
|
||||
prefixMutator("m1", "[M1]", interceptors.PhaseResponse, 10, interceptors.ModeEnforce),
|
||||
slowMutator,
|
||||
prefixMutator("m3", "[M3]", interceptors.PhaseResponse, 30, interceptors.ModeEnforce),
|
||||
)
|
||||
|
||||
// Per-invocation timeout: context expires before the 100ms handler completes.
|
||||
_, err := callEchoWithTimeout(t, cs, 5*time.Millisecond)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "context deadline exceeded")
|
||||
}
|
||||
|
||||
func TestServer_MutatorFailOpenContinuesChain(t *testing.T) {
|
||||
t.Parallel()
|
||||
// 3 response mutators. Mutator 2 (priority 20) returns an error but
|
||||
// has FailOpen set. The chain continues; M1 and M3 both apply.
|
||||
failOpenMutator := &interceptors.Mutator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "m2-failopen",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseResponse,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
FailOpen: true,
|
||||
PriorityHint: interceptors.NewPriority(20),
|
||||
},
|
||||
Handler: func(_ context.Context, _ *interceptors.Invocation) (*interceptors.MutationResult, error) {
|
||||
return nil, fmt.Errorf("simulated failure")
|
||||
},
|
||||
}
|
||||
|
||||
cs := setup(t,
|
||||
prefixMutator("m1", "[M1]", interceptors.PhaseResponse, 10, interceptors.ModeEnforce),
|
||||
failOpenMutator,
|
||||
prefixMutator("m3", "[M3]", interceptors.PhaseResponse, 30, interceptors.ModeEnforce),
|
||||
)
|
||||
|
||||
result, err := callEcho(t, cs)
|
||||
require.NoError(t, err)
|
||||
|
||||
text := resultText(t, result)
|
||||
assert.Contains(t, text, "[M1]")
|
||||
assert.Contains(t, text, "[M3]")
|
||||
}
|
||||
|
||||
func TestServer_ResponseMutatorSeesMutatedParams(t *testing.T) {
|
||||
t.Parallel()
|
||||
// A request mutator injects a marker into the arguments. A response
|
||||
// mutator reads the request payload and copies the marker into the
|
||||
// response text.
|
||||
//
|
||||
// NOTE: In the SEP model, interceptors receive json.RawMessage payloads.
|
||||
// Response-phase interceptors only see the response payload, not the
|
||||
// request params. This test is simplified to verify request mutation
|
||||
// flows through to the echo handler's output.
|
||||
reqMutator := &interceptors.Mutator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "inject-marker",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseRequest,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(_ context.Context, inv *interceptors.Invocation) (*interceptors.MutationResult, error) {
|
||||
raw, ok := inv.Payload.(json.RawMessage)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected payload type %T", inv.Payload)
|
||||
}
|
||||
var params map[string]any
|
||||
if err := json.Unmarshal(raw, ¶ms); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
args, _ := params["arguments"].(map[string]any)
|
||||
if args == nil {
|
||||
args = map[string]any{}
|
||||
}
|
||||
args["marker"] = "injected-by-request-mutator"
|
||||
params["arguments"] = args
|
||||
data, err := json.Marshal(params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &interceptors.MutationResult{Modified: true, Payload: json.RawMessage(data)}, nil
|
||||
},
|
||||
}
|
||||
|
||||
cs := setup(t, reqMutator)
|
||||
|
||||
result, err := callEcho(t, cs)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, resultText(t, result), "injected-by-request-mutator")
|
||||
}
|
||||
|
||||
func TestServer_CombinedValidatorsAndMutators(t *testing.T) {
|
||||
t.Parallel()
|
||||
// Exercises the full chain with 3 validators and 3 mutators on each
|
||||
// side, verifying:
|
||||
//
|
||||
// Request: Validate (parallel) → Mutate (sequential by priority)
|
||||
// Response: Mutate (sequential by priority) → Validate (parallel)
|
||||
//
|
||||
// Request mutators inject fields into arguments (reflected in echo output).
|
||||
// Response mutators prepend tags to text (visible in final result).
|
||||
// Atomic counters confirm every interceptor actually ran.
|
||||
|
||||
var (
|
||||
reqValCount atomic.Int32
|
||||
reqMutCount atomic.Int32
|
||||
respMutCount atomic.Int32
|
||||
respValCount atomic.Int32
|
||||
)
|
||||
|
||||
// --- Request validators (3, parallel) ---
|
||||
|
||||
// req-v1: passes if tool name is "echo".
|
||||
reqV1 := &interceptors.Validator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "req-v1-tool-check",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseRequest,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(_ context.Context, inv *interceptors.Invocation) (*interceptors.ValidationResult, error) {
|
||||
reqValCount.Add(1)
|
||||
raw, ok := inv.Payload.(json.RawMessage)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected type %T", inv.Payload)
|
||||
}
|
||||
var params struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, ¶ms); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if params.Name != "echo" {
|
||||
return &interceptors.ValidationResult{
|
||||
Valid: false,
|
||||
Messages: []interceptors.ValidationMessage{
|
||||
{Message: "only echo allowed", Severity: interceptors.SeverityError},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
return &interceptors.ValidationResult{Valid: true}, nil
|
||||
},
|
||||
}
|
||||
|
||||
// req-v2: passes if arguments contain "text".
|
||||
reqV2 := &interceptors.Validator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "req-v2-args-check",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseRequest,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(_ context.Context, inv *interceptors.Invocation) (*interceptors.ValidationResult, error) {
|
||||
reqValCount.Add(1)
|
||||
raw, ok := inv.Payload.(json.RawMessage)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected type %T", inv.Payload)
|
||||
}
|
||||
var params struct {
|
||||
Arguments json.RawMessage `json:"arguments"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, ¶ms); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var args map[string]any
|
||||
if err := json.Unmarshal(params.Arguments, &args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, ok := args["text"]; !ok {
|
||||
return &interceptors.ValidationResult{
|
||||
Valid: false,
|
||||
Messages: []interceptors.ValidationMessage{
|
||||
{Message: "missing text argument", Severity: interceptors.SeverityError},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
return &interceptors.ValidationResult{Valid: true}, nil
|
||||
},
|
||||
}
|
||||
|
||||
// req-v3: always passes with a warning (warn doesn't block).
|
||||
reqV3 := &interceptors.Validator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "req-v3-warn",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseRequest,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(_ context.Context, _ *interceptors.Invocation) (*interceptors.ValidationResult, error) {
|
||||
reqValCount.Add(1)
|
||||
return &interceptors.ValidationResult{
|
||||
Valid: true,
|
||||
Messages: []interceptors.ValidationMessage{
|
||||
{Message: "request noted", Severity: interceptors.SeverityWarn},
|
||||
},
|
||||
}, nil
|
||||
},
|
||||
}
|
||||
|
||||
// --- Request mutators (3, sequential by priority 10 → 20 → 30) ---
|
||||
// Each adds a field to the arguments.
|
||||
|
||||
requestArgMutator := func(name, key, value string, priority int) *interceptors.Mutator {
|
||||
return &interceptors.Mutator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: name,
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseRequest,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
PriorityHint: interceptors.NewPriority(priority),
|
||||
},
|
||||
Handler: func(_ context.Context, inv *interceptors.Invocation) (*interceptors.MutationResult, error) {
|
||||
reqMutCount.Add(1)
|
||||
raw, ok := inv.Payload.(json.RawMessage)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected type %T", inv.Payload)
|
||||
}
|
||||
var params map[string]any
|
||||
if err := json.Unmarshal(raw, ¶ms); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
argsRaw := params["arguments"]
|
||||
var args map[string]any
|
||||
if argsRaw != nil {
|
||||
argsBytes, _ := json.Marshal(argsRaw)
|
||||
json.Unmarshal(argsBytes, &args)
|
||||
}
|
||||
if args == nil {
|
||||
args = map[string]any{}
|
||||
}
|
||||
args[key] = value
|
||||
params["arguments"] = args
|
||||
data, err := json.Marshal(params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &interceptors.MutationResult{Modified: true, Payload: json.RawMessage(data)}, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
reqM1 := requestArgMutator("req-m1", "step1", "done", 10)
|
||||
reqM2 := requestArgMutator("req-m2", "step2", "done", 20)
|
||||
reqM3 := requestArgMutator("req-m3", "step3", "done", 30)
|
||||
|
||||
// --- Response mutators (3, sequential by priority 10 → 20 → 30) ---
|
||||
// Each prepends a tag. Applied innermost-first, so final text is:
|
||||
// [RM3] [RM2] [RM1] echo: ...
|
||||
|
||||
respPrefixMutator := func(name, tag string, priority int) *interceptors.Mutator {
|
||||
return &interceptors.Mutator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: name,
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseResponse,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
PriorityHint: interceptors.NewPriority(priority),
|
||||
},
|
||||
Handler: func(_ context.Context, inv *interceptors.Invocation) (*interceptors.MutationResult, error) {
|
||||
respMutCount.Add(1)
|
||||
raw, ok := inv.Payload.(json.RawMessage)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected type %T", inv.Payload)
|
||||
}
|
||||
var result mcp.CallToolResult
|
||||
if err := json.Unmarshal(raw, &result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, c := range result.Content {
|
||||
if tc, ok := c.(*mcp.TextContent); ok {
|
||||
tc.Text = tag + " " + tc.Text
|
||||
}
|
||||
}
|
||||
data, err := json.Marshal(&result)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &interceptors.MutationResult{Modified: true, Payload: json.RawMessage(data)}, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
respM1 := respPrefixMutator("resp-m1", "[RM1]", 10)
|
||||
respM2 := respPrefixMutator("resp-m2", "[RM2]", 20)
|
||||
respM3 := respPrefixMutator("resp-m3", "[RM3]", 30)
|
||||
|
||||
// --- Response validators (3, parallel) ---
|
||||
// Run after response mutators.
|
||||
|
||||
// resp-v1: passes if response has content.
|
||||
respV1 := &interceptors.Validator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "resp-v1-has-content",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseResponse,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(_ context.Context, inv *interceptors.Invocation) (*interceptors.ValidationResult, error) {
|
||||
respValCount.Add(1)
|
||||
raw, ok := inv.Payload.(json.RawMessage)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected type %T", inv.Payload)
|
||||
}
|
||||
var result mcp.CallToolResult
|
||||
if err := json.Unmarshal(raw, &result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(result.Content) == 0 {
|
||||
return &interceptors.ValidationResult{
|
||||
Valid: false,
|
||||
Messages: []interceptors.ValidationMessage{
|
||||
{Message: "empty response", Severity: interceptors.SeverityError},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
return &interceptors.ValidationResult{Valid: true}, nil
|
||||
},
|
||||
}
|
||||
|
||||
// resp-v2: rejects if response text doesn't contain "[RM1]".
|
||||
// This proves the response-side ordering (Mutate → Validate): if
|
||||
// this validator ran before mutators, it wouldn't find the tag.
|
||||
respV2 := &interceptors.Validator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "resp-v2-sees-mutation",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseResponse,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(_ context.Context, inv *interceptors.Invocation) (*interceptors.ValidationResult, error) {
|
||||
respValCount.Add(1)
|
||||
raw, ok := inv.Payload.(json.RawMessage)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected type %T", inv.Payload)
|
||||
}
|
||||
var result mcp.CallToolResult
|
||||
if err := json.Unmarshal(raw, &result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, c := range result.Content {
|
||||
if tc, ok := c.(*mcp.TextContent); ok {
|
||||
if strings.Contains(tc.Text, "[RM1]") {
|
||||
return &interceptors.ValidationResult{Valid: true}, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return &interceptors.ValidationResult{
|
||||
Valid: false,
|
||||
Messages: []interceptors.ValidationMessage{
|
||||
{Message: "response missing mutator tag [RM1]", Severity: interceptors.SeverityError},
|
||||
},
|
||||
}, nil
|
||||
},
|
||||
}
|
||||
|
||||
// resp-v3: always passes with an info message.
|
||||
respV3 := &interceptors.Validator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "resp-v3-info",
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseResponse,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(_ context.Context, _ *interceptors.Invocation) (*interceptors.ValidationResult, error) {
|
||||
respValCount.Add(1)
|
||||
return &interceptors.ValidationResult{
|
||||
Valid: true,
|
||||
Messages: []interceptors.ValidationMessage{
|
||||
{Message: "response looks good", Severity: interceptors.SeverityInfo},
|
||||
},
|
||||
}, nil
|
||||
},
|
||||
}
|
||||
|
||||
cs := setup(t,
|
||||
reqV1, reqV2, reqV3,
|
||||
reqM1, reqM2, reqM3,
|
||||
respM1, respM2, respM3,
|
||||
respV1, respV2, respV3,
|
||||
)
|
||||
|
||||
result, err := callEcho(t, cs)
|
||||
require.NoError(t, err)
|
||||
|
||||
text := resultText(t, result)
|
||||
|
||||
// Response mutators applied in priority order (outermost = highest priority).
|
||||
assert.True(t, strings.HasPrefix(text, "[RM3] [RM2] [RM1] echo:"),
|
||||
"expected response mutator tags in priority order, got: %s", text)
|
||||
|
||||
// Request mutators injected fields into arguments (visible in echo output).
|
||||
assert.Contains(t, text, "step1")
|
||||
assert.Contains(t, text, "step2")
|
||||
assert.Contains(t, text, "step3")
|
||||
|
||||
// Every interceptor ran exactly once.
|
||||
assert.Equal(t, int32(3), reqValCount.Load(), "expected 3 request validators to run")
|
||||
assert.Equal(t, int32(3), reqMutCount.Load(), "expected 3 request mutators to run")
|
||||
assert.Equal(t, int32(3), respMutCount.Load(), "expected 3 response mutators to run")
|
||||
assert.Equal(t, int32(3), respValCount.Load(), "expected 3 response validators to run")
|
||||
}
|
||||
282
go/sdk/interceptors/mcpserver/testharness_test.go
Normal file
282
go/sdk/interceptors/mcpserver/testharness_test.go
Normal file
|
|
@ -0,0 +1,282 @@
|
|||
package mcpserver_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/modelcontextprotocol/ext-interceptors/go/sdk/interceptors"
|
||||
"github.com/modelcontextprotocol/ext-interceptors/go/sdk/interceptors/integrations/gomiddleware"
|
||||
"github.com/modelcontextprotocol/ext-interceptors/go/sdk/interceptors/mcpserver"
|
||||
)
|
||||
|
||||
// --- Server setup ---
|
||||
|
||||
// setup creates an HTTP test server with interceptor support and a connected
|
||||
// client session. The server has a single "echo" tool registered for
|
||||
// EventToolsCall. Cleanup is registered via t.Cleanup.
|
||||
func setup(t *testing.T, is ...interceptors.Interceptor) *mcp.ClientSession {
|
||||
t.Helper()
|
||||
return setupWithTools(t, defaultTools(), is...)
|
||||
}
|
||||
|
||||
// setupWithTools creates an HTTP test server with the given tools and
|
||||
// interceptors. Uses LocalChain to create a chain that invokes
|
||||
// interceptors via interceptor/invoke over in-memory transport.
|
||||
// Cleanup is registered via t.Cleanup.
|
||||
func setupWithTools(t *testing.T, tools []testTool, is ...interceptors.Interceptor) *mcp.ClientSession {
|
||||
t.Helper()
|
||||
|
||||
mcpServer := mcp.NewServer(&mcp.Implementation{
|
||||
Name: "test-server",
|
||||
Version: "0.1.0",
|
||||
}, nil)
|
||||
|
||||
for _, tool := range tools {
|
||||
mcpServer.AddTool(tool.tool, tool.handler)
|
||||
}
|
||||
|
||||
srv := mcpserver.NewServer(mcpServer)
|
||||
for _, i := range is {
|
||||
srv.AddInterceptor(i)
|
||||
}
|
||||
|
||||
// Create a chain via LocalChain (in-memory transport).
|
||||
chain, err := srv.LocalChain(context.Background())
|
||||
require.NoError(t, err)
|
||||
|
||||
// Install the middleware for automatic interceptor execution.
|
||||
mcpServer.AddReceivingMiddleware(gomiddleware.Middleware(chain))
|
||||
|
||||
handler := mcpserver.NewStreamableHTTPHandler(srv, nil)
|
||||
httpServer := httptest.NewServer(handler)
|
||||
t.Cleanup(httpServer.Close)
|
||||
|
||||
client := mcp.NewClient(&mcp.Implementation{Name: "test-client", Version: "0.1.0"}, nil)
|
||||
cs, err := client.Connect(context.Background(), &mcp.StreamableClientTransport{
|
||||
Endpoint: httpServer.URL,
|
||||
}, nil)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { cs.Close() })
|
||||
|
||||
return cs
|
||||
}
|
||||
|
||||
// --- Tool definitions ---
|
||||
|
||||
// testTool pairs a tool definition with its handler for use with setupWithTools.
|
||||
type testTool struct {
|
||||
tool *mcp.Tool
|
||||
handler mcp.ToolHandler
|
||||
}
|
||||
|
||||
// defaultTools returns the standard "echo" tool used by most tests.
|
||||
func defaultTools() []testTool {
|
||||
return []testTool{
|
||||
{
|
||||
tool: &mcp.Tool{
|
||||
Name: "echo",
|
||||
Description: "echoes input",
|
||||
InputSchema: map[string]any{"type": "object"},
|
||||
},
|
||||
handler: func(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
return &mcp.CallToolResult{
|
||||
Content: []mcp.Content{&mcp.TextContent{Text: fmt.Sprintf("echo: %s", req.Params.Arguments)}},
|
||||
}, nil
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// --- Call helpers ---
|
||||
|
||||
// callEcho calls the "echo" tool and returns the result.
|
||||
func callEcho(t *testing.T, cs *mcp.ClientSession) (*mcp.CallToolResult, error) {
|
||||
t.Helper()
|
||||
return cs.CallTool(context.Background(), &mcp.CallToolParams{
|
||||
Name: "echo",
|
||||
Arguments: map[string]any{"text": "hello"},
|
||||
})
|
||||
}
|
||||
|
||||
// callEchoWithTimeout calls the "echo" tool with a context timeout.
|
||||
func callEchoWithTimeout(t *testing.T, cs *mcp.ClientSession, timeout time.Duration) (*mcp.CallToolResult, error) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
return cs.CallTool(ctx, &mcp.CallToolParams{
|
||||
Name: "echo",
|
||||
Arguments: map[string]any{"text": "hello"},
|
||||
})
|
||||
}
|
||||
|
||||
// --- Assertion helpers ---
|
||||
|
||||
// resultText extracts the first TextContent string from a CallToolResult.
|
||||
// Fails the test if the result has no content or the first item isn't TextContent.
|
||||
func resultText(t *testing.T, result *mcp.CallToolResult) string {
|
||||
t.Helper()
|
||||
require.NotEmpty(t, result.Content)
|
||||
tc, ok := result.Content[0].(*mcp.TextContent)
|
||||
require.True(t, ok, "expected TextContent, got %T", result.Content[0])
|
||||
return tc.Text
|
||||
}
|
||||
|
||||
// --- RPC server setup ---
|
||||
|
||||
// setupRPCServer creates an interceptor server with the given interceptors
|
||||
// and returns a connected client session. The client can call custom methods
|
||||
// via raw JSON-RPC.
|
||||
func setupRPCServer(t *testing.T, is ...interceptors.Interceptor) *mcp.ClientSession {
|
||||
t.Helper()
|
||||
|
||||
mcpServer := mcp.NewServer(&mcp.Implementation{
|
||||
Name: "test-server",
|
||||
Version: "0.1.0",
|
||||
}, nil)
|
||||
|
||||
// A minimal tool so the server has something to initialize with.
|
||||
mcpServer.AddTool(&mcp.Tool{
|
||||
Name: "echo",
|
||||
Description: "echoes input",
|
||||
InputSchema: map[string]any{"type": "object"},
|
||||
}, func(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
return &mcp.CallToolResult{
|
||||
Content: []mcp.Content{&mcp.TextContent{Text: fmt.Sprintf("echo: %s", req.Params.Arguments)}},
|
||||
}, nil
|
||||
})
|
||||
|
||||
srv := mcpserver.NewServer(mcpServer)
|
||||
for _, i := range is {
|
||||
srv.AddInterceptor(i)
|
||||
}
|
||||
|
||||
handler := mcpserver.NewStreamableHTTPHandler(srv, nil)
|
||||
httpServer := httptest.NewServer(handler)
|
||||
t.Cleanup(httpServer.Close)
|
||||
|
||||
client := mcp.NewClient(&mcp.Implementation{Name: "test-client", Version: "0.1.0"}, nil)
|
||||
cs, err := client.Connect(context.Background(), &mcp.StreamableClientTransport{
|
||||
Endpoint: httpServer.URL,
|
||||
}, nil)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { cs.Close() })
|
||||
|
||||
return cs
|
||||
}
|
||||
|
||||
// --- Interceptor builders ---
|
||||
// All handlers work with json.RawMessage payloads since that's what
|
||||
// interceptor/invoke delivers.
|
||||
|
||||
// prefixMutator creates a mutator that prepends tag to each TextContent
|
||||
// in a CallToolResult (response phase).
|
||||
func prefixMutator(name, tag string, phase interceptors.InterceptionPhase, priority int, mode interceptors.Mode) *interceptors.Mutator {
|
||||
return &interceptors.Mutator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: name,
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: phase,
|
||||
},
|
||||
Mode: mode,
|
||||
PriorityHint: interceptors.NewPriority(priority),
|
||||
},
|
||||
Handler: func(_ context.Context, inv *interceptors.Invocation) (*interceptors.MutationResult, error) {
|
||||
raw, ok := inv.Payload.(json.RawMessage)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected payload type %T", inv.Payload)
|
||||
}
|
||||
var result mcp.CallToolResult
|
||||
if err := json.Unmarshal(raw, &result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, c := range result.Content {
|
||||
if tc, ok := c.(*mcp.TextContent); ok {
|
||||
tc.Text = tag + " " + tc.Text
|
||||
}
|
||||
}
|
||||
data, err := json.Marshal(&result)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &interceptors.MutationResult{Modified: true, Payload: json.RawMessage(data)}, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// failMutator creates a mutator that always returns an error.
|
||||
func failMutator(name string, phase interceptors.InterceptionPhase, priority int) *interceptors.Mutator {
|
||||
return &interceptors.Mutator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: name,
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: phase,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
PriorityHint: interceptors.NewPriority(priority),
|
||||
},
|
||||
Handler: func(_ context.Context, _ *interceptors.Invocation) (*interceptors.MutationResult, error) {
|
||||
return nil, fmt.Errorf("simulated failure")
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// blockToolValidator creates a request validator that rejects calls to the named tool.
|
||||
func blockToolValidator(toolName string) *interceptors.Validator {
|
||||
return &interceptors.Validator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: "block-" + toolName,
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseRequest,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(_ context.Context, inv *interceptors.Invocation) (*interceptors.ValidationResult, error) {
|
||||
raw, ok := inv.Payload.(json.RawMessage)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected payload type %T", inv.Payload)
|
||||
}
|
||||
var params struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, ¶ms); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if params.Name == toolName {
|
||||
return &interceptors.ValidationResult{
|
||||
Valid: false,
|
||||
Messages: []interceptors.ValidationMessage{
|
||||
{Message: toolName + " is blocked", Severity: interceptors.SeverityError},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
return &interceptors.ValidationResult{Valid: true}, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// allowAllValidator creates a request validator that allows all calls.
|
||||
func allowAllValidator(name string) *interceptors.Validator {
|
||||
return &interceptors.Validator{
|
||||
Metadata: interceptors.Metadata{
|
||||
Name: name,
|
||||
Hook: interceptors.Hook{
|
||||
Events: []string{interceptors.EventToolsCall},
|
||||
Phase: interceptors.PhaseRequest,
|
||||
},
|
||||
Mode: interceptors.ModeEnforce,
|
||||
},
|
||||
Handler: func(_ context.Context, _ *interceptors.Invocation) (*interceptors.ValidationResult, error) {
|
||||
return &interceptors.ValidationResult{Valid: true}, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
62
go/sdk/interceptors/priority.go
Normal file
62
go/sdk/interceptors/priority.go
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
// 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
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// Priority represents an interceptor's ordering hint.
|
||||
// Can be a single value (applies to both phases) or per-phase.
|
||||
//
|
||||
// JSON representation is polymorphic: a single number when both
|
||||
// phases are equal, or {"request": N, "response": N} when they differ.
|
||||
type Priority struct {
|
||||
Request int
|
||||
Response int
|
||||
}
|
||||
|
||||
// NewPriority creates a Priority with the same value for both phases.
|
||||
func NewPriority(v int) Priority {
|
||||
return Priority{Request: v, Response: v}
|
||||
}
|
||||
|
||||
// Resolve returns the priority for the given phase.
|
||||
func (p Priority) Resolve(phase InterceptionPhase) int {
|
||||
if phase == PhaseResponse {
|
||||
return p.Response
|
||||
}
|
||||
return p.Request
|
||||
}
|
||||
|
||||
// MarshalJSON implements polymorphic serialization:
|
||||
// emits a single number when both phases are equal, or an object otherwise.
|
||||
func (p Priority) MarshalJSON() ([]byte, error) {
|
||||
if p.Request == p.Response {
|
||||
return json.Marshal(p.Request)
|
||||
}
|
||||
return json.Marshal(struct {
|
||||
Request int `json:"request,omitempty"`
|
||||
Response int `json:"response,omitempty"`
|
||||
}{p.Request, p.Response})
|
||||
}
|
||||
|
||||
// UnmarshalJSON handles both number and {request, response} forms.
|
||||
func (p *Priority) UnmarshalJSON(data []byte) error {
|
||||
var n int
|
||||
if err := json.Unmarshal(data, &n); err == nil {
|
||||
p.Request = n
|
||||
p.Response = n
|
||||
return nil
|
||||
}
|
||||
var obj struct {
|
||||
Request int `json:"request"`
|
||||
Response int `json:"response"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &obj); err != nil {
|
||||
return err
|
||||
}
|
||||
p.Request = obj.Request
|
||||
p.Response = obj.Response
|
||||
return nil
|
||||
}
|
||||
98
go/sdk/interceptors/wire.go
Normal file
98
go/sdk/interceptors/wire.go
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
// 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
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// JSON-RPC method names for the interceptor protocol.
|
||||
const (
|
||||
MethodList = "interceptors/list"
|
||||
MethodInvoke = "interceptor/invoke"
|
||||
)
|
||||
|
||||
// Event name constants for standard MCP methods.
|
||||
const (
|
||||
// Server Features
|
||||
EventToolsList = "tools/list"
|
||||
EventToolsCall = "tools/call"
|
||||
EventPromptsList = "prompts/list"
|
||||
EventPromptsGet = "prompts/get"
|
||||
EventResourcesList = "resources/list"
|
||||
EventResourcesRead = "resources/read"
|
||||
EventResourcesSubscribe = "resources/subscribe"
|
||||
)
|
||||
|
||||
// --- interceptors/list ---
|
||||
|
||||
// ListParams are the optional parameters for the interceptors/list method.
|
||||
type ListParams struct {
|
||||
Event string `json:"event,omitempty"` // Filter by event name; empty = all
|
||||
}
|
||||
|
||||
// InterceptorInfo describes a registered interceptor in wire format.
|
||||
type InterceptorInfo struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Type InterceptorType `json:"type"`
|
||||
Hook Hook `json:"hook"`
|
||||
PriorityHint Priority `json:"priorityHint,omitempty"`
|
||||
Compat *Compat `json:"compat,omitempty"`
|
||||
ConfigSchema json.RawMessage `json:"configSchema,omitempty"`
|
||||
Mode Mode `json:"mode"`
|
||||
FailOpen bool `json:"failOpen,omitempty"`
|
||||
}
|
||||
|
||||
// InfoFromInterceptor builds an InterceptorInfo from an Interceptor.
|
||||
func InfoFromInterceptor(i Interceptor) InterceptorInfo {
|
||||
m := i.GetMetadata()
|
||||
return InterceptorInfo{
|
||||
Name: m.Name,
|
||||
Version: m.Version,
|
||||
Description: m.Description,
|
||||
Type: i.GetType(),
|
||||
Hook: m.Hook,
|
||||
PriorityHint: m.PriorityHint,
|
||||
Compat: m.Compat,
|
||||
ConfigSchema: m.ConfigSchema,
|
||||
Mode: m.Mode,
|
||||
FailOpen: m.FailOpen,
|
||||
}
|
||||
}
|
||||
|
||||
// ListResult is the result of the interceptors/list method.
|
||||
type ListResult struct {
|
||||
Interceptors []InterceptorInfo `json:"interceptors"`
|
||||
}
|
||||
|
||||
// --- interceptor/invoke ---
|
||||
|
||||
// InvokeParams are the parameters for the interceptor/invoke method.
|
||||
// The caller specifies which interceptor to invoke by name.
|
||||
type InvokeParams struct {
|
||||
Name string `json:"name"`
|
||||
Event string `json:"event"`
|
||||
Phase InterceptionPhase `json:"phase"`
|
||||
Payload json.RawMessage `json:"payload"`
|
||||
TimeoutMs int64 `json:"timeoutMs,omitempty"`
|
||||
Config map[string]any `json:"config,omitempty"`
|
||||
Context *InvocationContext `json:"context,omitempty"`
|
||||
}
|
||||
|
||||
// InvokeResult is the result of the interceptor/invoke method.
|
||||
// Fields are type-specific: validators populate Validation, mutators populate Mutation + Payload.
|
||||
type InvokeResult struct {
|
||||
Interceptor string `json:"interceptor"`
|
||||
Type InterceptorType `json:"type"`
|
||||
Phase InterceptionPhase `json:"phase"`
|
||||
DurationMs int64 `json:"durationMs"`
|
||||
|
||||
// Validation result (type == "validation")
|
||||
Validation *ValidationResult `json:"validation,omitempty"`
|
||||
|
||||
// Mutation result (type == "mutation")
|
||||
Mutation *MutationResult `json:"mutation,omitempty"`
|
||||
Payload json.RawMessage `json:"payload,omitempty"` // Mutated payload (only for mutators)
|
||||
}
|
||||
Loading…
Reference in a new issue