GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(relay): add policy evaluation handler for tool calls · majorcontext/keep@dbcc765

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • internal/relay
    • handler.go
    • handler_test.go
    • testdata/rules
      • test-tools.yaml
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎internal/relay/handler.go‎

Copy file name to clipboard
+72Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package relay
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"time"
7+
8+
"github.com/majorcontext/keep"
9+
"github.com/majorcontext/keep/internal/audit"
10+
"github.com/majorcontext/keep/internal/relay/mcp"
11+
)
12+
13+
// RelayHandler bridges MCP tool calls to Keep policy evaluation.
14+
type RelayHandler struct {
15+
engine *keep.Engine
16+
router *Router
17+
logger *audit.Logger
18+
}
19+
20+
// NewRelayHandler creates a handler that evaluates policy on every tool call.
21+
func NewRelayHandler(engine *keep.Engine, router *Router, logger *audit.Logger) *RelayHandler {
22+
return &RelayHandler{engine: engine, router: router, logger: logger}
23+
}
24+
25+
// HandleToolCall implements mcp.Handler.
26+
func (h *RelayHandler) HandleToolCall(ctx context.Context, name string, args map[string]any) (*mcp.ToolCallResult, error) {
27+
// 1. Lookup route
28+
route, err := h.router.Lookup(name)
29+
if err != nil {
30+
return nil, err
31+
}
32+
33+
// 2. Build Keep call
34+
call := keep.Call{
35+
Operation: name,
36+
Params: args,
37+
Context: keep.CallContext{
38+
AgentID: "relay", // TODO: extract from request context
39+
Timestamp: time.Now(),
40+
Scope: route.Scope,
41+
Direction: "request",
42+
},
43+
}
44+
45+
// 3. Evaluate policy
46+
result, err := h.engine.Evaluate(call, route.Scope)
47+
if err != nil {
48+
return nil, fmt.Errorf("policy evaluation error: %w", err)
49+
}
50+
51+
// 4. Log audit entry
52+
if h.logger != nil {
53+
h.logger.Log(result.Audit)
54+
}
55+
56+
// 5. Handle decision
57+
switch result.Decision {
58+
case keep.Deny:
59+
msg := result.Message
60+
if msg == "" {
61+
msg = "Denied by policy"
62+
}
63+
return nil, fmt.Errorf("policy denied: %s (rule: %s)", msg, result.Rule)
64+
65+
case keep.Redact:
66+
// Apply mutations to args before forwarding
67+
args = keep.ApplyMutations(args, result.Mutations)
68+
}
69+
70+
// 6. Forward to upstream
71+
return route.Client.CallTool(ctx, name, args)
72+
}
Collapse file

‎internal/relay/handler_test.go‎

Copy file name to clipboard
+269Lines changed: 269 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,269 @@
1+
package relay
2+
3+
import (
4+
"bytes"
5+
"context"
6+
"encoding/json"
7+
"net/http"
8+
"net/http/httptest"
9+
"strings"
10+
"testing"
11+
12+
"github.com/majorcontext/keep"
13+
"github.com/majorcontext/keep/internal/audit"
14+
relayconfig "github.com/majorcontext/keep/internal/relay/config"
15+
"github.com/majorcontext/keep/internal/relay/mcp"
16+
)
17+
18+
// mockUpstreamWithEcho starts a mock MCP server that echoes tool call args back
19+
// as JSON in the result content, enabling redaction verification.
20+
func mockUpstreamWithEcho(t *testing.T, tools []mcp.Tool) *httptest.Server {
21+
t.Helper()
22+
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
23+
var req mcp.JSONRPCRequest
24+
json.NewDecoder(r.Body).Decode(&req)
25+
26+
var resp mcp.JSONRPCResponse
27+
resp.JSONRPC = "2.0"
28+
resp.ID = req.ID
29+
30+
switch req.Method {
31+
case "initialize":
32+
resp.Result = mcp.InitializeResult{
33+
ProtocolVersion: "2025-03-26",
34+
Capabilities: mcp.ServerCapabilities{Tools: &mcp.ToolsCapability{}},
35+
}
36+
case "tools/list":
37+
resp.Result = mcp.ListToolsResult{Tools: tools}
38+
case "tools/call":
39+
// Echo back the arguments so tests can verify mutations.
40+
paramsBytes, _ := json.Marshal(req.Params)
41+
var params mcp.ToolCallParams
42+
json.Unmarshal(paramsBytes, &params)
43+
argsJSON, _ := json.Marshal(params.Arguments)
44+
resp.Result = mcp.ToolCallResult{
45+
Content: []mcp.ContentBlock{{Type: "text", Text: string(argsJSON)}},
46+
}
47+
}
48+
49+
json.NewEncoder(w).Encode(resp)
50+
}))
51+
}
52+
53+
// mockUpstreamError starts a mock MCP server that always returns a JSON-RPC
54+
// error for tools/call requests.
55+
func mockUpstreamError(t *testing.T, tools []mcp.Tool) *httptest.Server {
56+
t.Helper()
57+
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
58+
var req mcp.JSONRPCRequest
59+
json.NewDecoder(r.Body).Decode(&req)
60+
61+
var resp mcp.JSONRPCResponse
62+
resp.JSONRPC = "2.0"
63+
resp.ID = req.ID
64+
65+
switch req.Method {
66+
case "initialize":
67+
resp.Result = mcp.InitializeResult{
68+
ProtocolVersion: "2025-03-26",
69+
Capabilities: mcp.ServerCapabilities{Tools: &mcp.ToolsCapability{}},
70+
}
71+
case "tools/list":
72+
resp.Result = mcp.ListToolsResult{Tools: tools}
73+
case "tools/call":
74+
resp.Error = &mcp.JSONRPCError{Code: -32000, Message: "upstream internal error"}
75+
}
76+
77+
json.NewEncoder(w).Encode(resp)
78+
}))
79+
}
80+
81+
// setupTest builds a RelayHandler backed by a mock upstream and the test rules
82+
// in testdata/rules/. Returns the handler and a buffer that captures audit log
83+
// output.
84+
func setupTest(t *testing.T) (*RelayHandler, *bytes.Buffer) {
85+
t.Helper()
86+
87+
tools := []mcp.Tool{
88+
{Name: "allowed_tool", Description: "An allowed tool"},
89+
{Name: "dangerous_tool", Description: "A dangerous tool"},
90+
{Name: "read_file", Description: "Reads a file"},
91+
}
92+
93+
// 1. Start mock upstream with echo behaviour.
94+
srv := mockUpstreamWithEcho(t, tools)
95+
t.Cleanup(srv.Close)
96+
97+
// 2. Load Keep engine from testdata/rules/.
98+
engine, err := keep.Load("testdata/rules")
99+
if err != nil {
100+
t.Fatalf("keep.Load: %v", err)
101+
}
102+
t.Cleanup(engine.Close)
103+
104+
// 3. Build Router from the mock upstream.
105+
routes := []relayconfig.Route{
106+
{Scope: "test-scope", Upstream: srv.URL},
107+
}
108+
router, err := NewRouter(context.Background(), routes)
109+
if err != nil {
110+
t.Fatalf("NewRouter: %v", err)
111+
}
112+
113+
// 4. Create audit logger writing to a buffer.
114+
var buf bytes.Buffer
115+
logger := audit.NewLogger(&buf)
116+
117+
// 5. Create RelayHandler.
118+
handler := NewRelayHandler(engine, router, logger)
119+
120+
return handler, &buf
121+
}
122+
123+
// TestHandler_Allow verifies that a tool with no matching deny rules is
124+
// forwarded to the upstream and the result is returned to the caller.
125+
func TestHandler_Allow(t *testing.T) {
126+
handler, _ := setupTest(t)
127+
128+
result, err := handler.HandleToolCall(context.Background(), "allowed_tool", map[string]any{"x": "1"})
129+
if err != nil {
130+
t.Fatalf("HandleToolCall: unexpected error: %v", err)
131+
}
132+
if result == nil || len(result.Content) == 0 {
133+
t.Fatal("HandleToolCall: expected non-empty result")
134+
}
135+
}
136+
137+
// TestHandler_Deny verifies that a tool matched by a deny rule returns an
138+
// error containing the rule name and policy message. The upstream must never
139+
// be called.
140+
func TestHandler_Deny(t *testing.T) {
141+
handler, _ := setupTest(t)
142+
143+
result, err := handler.HandleToolCall(context.Background(), "dangerous_tool", map[string]any{})
144+
if err == nil {
145+
t.Fatal("HandleToolCall: expected error for denied tool, got nil")
146+
}
147+
if result != nil {
148+
t.Errorf("HandleToolCall: expected nil result on deny, got %+v", result)
149+
}
150+
151+
errStr := err.Error()
152+
if !strings.Contains(errStr, "block-dangerous") {
153+
t.Errorf("error should contain rule name %q, got: %s", "block-dangerous", errStr)
154+
}
155+
if !strings.Contains(errStr, "This tool is blocked by policy.") {
156+
t.Errorf("error should contain policy message, got: %s", errStr)
157+
}
158+
}
159+
160+
// TestHandler_Redact verifies that args containing secrets are redacted before
161+
// being forwarded to the upstream. The mock upstream echoes the args it
162+
// received so we can inspect them.
163+
func TestHandler_Redact(t *testing.T) {
164+
handler, _ := setupTest(t)
165+
166+
args := map[string]any{
167+
"path": "/etc/config",
168+
"content": "value=SECRET_KEY other=SECRET_TOKEN",
169+
}
170+
171+
result, err := handler.HandleToolCall(context.Background(), "read_file", args)
172+
if err != nil {
173+
t.Fatalf("HandleToolCall: unexpected error: %v", err)
174+
}
175+
if result == nil || len(result.Content) == 0 {
176+
t.Fatal("HandleToolCall: expected non-empty result")
177+
}
178+
179+
// The upstream echoed the args it received. Parse them back.
180+
echoedText := result.Content[0].Text
181+
var echoedArgs map[string]any
182+
if err := json.Unmarshal([]byte(echoedText), &echoedArgs); err != nil {
183+
t.Fatalf("parse echoed args: %v", err)
184+
}
185+
186+
content, ok := echoedArgs["content"].(string)
187+
if !ok {
188+
t.Fatalf("echoed args missing 'content' string field")
189+
}
190+
if strings.Contains(content, "SECRET_KEY") || strings.Contains(content, "SECRET_TOKEN") {
191+
t.Errorf("upstream received unredacted content: %s", content)
192+
}
193+
if !strings.Contains(content, "[REDACTED]") {
194+
t.Errorf("upstream content does not contain redaction marker: %s", content)
195+
}
196+
}
197+
198+
// TestHandler_UnknownTool verifies that a call to a tool not in the router
199+
// returns an error.
200+
func TestHandler_UnknownTool(t *testing.T) {
201+
handler, _ := setupTest(t)
202+
203+
result, err := handler.HandleToolCall(context.Background(), "nonexistent_tool", map[string]any{})
204+
if err == nil {
205+
t.Fatal("HandleToolCall: expected error for unknown tool, got nil")
206+
}
207+
if result != nil {
208+
t.Errorf("HandleToolCall: expected nil result for unknown tool, got %+v", result)
209+
}
210+
}
211+
212+
// TestHandler_UpstreamError verifies that when the upstream returns an error
213+
// it is surfaced to the caller.
214+
func TestHandler_UpstreamError(t *testing.T) {
215+
tools := []mcp.Tool{
216+
{Name: "allowed_tool", Description: "An allowed tool"},
217+
}
218+
srv := mockUpstreamError(t, tools)
219+
t.Cleanup(srv.Close)
220+
221+
engine, err := keep.Load("testdata/rules")
222+
if err != nil {
223+
t.Fatalf("keep.Load: %v", err)
224+
}
225+
t.Cleanup(engine.Close)
226+
227+
routes := []relayconfig.Route{
228+
{Scope: "test-scope", Upstream: srv.URL},
229+
}
230+
router, err := NewRouter(context.Background(), routes)
231+
if err != nil {
232+
t.Fatalf("NewRouter: %v", err)
233+
}
234+
235+
handler := NewRelayHandler(engine, router, nil)
236+
237+
result, err := handler.HandleToolCall(context.Background(), "allowed_tool", map[string]any{})
238+
if err == nil {
239+
t.Fatal("HandleToolCall: expected upstream error, got nil")
240+
}
241+
if result != nil {
242+
t.Errorf("HandleToolCall: expected nil result on upstream error, got %+v", result)
243+
}
244+
if !strings.Contains(err.Error(), "upstream internal error") {
245+
t.Errorf("error should mention upstream error message, got: %v", err)
246+
}
247+
}
248+
249+
// TestHandler_AuditLogged verifies that after a tool call the audit logger
250+
// buffer contains at least one JSON line with the evaluation decision.
251+
func TestHandler_AuditLogged(t *testing.T) {
252+
handler, buf := setupTest(t)
253+
254+
_, _ = handler.HandleToolCall(context.Background(), "allowed_tool", map[string]any{})
255+
256+
line := buf.String()
257+
if line == "" {
258+
t.Fatal("audit buffer is empty; expected a JSON audit entry")
259+
}
260+
261+
// The line should be valid JSON and contain a "Decision" field.
262+
var entry map[string]any
263+
if err := json.Unmarshal([]byte(strings.TrimSpace(line)), &entry); err != nil {
264+
t.Fatalf("audit entry is not valid JSON: %v\nraw: %s", err, line)
265+
}
266+
if _, ok := entry["Decision"]; !ok {
267+
t.Errorf("audit entry missing 'Decision' field; got keys: %v", entry)
268+
}
269+
}
Collapse file

‎internal/relay/testdata/rules/test-tools.yaml‎

Copy file name to clipboard
+17Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
scope: test-scope
2+
mode: enforce
3+
rules:
4+
- name: block-dangerous
5+
match:
6+
operation: "dangerous_tool"
7+
action: deny
8+
message: "This tool is blocked by policy."
9+
- name: redact-secrets
10+
match:
11+
operation: "read_file"
12+
action: redact
13+
redact:
14+
target: "params.content"
15+
patterns:
16+
- match: "SECRET_[A-Z]+"
17+
replace: "[REDACTED]"

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.