diff --git a/pkgs/mcpx/docs/configuration.md b/pkgs/mcpx/docs/configuration.md index 66710db6f0..3bae3617c8 100644 --- a/pkgs/mcpx/docs/configuration.md +++ b/pkgs/mcpx/docs/configuration.md @@ -184,6 +184,74 @@ Each entry is one of: A pattern that cannot compile is a configuration error naming the field, not a rule that silently matches nothing. +### Constraining calls by their arguments + +Hiding decides by tool name: a tool is callable with any arguments or not at +all. `argumentRules` decides by the call: a per-server map in the `mcpx` +block -- also allowed in the top-level `pool` block -- whose keys are tool +patterns matched exactly as `tools`/`excludeTools` match (exact name, glob, +or `/regexp/`), and whose values are JSON Schema objects. A call is allowed +only if its arguments validate against **every** rule whose key matches the +tool. Pool rules and server rules add up, and so do rules from layered config +files: rules only tighten, and a nearer file cannot loosen a farther one. + +```json +{ + "mcpServers": { + "github": { + "command": "...", + "mcpx": { + "argumentRules": { + "create_repository": { + "required": ["private", "organization"], + "properties": { + "private": { "const": true }, + "organization": { "pattern": "^(my-org|my-org-sandbox)$" } + } + }, + "/^(push_files|create_or_update_file|delete_file)$/": { + "required": ["branch"], + "properties": { "branch": { "not": { "enum": ["main", "master"] } } } + }, + "*": { + "properties": { "owner": { "pattern": "^(my-org|my-user)$" } } + } + } + } + } + } +} +``` + +Per-argument rules are the same mechanism: a `"*"` key whose schema is a +`properties` object constrains that argument on every tool that carries it, +and leaves tools without the argument untouched. + +A refused call is a 400, as a hidden tool is, before the server is started: +the message names the argument path, the value sent, the constraint it +broke, and where the rule came from (config file, server, key). Over the MCP +pass-through the same refusal arrives as a tool result with `isError: true`. +Listings advertise the tightened schema: the `inputSchema` shown by +`mcpx types`, the generated client, search, and the pass-through's +`tools/list` is the upstream schema `allOf` every matching rule, so an agent +sees `private: true` before it ever calls. + +A rule whose key matches no tool on its server warns at load and on catalog +changes -- a server that renames a tool must not silently disable the rule +that guarded it. A value that is not a valid schema, or a `pattern` the +validator cannot compile (JSON Schema patterns are ECMA-262; lookahead and +backreferences are unsupported), is a configuration error naming the server +and key, like a bad tool pattern. + +Two cautions, plainly: + +- **Server defaults are invisible.** A rule constrains what is *sent*, not + what the server fills in. If a constraint matters, list the argument in + `required` -- never rely on a server-side default to satisfy it. +- **Free-form arguments cannot truly be constrained.** A `pattern` over a + `query`/`jql`/`sql` string matches text, not meaning. A tool whose danger + lives in a free-form argument belongs in `excludeTools`, not in a rule. + `extraIncludeTools` takes the same entries and adds them to the allowlist instead of replacing it, so a server can widen a pool-wide `tools` by one tool without restating the rest: diff --git a/pkgs/mcpx/internal/codegen/codegen_test.go b/pkgs/mcpx/internal/codegen/codegen_test.go index c72feb2620..f5e5af6939 100644 --- a/pkgs/mcpx/internal/codegen/codegen_test.go +++ b/pkgs/mcpx/internal/codegen/codegen_test.go @@ -122,6 +122,25 @@ func TestAllOfBecomesIntersection(t *testing.T) { } } +// The effective schema for a ruled tool (#1986) keeps the upstream +// properties and required list at the root and adds the rules under +// allOf. The rendered type must keep the root fields: dropping them +// would hide required arguments (path, owner) behind the one field a +// rule happens to constrain. +func TestAllOfKeepsSiblingRootProperties(t *testing.T) { + got := typeOf(t, `{ + "type":"object", + "properties":{"path":{"type":"string"},"owner":{"type":"string"}}, + "required":["path","owner"], + "allOf":[{"type":"object","properties":{"owner":{"enum":["my-org"]}},"required":["owner"]}] + }`) + for _, want := range []string{"path: string;", "owner: string;", `owner: "my-org";`, "&"} { + if !strings.Contains(got, want) { + t.Errorf("rendered type %q missing %q", got, want) + } + } +} + func TestAdditionalPropertiesBecomesIndexSignature(t *testing.T) { got := typeOf(t, `{"type":"object","properties":{"a":{"type":"string"}},"additionalProperties":{"type":"number"}}`) if !strings.Contains(got, "[key: string]: number;") { @@ -364,3 +383,23 @@ func TestOutputSchemaTypeGeneration(t *testing.T) { t.Fatalf("module missing typed return signature or Attached export:\n%s", mod) } } + +// Argument rules (#1986) carry their required lists under allOf (via +// EffectiveSchema $defs copies), not at the root: a rule that requires +// an argument must still make the generated parameter mandatory, or +// generated clients pass strict type checking for calls the gate +// necessarily rejects (Codex P2 on PR #2855, round 5). +func TestArgsTypeMarksRuleRequiredAsMandatory(t *testing.T) { + _, optional := codegen.ArgsTypeFor(json.RawMessage(`{"type":"object","properties":{"a":{"type":"string"}},"allOf":[{"required":["a"]}]}`), "") + if optional { + t.Fatal("an allOf member requiring a prop must demand the argument object") + } + _, optional = codegen.ArgsTypeFor(json.RawMessage(`{"type":"object","properties":{"a":{"type":"string"}},"$defs":{"argumentrule0$doc":{"type":"object","required":["a"]}},"allOf":[{"$ref":"#/$defs/argumentrule0$doc"}]}`), "") + if optional { + t.Fatal("a $ref'd rule requiring a prop must demand the argument object") + } + _, optional = codegen.ArgsTypeFor(json.RawMessage(`{"type":"object","properties":{"a":{"type":"string"}},"anyOf":[{"required":["a"]}]}`), "") + if !optional { + t.Fatal("an anyOf branch requiring a prop must not demand the argument object") + } +} diff --git a/pkgs/mcpx/internal/codegen/ts.go b/pkgs/mcpx/internal/codegen/ts.go index 47394e20c1..da27943375 100644 --- a/pkgs/mcpx/internal/codegen/ts.go +++ b/pkgs/mcpx/internal/codegen/ts.go @@ -97,7 +97,41 @@ func ArgsTypeFor(raw json.RawMessage, indent string) (ts string, optional bool) return "Record", true } r := &renderer{root: &s, seen: map[string]bool{}} - return r.render(&s, indent), len(s.Required) == 0 + return r.render(&s, indent), !requiresArgs(&s, &s, map[string]bool{}) +} + +// requiresArgs reports whether the schema makes the argument object +// itself mandatory: a non-empty required list at the root or in any +// allOf member (resolving $refs into the root $defs). Argument rules +// (#1986) place their required lists under allOf via EffectiveSchema, +// so looking only at the root list would render a parameter optional +// that the argument-rule gate necessarily rejects when omitted. +// anyOf/oneOf members do not count: a caller may satisfy the schema +// through a branch that requires nothing. +func requiresArgs(s *schema, root *schema, seen map[string]bool) bool { + if s == nil { + return false + } + if len(s.Required) > 0 { + return true + } + if s.Ref != "" { + if seen[s.Ref] { + return false + } + seen[s.Ref] = true + r := &renderer{root: root} + if target := r.resolve(s.Ref); target != nil { + return requiresArgs(target, root, seen) + } + return false + } + for _, m := range s.AllOf { + if requiresArgs(m, root, seen) { + return true + } + } + return false } // ResultTypeFor renders the return type expression for a tool. If outputSchema @@ -159,7 +193,20 @@ func (r *renderer) render(s *schema, indent string) string { return r.union(s.AnyOf, indent) } if len(s.AllOf) > 0 { - parts := make([]string, 0, len(s.AllOf)) + parts := make([]string, 0, len(s.AllOf)+1) + // Constraints written beside the allOf are part of the schema + // too: EffectiveSchema (#1986) keeps the upstream properties + // and required list at the root and puts the argument rules + // under allOf, so rendering only the members would drop the + // tool's own arguments from `mcpx types` and let generated + // clients reject object literals that use them. + if s.Type != nil || len(s.Properties) > 0 || len(s.Items) > 0 || len(s.PrefixItems) > 0 { + sibling := *s + sibling.AllOf = nil + if root := r.render(&sibling, indent); root != "unknown" && root != "" { + parts = append(parts, root) + } + } for _, sub := range s.AllOf { parts = append(parts, r.render(sub, indent)) } diff --git a/pkgs/mcpx/internal/config/argumentrules.go b/pkgs/mcpx/internal/config/argumentrules.go new file mode 100644 index 0000000000..7683865492 --- /dev/null +++ b/pkgs/mcpx/internal/config/argumentrules.go @@ -0,0 +1,785 @@ +package config + +import ( + "bytes" + "encoding/json" + "fmt" + "sort" + "strconv" + "strings" + + "github.com/dezren39/mcpx/internal/schemaval" +) + +// Argument rules (#1986, Phase 2 of the write-policy design #2126): +// per-tool, per-argument call constraints written as JSON Schema. Where +// tools/excludeTools decide by tool name alone -- a tool is callable +// with any arguments or not at all -- an argument rule decides by the +// call itself: this tool, but never on branch main; this tool, but only +// ever private repositories in one org. +// +// A rule set is the union of the pool block's argumentRules and the +// server's own, across every layered config file. Rules only ever +// tighten: a call is allowed only if its arguments validate against +// EVERY rule whose key matches the tool name (allOf semantics), and no +// layer can remove or loosen a rule a farther layer set. + +// ArgumentRule is one compiled argumentRules entry. +type ArgumentRule struct { + // Key is the tool pattern as written: an exact name, a glob, or a + // /regexp/, matched exactly as tools/excludeTools entries match. + Key string + // Origin names where the rule came from -- the config file, and + // whether it sat in the pool block or a server's mcpx block -- so a + // refusal can say whose rule refused the call. + Origin string + // Schema is the rule's JSON Schema, as written. + Schema json.RawMessage + + pattern ToolPatterns + compiled *schemaval.Schema +} + +// ArgumentRuleSet is a server's compiled argument rules, in a stable +// order (pool rules before server rules, keys sorted within each), so +// the first violation a call meets is deterministic. +type ArgumentRuleSet struct { + rules []ArgumentRule +} + +// ArgumentRuleSource is one uncompiled rule: where it was written, its +// pattern key, and its schema document. +type ArgumentRuleSource struct { + Key string + Origin string + Schema json.RawMessage +} + +// CompileArgumentRules compiles sources into a set, failing on the +// first bad entry: a rule whose pattern is not a valid tool pattern +// (including a non-RE2 /regexp/) or whose schema schemaval refuses is +// a load-time config error, never a rule that silently matches nothing +// or validates nothing. +func CompileArgumentRules(sources []ArgumentRuleSource) (*ArgumentRuleSet, error) { + set := &ArgumentRuleSet{} + for _, src := range sources { + pat, err := CompileToolPatterns([]string{src.Key}) + if err != nil { + return nil, fmt.Errorf("argumentRules %q (%s): %w", src.Key, src.Origin, err) + } + compiled, err := schemaval.Compile(src.Schema) + if err != nil { + return nil, fmt.Errorf("argumentRules %q (%s): %w", src.Key, src.Origin, err) + } + set.rules = append(set.rules, ArgumentRule{ + Key: src.Key, Origin: src.Origin, Schema: src.Schema, + pattern: pat, compiled: compiled, + }) + } + return set, nil +} + +// Empty reports whether the set has no rules. A nil set is empty. +func (s *ArgumentRuleSet) Empty() bool { return s == nil || len(s.rules) == 0 } + +// Rules returns the set's rules in evaluation order. +func (s *ArgumentRuleSet) Rules() []ArgumentRule { + if s == nil { + return nil + } + return append([]ArgumentRule(nil), s.rules...) +} + +// Matching returns the rules whose key matches tool, in set order. +func (s *ArgumentRuleSet) Matching(tool string) []ArgumentRule { + if s == nil { + return nil + } + var out []ArgumentRule + for _, r := range s.rules { + if r.pattern.Match(tool) { + out = append(out, r) + } + } + return out +} + +// ArgumentRuleViolation is one rule one call broke: the rule, the first +// validation problem (its path and the constraint it names), and the +// value the call actually sent at that path. +type ArgumentRuleViolation struct { + Rule ArgumentRule + Problem schemaval.Problem + Value string +} + +// Error renders the refusal in the HiddenTool style: the argument path, +// the sent value, the constraint it broke, and the rule's origin. +func (v *ArgumentRuleViolation) Error() string { + return fmt.Sprintf("argument %s = %s violates %s (argument rule %q from %s)", + v.Problem.Path, v.Value, v.Problem.Message, v.Rule.Key, v.Rule.Origin) +} + +// Check validates args against every rule matching tool and returns +// the first violation, or nil when the call satisfies all of them. +// args is the call's argument value as the daemon holds it (usually a +// map decoded from JSON); it is re-decoded the way schemaval expects, +// so integers past float64 precision keep their exact value. +func (s *ArgumentRuleSet) Check(tool string, args any) *ArgumentRuleViolation { + matching := s.Matching(tool) + if len(matching) == 0 { + return nil + } + raw, err := json.Marshal(args) + if err == nil && string(raw) == "null" { + // A caller can send "args": null (the daemon decodes it to a + // nil map). Object keywords -- required, properties -- do not + // reject JSON null, so the call would sail past rules written + // exactly like the documented examples and only become the + // empty object the client actually sends upstream afterwards. + // Judge the value that will be sent: no arguments at all is + // the empty object. + raw = []byte("{}") + } + if err != nil { + // Arguments that will not marshal cannot be validated; refuse + // rather than wave an unchecked call through. + return &ArgumentRuleViolation{ + Rule: matching[0], + Problem: schemaval.Problem{Path: "$", Message: "arguments could not be encoded for validation: " + err.Error()}, + Value: fmt.Sprintf("%v", args), + } + } + inst, err := schemaval.DecodeInstance(raw) + if err != nil { + return &ArgumentRuleViolation{ + Rule: matching[0], + Problem: schemaval.Problem{Path: "$", Message: "arguments could not be decoded for validation: " + err.Error()}, + Value: string(raw), + } + } + for _, r := range matching { + verr := r.compiled.Validate(inst) + if verr == nil { + continue + } + ve, ok := verr.(*schemaval.ValidationError) + if !ok || len(ve.Problems) == 0 { + return &ArgumentRuleViolation{ + Rule: r, + Problem: schemaval.Problem{Path: "$", Message: verr.Error()}, + Value: valueAt(raw, "$"), + } + } + p := ve.Problems[0] + return &ArgumentRuleViolation{Rule: r, Problem: p, Value: valueAt(raw, p.Path)} + } + return nil +} + +// EffectiveSchema returns the inputSchema a surface should advertise +// for tool: the upstream schema with every matching rule folded in, so +// what a caller reads is the constraint the call will actually be +// judged against. With no matching rules the upstream schema is +// returned unchanged, byte for byte. +// +// The upstream schema stays at the root, never nested under allOf: +// the MCP schemas require inputSchema.type to be "object" at the root +// itself, header annotations (x-mcp-header) are only reachable where +// the upstream schema put them -- composition keywords hide them from +// mcpheaders.ToolParams -- and the upstream document's own local +// references keep resolving against the root they were written for. +// Each rule joins as an allOf member that is a bare $ref into a +// namespaced copy of the rule kept in the root $defs (see +// scopedSchemaMember), so a rule's local references keep their own +// scope no matter what the root already defines. +func (s *ArgumentRuleSet) EffectiveSchema(tool string, upstream json.RawMessage) json.RawMessage { + matching := s.Matching(tool) + if len(matching) == 0 { + return upstream + } + root := map[string]any{} + if len(upstream) > 0 { + dec := json.NewDecoder(bytes.NewReader(upstream)) + dec.UseNumber() + var doc any + if err := dec.Decode(&doc); err != nil { + return upstream + } + obj, ok := doc.(map[string]any) + if !ok { + // A non-object upstream schema cannot carry the root + // this composition needs; advertise it unchanged + // rather than a shape that misstates it. + return upstream + } + root = obj + } + // The protocol's structural requirement, at the root where a + // validating client looks for it. + root["type"] = "object" + defs, _ := root["$defs"].(map[string]any) + if defs == nil { + defs = map[string]any{} + } + var allOf []any + if existing, ok := root["allOf"].([]any); ok { + allOf = existing + } + for i, r := range matching { + taken := make(map[string]bool, len(defs)) + for name := range defs { + taken[name] = true + } + member, scoped := scopedSchemaMemberTaken(r.Schema, fmt.Sprintf("argumentrule%d", i), taken) + for name, def := range scoped { + defs[name] = def + } + allOf = append(allOf, member) + } + // An upstream unevaluatedProperties at the root judges the + // properties its OWN adjacent applicators evaluated. Left at + // the root here, the rule members under allOf would count as + // evaluators too, and a property a rule mentions would stop + // being "unevaluated" for the upstream keyword -- the + // composition would loosen the upstream schema it advertises + // (Codex P2 on PR #2855, round 6). Move the keyword into a + // boundary member carrying copies of the upstream root's own + // property applicators: inside that member, adjacency is the + // upstream document's own again, so the keyword keeps exactly + // its standalone meaning while the root applies the upstream + // schema and the rules as before. + if up, present := root["unevaluatedProperties"]; present { + delete(root, "unevaluatedProperties") + boundary := map[string]any{"unevaluatedProperties": up} + for _, k := range []string{ + "properties", "patternProperties", "additionalProperties", + "dependentSchemas", + "allOf", "anyOf", "oneOf", "not", "if", "then", "else", + "$ref", "$dynamicRef", + } { + if v, ok := root[k]; ok { + boundary[k] = stripAnchorDefs(v) + } + } + allOf = append([]any{boundary}, allOf...) + } + if len(defs) > 0 { + root["$defs"] = defs + } + root["allOf"] = allOf + out, err := json.Marshal(root) + if err != nil { + return upstream + } + return out +} + +// scopedSchemaMember prepares one schema document for composition +// into another document's allOf. The document is copied into the host +// document's $defs under "$doc" and every local reference in +// the copy ("#", "#/$defs/...", any "#/..." pointer, via $ref or +// $dynamicRef) is rewritten to resolve within that copy, so the copy +// means exactly what the document meant standalone. The returned +// member is a bare $ref to the copy; a document with no local +// references and no anchor definitions needs no copy and is +// returned as itself with no defs. +func scopedSchemaMember(raw json.RawMessage, prefix string) (member any, defs map[string]any) { + return scopedSchemaMemberTaken(raw, prefix, nil) +} + +// scopedSchemaMemberTaken is scopedSchemaMember with a set of $defs +// names the host document already uses. The scoped copy must never +// take one of those names: overwriting an upstream definition would +// silently retarget the upstream schema's own references to the rule +// document, changing (and potentially loosening) constraints the +// upstream schema already carried. When the generated name is taken, +// allocate the next free suffixed name and rewrite references to it +// consistently. +func scopedSchemaMemberTaken(raw json.RawMessage, prefix string, taken map[string]bool) (member any, defs map[string]any) { + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.UseNumber() + var doc any + if err := dec.Decode(&doc); err != nil { + return json.RawMessage(raw), nil + } + anchors := anchorNames(doc) + if !hasLocalRef(doc) && len(anchors) == 0 { + return doc, nil + } + name := prefix + "$doc" + for n := 2; taken[name]; n++ { + name = fmt.Sprintf("%s$doc$%d", prefix, n) + } + // Anchors are document-scoped names, not pointers: two documents + // copied into one host resource can each define the same $anchor + // (two layered rules both anchoring "T"), and the host then has + // a duplicate anchor -- a compile error, or one rule's "#T" + // resolving to the other rule's target (Codex P2 on PR #2855, + // round 6). Namespace every anchor this document defines with + // the copy's own (collision-free) defs name, and rewrite the + // document's references to them to match. Anchor names cannot + // contain "$", so the defs name's "$"s become "_"s. + renamed := make(map[string]string, len(anchors)) + if len(anchors) > 0 { + base := strings.NewReplacer("$", "_").Replace(name) + "_" + names := make([]string, 0, len(anchors)) + for a := range anchors { + names = append(names, a) + } + sort.Strings(names) + for _, a := range names { + renamed[a] = base + a + } + } + scoped := rewriteLocalRefs(doc, "#/$defs/"+name, renamed) + return map[string]any{"$ref": "#/$defs/" + name}, map[string]any{name: scoped} +} + +// anchorNames returns the $anchor/$dynamicAnchor names a decoded +// schema document defines within its own resource. A map carrying +// its own $id -- the document root included -- is a separate +// resource whose anchors the host never sees (the ref rewrite +// returns such subtrees verbatim), so the walk does not descend +// into it; literal payloads are instance data, not definitions. +func anchorNames(doc any) map[string]bool { + out := map[string]bool{} + collectAnchorNames(doc, out) + return out +} + +func collectAnchorNames(v any, out map[string]bool) { + switch t := v.(type) { + case map[string]any: + if id, ok := t["$id"].(string); ok && id != "" { + return + } + for k, val := range t { + switch { + case k == "$anchor" || k == "$dynamicAnchor": + if s, ok := val.(string); ok && s != "" { + out[s] = true + } + case literalValueKey(k): + continue + case nameMapKey(k): + if m, ok := val.(map[string]any); ok { + for _, sub := range m { + collectAnchorNames(sub, out) + } + } + default: + collectAnchorNames(val, out) + } + } + case []any: + for _, e := range t { + collectAnchorNames(e, out) + } + } +} + +// stripAnchorDefs returns a copy of a decoded schema with every +// $anchor/$dynamicAnchor definition removed in schema position. +// EffectiveSchema's unevaluatedProperties boundary member duplicates +// the upstream root's applicators; the originals stay at the root, +// so a "#name" reference inside a copy still resolves to the +// identical definition there, while defining the same anchor twice +// in one resource would be a compile error. Subtrees under their +// own $id are separate resources and are returned verbatim, as in +// the ref traversals. +func stripAnchorDefs(v any) any { + switch t := v.(type) { + case map[string]any: + if id, ok := t["$id"].(string); ok && id != "" { + return v + } + out := make(map[string]any, len(t)) + for k, val := range t { + if k == "$anchor" || k == "$dynamicAnchor" { + continue + } + switch { + case literalValueKey(k): + out[k] = val + case nameMapKey(k): + if m, ok := val.(map[string]any); ok { + nm := make(map[string]any, len(m)) + for n, sub := range m { + nm[n] = stripAnchorDefs(sub) + } + out[k] = nm + } else { + out[k] = val + } + default: + out[k] = stripAnchorDefs(val) + } + } + return out + case []any: + out := make([]any, len(t)) + for i, e := range t { + out[i] = stripAnchorDefs(e) + } + return out + default: + return v + } +} + +// literalValueKey reports whether a schema keyword's value is +// instance data rather than a schema. A const/enum/default/examples +// payload is a literal argument value: a "$ref" key inside it names +// data, not a reference. Ref discovery and rewriting must not +// descend into these values -- merging layers would otherwise +// rewrite the very values a rule permits into ones it forbids, +// loosening (and corrupting) the farther rule instead of only +// tightening it. +func literalValueKey(k string) bool { + switch k { + case "const", "enum", "default", "examples", "example": + return true + } + return false +} + +// nameMapKey reports whether a schema keyword's value is a map of +// NAME -> schema (properties, $defs, ...). Keys in such a map are +// property or definition names, never keywords: an argument named +// "default" or a definition named "enum" is a name whose schema must +// be traversed like any other, not a literal payload to skip. +func nameMapKey(k string) bool { + switch k { + case "properties", "patternProperties", "$defs", "definitions", "dependentSchemas": + return true + } + return false +} + +// The two traversals below walk a decoded schema in SCHEMA position. +// They are structure-aware in three ways a blind walk cannot be: +// +// - literal payloads (literalValueKey) are instance data, not +// schemas, and are never descended into; +// - name maps (nameMapKey) flip the walk into name position, where +// every value is a schema whatever its key spells; +// - a subschema carrying its own $id is a separate resource: +// references inside it resolve against that resource, so the +// subtree is never re-based (rewrite returns it verbatim); +// - plain-name fragments ("#T") are not JSON Pointers: they name +// $anchors, and a scoped copy namespaces every anchor the +// document defines (see scopedSchemaMemberTaken), rewriting +// references to locally defined anchors to the namespaced +// name; a fragment naming no local anchor is left alone. + +// hasLocalRef reports whether a decoded schema document contains a +// $ref or $dynamicRef pointing inside itself. +func hasLocalRef(v any) bool { + switch t := v.(type) { + case map[string]any: + for k, val := range t { + if k == "$ref" || k == "$dynamicRef" { + if ref, ok := val.(string); ok && strings.HasPrefix(ref, "#") { + return true + } + } + switch { + case literalValueKey(k): + continue + case nameMapKey(k): + if hasLocalRefInNames(val) { + return true + } + default: + if hasLocalRef(val) { + return true + } + } + } + case []any: + for _, e := range t { + if hasLocalRef(e) { + return true + } + } + } + return false +} + +// hasLocalRefInNames walks a name -> schema map: every value is a +// schema, whatever its key spells. +func hasLocalRefInNames(v any) bool { + t, ok := v.(map[string]any) + if !ok { + return false + } + for _, sub := range t { + if hasLocalRef(sub) { + return true + } + } + return false +} + +// rewriteLocalRefs returns a copy of a decoded schema document with +// every local root-pointer $ref/$dynamicRef re-based at base: "#" +// becomes base itself and "#/..." becomes base + "/...". $anchor +// and $dynamicAnchor definitions are renamed per anchors (the +// document's own anchors mapped to their namespaced names), and +// plain-name fragment references to a renamed anchor are rewritten +// to match. The inside of any $id-carrying subschema is returned +// unchanged (see the traversal note above). +func rewriteLocalRefs(v any, base string, anchors map[string]string) any { + switch t := v.(type) { + case map[string]any: + if id, ok := t["$id"].(string); ok && id != "" { + return v // a separate resource: its refs are its own + } + out := make(map[string]any, len(t)) + for k, val := range t { + if k == "$anchor" || k == "$dynamicAnchor" { + if s, ok := val.(string); ok { + if renamed, ok := anchors[s]; ok { + out[k] = renamed + continue + } + } + } + if k == "$ref" || k == "$dynamicRef" { + if ref, ok := val.(string); ok { + switch { + case ref == "#" || strings.HasPrefix(ref, "#/"): + out[k] = base + strings.TrimPrefix(ref, "#") + continue + case strings.HasPrefix(ref, "#"): + if renamed, ok := anchors[ref[1:]]; ok { + out[k] = "#" + renamed + continue + } + } + } + } + switch { + case literalValueKey(k): + out[k] = val // literal instance data, not a schema + case nameMapKey(k): + out[k] = rewriteLocalRefsInNames(val, base, anchors) + default: + out[k] = rewriteLocalRefs(val, base, anchors) + } + } + return out + case []any: + out := make([]any, len(t)) + for i, e := range t { + out[i] = rewriteLocalRefs(e, base, anchors) + } + return out + default: + return v + } +} + +// rewriteLocalRefsInNames rewrites a name -> schema map: every value +// is a schema, whatever its key spells. +func rewriteLocalRefsInNames(v any, base string, anchors map[string]string) any { + t, ok := v.(map[string]any) + if !ok { + return v + } + out := make(map[string]any, len(t)) + for name, sub := range t { + out[name] = rewriteLocalRefs(sub, base, anchors) + } + return out +} + +// DeadRules returns the rules that match none of the known tool names: +// a rule keyed on a tool the server does not have constrains nothing, +// which is worth a warning where the catalog is known (at load and on +// catalog change) -- it is usually a typo. +func (s *ArgumentRuleSet) DeadRules(known []string) []ArgumentRule { + if s == nil { + return nil + } + var out []ArgumentRule + for _, r := range s.rules { + alive := false + for _, name := range known { + if r.pattern.Match(name) { + alive = true + break + } + } + if !alive { + out = append(out, r) + } + } + return out +} + +// argumentRuleSources flattens one argumentRules map into sources in +// key order, each stamped with the same origin. +func argumentRuleSources(m map[string]json.RawMessage, origin string) []ArgumentRuleSource { + if len(m) == 0 { + return nil + } + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + out := make([]ArgumentRuleSource, 0, len(keys)) + for _, k := range keys { + out = append(out, ArgumentRuleSource{Key: k, Origin: origin, Schema: m[k]}) + } + return out +} + +// mergeArgumentRules unions the argumentRules of two layered Extras: +// the nearer file's rules and the farther file's rules both apply. +// When both files key a rule on the same pattern the two schemas are +// combined with allOf rather than one replacing the other -- a nearer +// file can tighten a farther rule, never loosen it. +func mergeArgumentRules(near, far map[string]json.RawMessage) map[string]json.RawMessage { + if len(far) == 0 { + return near + } + if len(near) == 0 { + return far + } + out := make(map[string]json.RawMessage, len(near)+len(far)) + for k, v := range far { + out[k] = v + } + for k, v := range near { + if fv, dup := out[k]; dup { + if combined := composeSchemas(fv, v); combined != nil { + out[k] = combined + continue + } + } + out[k] = v + } + return out +} + +// composeSchemas combines two layered schemas written for the same +// rule key into one document that means both (allOf), keeping each +// side's local references in their own scope via scopedSchemaMember: +// nesting the two documents under allOf without that moves their +// $defs but leaves "#/$defs/..." pointing at the combined root, and a +// rule that compiled standalone fails to compile merged. +func composeSchemas(far, near json.RawMessage) json.RawMessage { + farMember, farDefs := scopedSchemaMember(far, "far") + nearMember, nearDefs := scopedSchemaMember(near, "near") + root := map[string]any{"allOf": []any{farMember, nearMember}} + if len(farDefs)+len(nearDefs) > 0 { + defs := make(map[string]any, len(farDefs)+len(nearDefs)) + for n, d := range farDefs { + defs[n] = d + } + for n, d := range nearDefs { + defs[n] = d + } + root["$defs"] = defs + } + out, err := json.Marshal(root) + if err != nil { + return nil + } + return out +} + +// valueAt renders the value at a schemaval problem path ("$.a.b[0]") +// in the raw instance document, compactly, for a refusal message. A +// path that does not resolve (a missing required property, say) +// renders as "nothing". +func valueAt(raw json.RawMessage, path string) string { + if path == "" || path == "$" { + return compactJSON(raw) + } + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.UseNumber() + var doc any + if err := dec.Decode(&doc); err != nil { + return compactJSON(raw) + } + cur := doc + rest := strings.TrimPrefix(path, "$") + for rest != "" { + switch { + case strings.HasPrefix(rest, "."): + rest = rest[1:] + end := strings.IndexAny(rest, ".[") + var key string + if end < 0 { + key, rest = rest, "" + } else { + key, rest = rest[:end], rest[end:] + } + m, ok := cur.(map[string]any) + if !ok { + return "nothing" + } + cur, ok = m[key] + if !ok { + return "nothing" + } + case strings.HasPrefix(rest, "["): + end := strings.IndexByte(rest, ']') + if end < 0 { + return "nothing" + } + tok := rest[1:end] + rest = rest[end+1:] + if strings.HasPrefix(tok, "\"") { + var key string + if err := json.Unmarshal([]byte(tok), &key); err != nil { + return "nothing" + } + m, ok := cur.(map[string]any) + if !ok { + return "nothing" + } + cur, ok = m[key] + if !ok { + return "nothing" + } + continue + } + n, err := strconv.Atoi(tok) + if err != nil { + return "nothing" + } + arr, ok := cur.([]any) + if !ok || n < 0 || n >= len(arr) { + return "nothing" + } + cur = arr[n] + default: + return "nothing" + } + } + b, err := json.Marshal(cur) + if err != nil { + return fmt.Sprintf("%v", cur) + } + return compactJSON(b) +} + +// compactJSON renders raw on one line, truncated so a refusal message +// stays a message even when the value is a document. +func compactJSON(raw json.RawMessage) string { + var buf bytes.Buffer + if err := json.Compact(&buf, raw); err != nil { + return string(raw) + } + s := buf.String() + const max = 160 + if len(s) > max { + return s[:max] + "..." + } + return s +} diff --git a/pkgs/mcpx/internal/config/argumentrules_test.go b/pkgs/mcpx/internal/config/argumentrules_test.go new file mode 100644 index 0000000000..e3c2461d22 --- /dev/null +++ b/pkgs/mcpx/internal/config/argumentrules_test.go @@ -0,0 +1,708 @@ +package config + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/dezren39/mcpx/internal/schemaval" +) + +// The four worked examples from #1986, as one server's rule set. +func exampleRules(t *testing.T) *ArgumentRuleSet { + t.Helper() + set, err := CompileArgumentRules([]ArgumentRuleSource{ + {Key: "create_repository", Origin: "test", Schema: json.RawMessage(`{ + "required": ["private", "organization"], + "properties": { + "private": {"const": true}, + "organization": {"pattern": "^(my-org|my-org-sandbox)$"} + }}`)}, + {Key: "/^(push_files|create_or_update_file|delete_file)$/", Origin: "test", Schema: json.RawMessage(`{ + "required": ["branch"], + "properties": {"branch": {"not": {"enum": ["main", "master"]}}}}`)}, + {Key: "*", Origin: "test", Schema: json.RawMessage(`{ + "properties": {"owner": {"pattern": "^(my-org|my-user)$"}}}`)}, + {Key: "execute_datadog_workflow", Origin: "test", Schema: json.RawMessage(`{ + "required": ["workflow_id"], + "properties": {"workflow_id": {"enum": ["id-1", "id-2"]}}}`)}, + }) + if err != nil { + t.Fatalf("CompileArgumentRules: %v", err) + } + return set +} + +func TestArgumentRulesWorkedExamples(t *testing.T) { + set := exampleRules(t) + + // create_repository: private in a known org passes; public, or a + // foreign org, or no organization at all is refused. + if v := set.Check("create_repository", map[string]any{"private": true, "organization": "my-org"}); v != nil { + t.Errorf("conforming create_repository refused: %v", v) + } + for name, args := range map[string]map[string]any{ + "public": {"private": false, "organization": "my-org"}, + "foreign org": {"private": true, "organization": "evil-corp"}, + "no org": {"private": true}, + } { + v := set.Check("create_repository", args) + if v == nil { + t.Errorf("create_repository %s: allowed, want refusal", name) + continue + } + if v.Rule.Key != "create_repository" { + t.Errorf("create_repository %s: refused by rule %q, want create_repository", name, v.Rule.Key) + } + } + + // Branch rule, keyed by regexp across three tools: main/master + // refused, a feature branch allowed, on every matched tool. + for _, tool := range []string{"push_files", "create_or_update_file", "delete_file"} { + if v := set.Check(tool, map[string]any{"branch": "main"}); v == nil { + t.Errorf("%s to main: allowed, want refusal", tool) + } else if !strings.Contains(v.Error(), "$.branch") || !strings.Contains(v.Error(), `"main"`) { + t.Errorf("%s refusal should name path and value, got: %v", tool, v) + } + if v := set.Check(tool, map[string]any{"branch": "feat/x"}); v != nil { + t.Errorf("%s to feat/x refused: %v", tool, v) + } + } + // The regexp does not reach other tools. + if v := set.Check("get_file_contents", map[string]any{"branch": "main"}); v != nil { + t.Errorf("unmatched tool refused by branch rule: %v", v) + } + + // Owner rule, keyed "*" per-argument: applies only when owner is + // present, to any tool that carries it. + if v := set.Check("list_repos", map[string]any{"owner": "someone-else"}); v == nil { + t.Error("foreign owner allowed, want refusal") + } + if v := set.Check("list_repos", map[string]any{"owner": "my-user"}); v != nil { + t.Errorf("own owner refused: %v", v) + } + if v := set.Check("list_repos", map[string]any{"page": 1}); v != nil { + t.Errorf("tool without owner refused: %v", v) + } + + // Workflow ids: only the reviewed enum. + if v := set.Check("execute_datadog_workflow", map[string]any{"workflow_id": "id-9"}); v == nil { + t.Error("unreviewed workflow id allowed, want refusal") + } + if v := set.Check("execute_datadog_workflow", map[string]any{"workflow_id": "id-2"}); v != nil { + t.Errorf("reviewed workflow id refused: %v", v) + } +} + +func TestArgumentRuleViolationNamesOrigin(t *testing.T) { + set := exampleRules(t) + v := set.Check("create_repository", map[string]any{"private": false, "organization": "my-org"}) + if v == nil { + t.Fatal("want violation") + } + msg := v.Error() + for _, want := range []string{"$.private", "false", "create_repository", "test"} { + if !strings.Contains(msg, want) { + t.Errorf("violation %q does not name %q", msg, want) + } + } +} + +func TestArgumentRulesLoadTimeErrors(t *testing.T) { + // A bad schema is a load-time error. + if _, err := CompileArgumentRules([]ArgumentRuleSource{ + {Key: "x", Origin: "test", Schema: json.RawMessage(`{"properties": {"a": {"type": "nonesuch"}}}`)}, + }); err == nil { + t.Error("invalid schema compiled, want load-time error") + } + // A non-RE2 tool pattern key is a load-time error. + if _, err := CompileArgumentRules([]ArgumentRuleSource{ + {Key: "/(?=delete)purge/", Origin: "test", Schema: json.RawMessage(`{}`)}, + }); err == nil { + t.Error("lookahead tool pattern compiled, want load-time error") + } + // A schema pattern outside the validator's dialect (lookahead) is + // a load-time error, not a rule that silently never matches. + if _, err := CompileArgumentRules([]ArgumentRuleSource{ + {Key: "x", Origin: "test", Schema: json.RawMessage(`{"properties": {"a": {"pattern": "^(?=x)y"}}}`)}, + }); err == nil { + t.Error("lookahead schema pattern compiled, want load-time error") + } +} + +func TestArgumentRulesComposeAcrossPoolServerAndLayers(t *testing.T) { + // Pool says owner must be my-org; the server adds branch-not-main. + // Both apply to one call (allOf composition through Resolve). + cfg := &Config{ + Path: "base.json", + Pool: Extras{ArgumentRules: map[string]json.RawMessage{ + "*": json.RawMessage(`{"properties": {"owner": {"pattern": "^my-org$"}}}`), + }}, + MCPServers: map[string]*Server{ + "gh": {Command: "demo", Mcpx: &Extras{ArgumentRules: map[string]json.RawMessage{ + "push_files": json.RawMessage(`{"properties": {"branch": {"not": {"enum": ["main"]}}}}`), + }}}, + }, + } + r, err := cfg.Resolve("gh") + if err != nil { + t.Fatalf("Resolve: %v", err) + } + if v := r.ArgumentRules.Check("push_files", map[string]any{"owner": "other", "branch": "feat"}); v == nil { + t.Error("pool rule not applied through Resolve") + } + if v := r.ArgumentRules.Check("push_files", map[string]any{"owner": "my-org", "branch": "main"}); v == nil { + t.Error("server rule not applied through Resolve") + } + if v := r.ArgumentRules.Check("push_files", map[string]any{"owner": "my-org", "branch": "feat"}); v != nil { + t.Errorf("conforming call refused: %v", v) + } + + // Layered files: the far file's rule survives the merge, and a key + // both files use composes instead of the near file loosening it. + near := Extras{ArgumentRules: map[string]json.RawMessage{ + "*": json.RawMessage(`{"properties": {"branch": {"not": {"enum": ["main"]}}}}`), + }} + far := Extras{ArgumentRules: map[string]json.RawMessage{ + "*": json.RawMessage(`{"properties": {"owner": {"pattern": "^my-org$"}}}`), + "deploy": json.RawMessage(`{"properties": {"env": {"const": "staging"}}}`), + }} + merged := mergeExtras(near, far) + set, err := CompileArgumentRules(argumentRuleSources(merged.ArgumentRules, "test")) + if err != nil { + t.Fatalf("compile merged: %v", err) + } + if v := set.Check("anything", map[string]any{"owner": "other"}); v == nil { + t.Error("far file's owner rule lost in layered merge") + } + if v := set.Check("anything", map[string]any{"branch": "main"}); v == nil { + t.Error("near file's branch rule lost in layered merge") + } + if v := set.Check("deploy", map[string]any{"env": "prod"}); v == nil { + t.Error("far file's deploy rule lost in layered merge") + } +} + +func TestArgumentRulesDeadAndEffectiveSchema(t *testing.T) { + set := exampleRules(t) + dead := set.DeadRules([]string{"create_repository", "push_files"}) + // "*" and the branch regexp are alive; the datadog rule is dead + // against this catalog. + found := map[string]bool{} + for _, r := range dead { + found[r.Key] = true + } + if !found["execute_datadog_workflow"] { + t.Errorf("dead rules = %v, want execute_datadog_workflow among them", dead) + } + if found["*"] || found["create_repository"] { + t.Errorf("live rules reported dead: %v", dead) + } + + upstream := json.RawMessage(`{"type": "object", "properties": {"private": {"type": "boolean"}}}`) + eff := set.EffectiveSchema("create_repository", upstream) + // The upstream schema stays at the root -- the MCP schemas + // require inputSchema.type == "object" at the root itself, not + // inside an allOf member -- and the matching rules (the + // create_repository rule + the "*" rule) join as allOf members. + var doc struct { + Type string `json:"type"` + Properties map[string]json.RawMessage `json:"properties"` + AllOf []json.RawMessage `json:"allOf"` + } + if err := json.Unmarshal(eff, &doc); err != nil { + t.Fatalf("effective schema does not parse: %v", err) + } + if doc.Type != "object" { + t.Errorf("effective schema root type = %q, want object: %s", doc.Type, eff) + } + if _, ok := doc.Properties["private"]; !ok { + t.Errorf("upstream properties lost from the root: %s", eff) + } + if len(doc.AllOf) != 2 { + t.Fatalf("effective schema = %s, want allOf of 2 rules", eff) + } + // A tool only the "*" rule matches gets just that one member. + got := set.EffectiveSchema("unrelated_tool_xyz", upstream) + var d2 struct { + AllOf []json.RawMessage `json:"allOf"` + } + if err := json.Unmarshal(got, &d2); err != nil || len(d2.AllOf) != 1 { + t.Fatalf("effective schema for other tool = %s, want allOf of 1 (* rule)", got) + } +} + +// A call with no arguments at all ("args": null on the wire, a nil +// map in the daemon) is judged as the empty object the client will +// actually send upstream -- never as JSON null, which object keywords +// like required do not reject. +func TestArgumentRuleNilArgsJudgedAsEmptyObject(t *testing.T) { + set := exampleRules(t) + if v := set.Check("create_repository", nil); v == nil { + t.Error("nil args allowed past a rule requiring private+organization; want refusal") + } + // A rule that only constrains a present property still passes an + // argument-less call. + if v := set.Check("list_repos", nil); v != nil { + t.Errorf("nil args refused by a properties-only rule: %v", v) + } +} + +// The advertised schema keeps the upstream document at the root -- +// its type: object declaration and its x-mcp-header property +// annotations stay where clients look for them -- and a rule whose +// schema references its own $defs still resolves after composition. +func TestEffectiveSchemaPreservesRootAndRuleRefs(t *testing.T) { + set, err := CompileArgumentRules([]ArgumentRuleSource{ + {Key: "read_file", Origin: "test", Schema: json.RawMessage(`{ + "$defs": {"nonEmpty": {"type": "string", "minLength": 1}}, + "properties": {"path": {"$ref": "#/$defs/nonEmpty"}}}`)}, + }) + if err != nil { + t.Fatalf("CompileArgumentRules: %v", err) + } + upstream := json.RawMessage(`{"type": "object", "properties": {"path": {"type": "string", "x-mcp-header": "X-Path"}}}`) + eff := set.EffectiveSchema("read_file", upstream) + var root map[string]any + if err := json.Unmarshal(eff, &root); err != nil { + t.Fatalf("effective schema does not parse: %v", err) + } + if root["type"] != "object" { + t.Errorf("root type = %v, want object: %s", root["type"], eff) + } + props, _ := root["properties"].(map[string]any) + path, _ := props["path"].(map[string]any) + if path["x-mcp-header"] != "X-Path" { + t.Errorf("x-mcp-header annotation not reachable at the root properties: %s", eff) + } + // The composed document must itself compile and judge: the + // rule's $defs reference survived composition. + compiled, err := schemaval.Compile(eff) + if err != nil { + t.Fatalf("effective schema does not compile: %v (%s)", err, eff) + } + inst, err := schemaval.DecodeInstance(json.RawMessage(`{"path": ""}`)) + if err != nil { + t.Fatal(err) + } + if err := compiled.Validate(inst); err == nil { + t.Error("empty path validated against the composed schema; want the rule's minLength to bite") + } + inst, err = schemaval.DecodeInstance(json.RawMessage(`{"path": "x"}`)) + if err != nil { + t.Fatal(err) + } + if err := compiled.Validate(inst); err != nil { + t.Errorf("valid path refused by the composed schema: %v", err) + } +} + +// Two layers keying a rule on the same pattern compose with allOf; +// when both schemas carry local $defs references the merged rule +// still compiles and both sides still bite. +func TestMergedLayerRulesWithLocalRefsCompile(t *testing.T) { + near := Extras{ArgumentRules: map[string]json.RawMessage{ + "*": json.RawMessage(`{"$defs": {"ok": {"type": "string", "pattern": "^near-"}}, "properties": {"branch": {"$ref": "#/$defs/ok"}}}`), + }} + far := Extras{ArgumentRules: map[string]json.RawMessage{ + "*": json.RawMessage(`{"$defs": {"ok": {"type": "string", "pattern": "^far-"}}, "properties": {"owner": {"$ref": "#/$defs/ok"}}}`), + }} + merged := mergeExtras(near, far) + set, err := CompileArgumentRules(argumentRuleSources(merged.ArgumentRules, "test")) + if err != nil { + t.Fatalf("merged rules with local refs do not compile: %v", err) + } + // Branch can satisfy at most one side's pattern prefix per value; + // use values that isolate each side's bite via the other property. + if v := set.Check("anything", map[string]any{"branch": "zzz", "owner": "far-org"}); v == nil { + t.Error("near layer's branch rule lost in the merge") + } + if v := set.Check("anything", map[string]any{"branch": "near-x", "owner": "zzz"}); v == nil { + t.Error("far layer's owner rule lost in the merge") + } + if v := set.Check("anything", map[string]any{"branch": "near-x", "owner": "far-org"}); v != nil { + t.Errorf("call satisfying both layers refused: %v", v) + } +} + +// Literal instance data is not a schema: a rule whose const/enum +// payload is an object carrying a "$ref" key permits THAT object. +// Layered merging must not rewrite the literal while re-basing real +// schema references, or the merged rule would forbid the permitted +// value and permit a rewritten one nobody wrote. +func TestMergedRulesPreserveLiteralRefValues(t *testing.T) { + far := Extras{ArgumentRules: map[string]json.RawMessage{ + "*": json.RawMessage(`{"properties": { + "payload": {"const": {"$ref": "#/ok"}}, + "mode": {"enum": [{"$ref": "#/ok"}, "plain"]} + }}`), + }} + near := Extras{ArgumentRules: map[string]json.RawMessage{ + "*": json.RawMessage(`{}`), + }} + merged := mergeExtras(near, far) + set, err := CompileArgumentRules(argumentRuleSources(merged.ArgumentRules, "test")) + if err != nil { + t.Fatalf("CompileArgumentRules: %v", err) + } + good := map[string]any{ + "payload": map[string]any{"$ref": "#/ok"}, + "mode": map[string]any{"$ref": "#/ok"}, + } + if v := set.Check("anything", good); v != nil { + t.Errorf("call carrying the literal values the rule permits refused after merge: %v", v) + } + rewritten := map[string]any{ + "payload": map[string]any{"$ref": "#/$defs/far$doc/ok"}, + "mode": "plain", + } + if v := set.Check("anything", rewritten); v == nil { + t.Error("call carrying the rewritten literal the merge invented was permitted; the literal was treated as a schema reference") + } +} + +// Property and definition NAMES are not keywords: a rule constraining +// an argument named "default" (or "enum") writes that name as a key of +// the properties map, and its value is a schema like any other. The +// ref traversal must walk it in name position, or the schema's $ref +// is left pointing at the combined root and loading fails. +func TestMergedRulesTraversePropertyNamesNotKeywords(t *testing.T) { + far := Extras{ArgumentRules: map[string]json.RawMessage{ + "*": json.RawMessage(`{ + "$defs": {"T": {"type": "string", "minLength": 2}}, + "properties": { + "default": {"$ref": "#/$defs/T"}, + "enum": {"$ref": "#/$defs/T"} + }}`), + }} + near := Extras{ArgumentRules: map[string]json.RawMessage{ + "*": json.RawMessage(`{}`), + }} + merged := mergeExtras(near, far) + set, err := CompileArgumentRules(argumentRuleSources(merged.ArgumentRules, "test")) + if err != nil { + t.Fatalf("merged rule with arguments named default/enum does not compile: %v", err) + } + if v := set.Check("anything", map[string]any{"default": "ok", "enum": "ok"}); v != nil { + t.Errorf("conforming call refused after merge: %v", v) + } + if v := set.Check("anything", map[string]any{"default": "x"}); v == nil { + t.Error("rule behind the argument named default lost its bite in the merge") + } + if v := set.Check("anything", map[string]any{"enum": 42}); v == nil { + t.Error("rule behind the argument named enum lost its bite in the merge") + } +} + +// A rule carrying its own absolute $id is a separate resource: its +// internal references resolve against that resource, so composition +// must copy the document without re-basing the references inside it. +func TestMergedRulesRespectSchemaIDBoundaries(t *testing.T) { + far := Extras{ArgumentRules: map[string]json.RawMessage{ + "*": json.RawMessage(`{ + "$id": "https://example.com/rules/arg.json", + "$defs": {"T": {"type": "string", "minLength": 2}}, + "properties": {"name": {"$ref": "#/$defs/T"}}}`), + }} + near := Extras{ArgumentRules: map[string]json.RawMessage{ + "*": json.RawMessage(`{"properties": {"other": {"type": "boolean"}}}`), + }} + merged := mergeExtras(near, far) + set, err := CompileArgumentRules(argumentRuleSources(merged.ArgumentRules, "test")) + if err != nil { + t.Fatalf("merged rule with its own $id does not compile: %v", err) + } + if v := set.Check("anything", map[string]any{"name": "ok", "other": true}); v != nil { + t.Errorf("conforming call refused after merge: %v", v) + } + if v := set.Check("anything", map[string]any{"name": "x"}); v == nil { + t.Error("$id rule's referenced constraint lost its bite in the merge") + } +} + +// A plain-name fragment ("#T") references an $anchor, not a JSON +// Pointer into the document root: prefixing it produces a pointer to +// a nonexistent definition. Composition must leave anchor references +// (and their targets) alone. +func TestMergedRulesPreserveAnchorReferences(t *testing.T) { + far := Extras{ArgumentRules: map[string]json.RawMessage{ + "*": json.RawMessage(`{ + "$defs": {"T": {"$anchor": "T", "type": "string", "minLength": 2}}, + "properties": {"name": {"$ref": "#T"}}}`), + }} + near := Extras{ArgumentRules: map[string]json.RawMessage{ + "*": json.RawMessage(`{}`), + }} + merged := mergeExtras(near, far) + set, err := CompileArgumentRules(argumentRuleSources(merged.ArgumentRules, "test")) + if err != nil { + t.Fatalf("merged rule with an anchor reference does not compile: %v", err) + } + if v := set.Check("anything", map[string]any{"name": "ok"}); v != nil { + t.Errorf("conforming call refused after merge: %v", v) + } + if v := set.Check("anything", map[string]any{"name": "x"}); v == nil { + t.Error("anchor-referenced constraint lost its bite in the merge") + } +} + +// A nearer config file that redefines a server without restating its +// argumentRules must not drop the farther file's server-level rules: +// rules only tighten, across layers as within one file. +func TestServerArgumentRulesSurviveLayeredMerge(t *testing.T) { + far := &Config{ + MCPServers: map[string]*Server{ + "gh": {Command: "demo", Mcpx: &Extras{ArgumentRules: map[string]json.RawMessage{ + "push_files": json.RawMessage(`{"properties": {"branch": {"not": {"enum": ["main"]}}}}`), + }}}, + }, + Origin: map[string]string{}, + } + near := &Config{ + MCPServers: map[string]*Server{ + "gh": {Command: "demo-near"}, + }, + Origin: map[string]string{}, + } + mergeInto(near, far, "far.json") + got := near.MCPServers["gh"] + if got.Command != "demo-near" { + t.Fatalf("nearer server definition should win, got command %q", got.Command) + } + if got.Mcpx == nil || len(got.Mcpx.ArgumentRules) != 1 { + t.Fatalf("farther server's argumentRules lost in mergeInto: %+v", got.Mcpx) + } + set, err := CompileArgumentRules(argumentRuleSources(got.Mcpx.ArgumentRules, "test")) + if err != nil { + t.Fatalf("compile merged server rules: %v", err) + } + if v := set.Check("push_files", map[string]any{"branch": "main"}); v == nil { + t.Error("inherited server rule does not bite after the layered merge") + } +} + +// A rule's scoped copy must never overwrite an upstream $defs entry +// that happens to carry the generated name: upstream references to +// that entry would silently resolve to the rule document instead of +// their original target (Codex P2 on PR #2855, round 5). +func TestEffectiveSchemaDoesNotOverwriteUpstreamDefs(t *testing.T) { + set, err := CompileArgumentRules([]ArgumentRuleSource{ + {Key: "create_repository", Origin: "test", Schema: json.RawMessage(`{ + "$defs": {"s": {"type": "string", "pattern": "^ok-"}}, + "properties": {"name": {"$ref": "#/$defs/s"}}}`)}, + }) + if err != nil { + t.Fatalf("CompileArgumentRules: %v", err) + } + upstream := json.RawMessage(`{"type": "object", + "$defs": {"argumentrule0$doc": {"type": "string"}}, + "properties": { + "path": {"$ref": "#/$defs/argumentrule0$doc"}, + "name": {"type": "string"}}}`) + eff := set.EffectiveSchema("create_repository", upstream) + var root map[string]any + if err := json.Unmarshal(eff, &root); err != nil { + t.Fatalf("effective schema does not parse: %v", err) + } + defs, _ := root["$defs"].(map[string]any) + up, _ := defs["argumentrule0$doc"].(map[string]any) + if up["type"] != "string" || len(up) != 1 { + t.Fatalf("upstream $defs entry overwritten by rule composition: %s", eff) + } + if len(defs) != 2 { + t.Fatalf("rule copy missing from $defs: %s", eff) + } + compiled, err := schemaval.Compile(eff) + if err != nil { + t.Fatalf("effective schema does not compile: %v (%s)", err, eff) + } + for inst, wantErr := range map[string]bool{ + `{"path": "p", "name": "ok-1"}`: false, + `{"path": {"x": 1}, "name": "ok-1"}`: true, + `{"path": "p", "name": "nope"}`: true, + } { + dec, err := schemaval.DecodeInstance(json.RawMessage(inst)) + if err != nil { + t.Fatal(err) + } + if gotErr := compiled.Validate(dec) != nil; gotErr != wantErr { + t.Errorf("validate %s: error = %v, want %v (schema %s)", inst, gotErr, wantErr, eff) + } + } +} + +// Two layered rules may each define the same $anchor name for +// different targets: anchors are document-scoped, so copying both +// documents into one composed root without isolating their anchors +// collides them -- a duplicate-anchor compile error, or one rule's +// "#T" resolving to the other rule's target (Codex P2 on PR #2855, +// round 6). Composition must namespace each document's anchors. +func TestMergedRulesAnchorCollisionAcrossLayers(t *testing.T) { + far := Extras{ArgumentRules: map[string]json.RawMessage{ + "*": json.RawMessage(`{ + "$defs": {"T": {"$anchor": "T", "type": "string"}}, + "properties": {"a": {"$ref": "#T"}}}`), + }} + near := Extras{ArgumentRules: map[string]json.RawMessage{ + "*": json.RawMessage(`{ + "$defs": {"T": {"$anchor": "T", "type": "integer"}}, + "properties": {"b": {"$ref": "#T"}}}`), + }} + merged := mergeExtras(near, far) + set, err := CompileArgumentRules(argumentRuleSources(merged.ArgumentRules, "test")) + if err != nil { + t.Fatalf("merged rules with colliding anchors do not compile: %v", err) + } + if v := set.Check("anything", map[string]any{"a": "yes", "b": 1}); v != nil { + t.Errorf("conforming call refused after merge: %v", v) + } + if v := set.Check("anything", map[string]any{"a": 1, "b": 1}); v == nil { + t.Error("far rule's string anchor lost its bite in the merge") + } + if v := set.Check("anything", map[string]any{"a": "yes", "b": "x"}); v == nil { + t.Error("near rule's integer anchor lost its bite in the merge") + } +} + +// A $dynamicRef is a local reference exactly like $ref for scoping +// purposes: a rule whose only local reference is dynamic must still +// be scoped, or the reference re-bases onto the composed root and +// its target definition is lost (Codex P2 on PR #2855, round 6). +func TestMergedRulesDynamicRefScoped(t *testing.T) { + far := Extras{ArgumentRules: map[string]json.RawMessage{ + "*": json.RawMessage(`{ + "$defs": {"T": {"type": "string", "minLength": 2}}, + "properties": {"name": {"$dynamicRef": "#/$defs/T"}}}`), + }} + near := Extras{ArgumentRules: map[string]json.RawMessage{ + "*": json.RawMessage(`{}`), + }} + merged := mergeExtras(near, far) + set, err := CompileArgumentRules(argumentRuleSources(merged.ArgumentRules, "test")) + if err != nil { + t.Fatalf("merged rule with a $dynamicRef does not compile: %v", err) + } + if v := set.Check("anything", map[string]any{"name": "ok"}); v != nil { + t.Errorf("conforming call refused after merge: %v", v) + } + if v := set.Check("anything", map[string]any{"name": "x"}); v == nil { + t.Error("$dynamicRef-referenced constraint lost its bite in the merge") + } +} + +// Two rules matching the same tool may define the same anchor name +// for different targets; the advertised effective schema composes +// both into one root, where their anchors must not collide. +func TestEffectiveSchemaAnchorCollisionAcrossRules(t *testing.T) { + set, err := CompileArgumentRules([]ArgumentRuleSource{ + {Key: "*", Origin: "test", Schema: json.RawMessage(`{ + "$defs": {"T": {"$anchor": "T", "type": "string", "minLength": 2}}, + "properties": {"a": {"$ref": "#T"}}}`)}, + {Key: "do_thing", Origin: "test", Schema: json.RawMessage(`{ + "$defs": {"T": {"$anchor": "T", "type": "integer"}}, + "properties": {"b": {"$ref": "#T"}}}`)}, + }) + if err != nil { + t.Fatalf("CompileArgumentRules: %v", err) + } + upstream := json.RawMessage(`{"type": "object", "properties": {"a": {"type": "string"}, "b": {"type": "integer"}}}`) + eff := set.EffectiveSchema("do_thing", upstream) + compiled, err := schemaval.Compile(eff) + if err != nil { + t.Fatalf("effective schema with colliding rule anchors does not compile: %v (%s)", err, eff) + } + for inst, wantErr := range map[string]bool{ + `{"a": "ok", "b": 1}`: false, + `{"a": "x", "b": 1}`: true, + `{"a": "ok", "b": "s"}`: true, + } { + dec, err := schemaval.DecodeInstance(json.RawMessage(inst)) + if err != nil { + t.Fatal(err) + } + if gotErr := compiled.Validate(dec) != nil; gotErr != wantErr { + t.Errorf("validate %s: error = %v, want %v (schema %s)", inst, gotErr, wantErr, eff) + } + } +} + +// An upstream unevaluatedProperties: false forbids every property +// the upstream schema itself does not evaluate. Folding a rule into +// the same root under allOf must not make the properties the rule +// mentions count as evaluated for that keyword -- the advertised +// schema would accept arguments the upstream schema forbids +// (Codex P2 on PR #2855, round 6). +func TestEffectiveSchemaPreservesUnevaluatedProperties(t *testing.T) { + set, err := CompileArgumentRules([]ArgumentRuleSource{ + {Key: "*", Origin: "test", Schema: json.RawMessage(`{"properties": {"private": {"const": true}}}`)}, + }) + if err != nil { + t.Fatalf("CompileArgumentRules: %v", err) + } + upstream := json.RawMessage(`{"type": "object", + "properties": {"path": {"type": "string"}}, + "unevaluatedProperties": false}`) + eff := set.EffectiveSchema("anything", upstream) + var root map[string]any + if err := json.Unmarshal(eff, &root); err != nil { + t.Fatalf("effective schema does not parse: %v", err) + } + if _, ok := root["properties"]; !ok { + t.Errorf("upstream properties no longer advertised at the root: %s", eff) + } + compiled, err := schemaval.Compile(eff) + if err != nil { + t.Fatalf("effective schema does not compile: %v (%s)", err, eff) + } + for inst, wantErr := range map[string]bool{ + `{"path": "p"}`: false, + `{"path": "p", "private": true}`: true, + `{"path": "p", "other": 1}`: true, + `{"path": 1}`: true, + } { + dec, err := schemaval.DecodeInstance(json.RawMessage(inst)) + if err != nil { + t.Fatal(err) + } + if gotErr := compiled.Validate(dec) != nil; gotErr != wantErr { + t.Errorf("validate %s: error = %v, want %v (schema %s)", inst, gotErr, wantErr, eff) + } + } +} + +// dependentSchemas subschemas are upstream applicators too: the +// properties they evaluate count for the upstream root's +// unevaluatedProperties, so the boundary member must carry them or +// the advertised schema forbids arguments the upstream schema +// accepts (Codex P2 on PR #2855, round 7). +func TestEffectiveSchemaUnevaluatedDependentSchemas(t *testing.T) { + set, err := CompileArgumentRules([]ArgumentRuleSource{ + {Key: "*", Origin: "test", Schema: json.RawMessage(`{}`)}, + }) + if err != nil { + t.Fatalf("CompileArgumentRules: %v", err) + } + upstream := json.RawMessage(`{"type": "object", + "properties": {"trigger": {}}, + "dependentSchemas": {"trigger": {"properties": {"other": {}}}}, + "unevaluatedProperties": false}`) + eff := set.EffectiveSchema("anything", upstream) + compiled, err := schemaval.Compile(eff) + if err != nil { + t.Fatalf("effective schema does not compile: %v (%s)", err, eff) + } + for inst, wantErr := range map[string]bool{ + `{"trigger": true, "other": "ok"}`: false, + `{"trigger": true}`: false, + `{"trigger": true, "other": "ok", "x": 1}`: true, + `{"other": "ok"}`: true, + } { + dec, err := schemaval.DecodeInstance(json.RawMessage(inst)) + if err != nil { + t.Fatal(err) + } + if gotErr := compiled.Validate(dec) != nil; gotErr != wantErr { + t.Errorf("validate %s: error = %v, want %v (schema %s)", inst, gotErr, wantErr, eff) + } + } +} diff --git a/pkgs/mcpx/internal/config/config.go b/pkgs/mcpx/internal/config/config.go index a62834c45c..513b19d6e9 100644 --- a/pkgs/mcpx/internal/config/config.go +++ b/pkgs/mcpx/internal/config/config.go @@ -152,6 +152,14 @@ type Extras struct { // server alone: ask, allow or deny (#1979). Empty means inherit the // daemon mode. WritePolicy string `json:"writePolicy,omitempty"` + // ArgumentRules constrains calls by their arguments (#1986): keys + // are tool patterns matched exactly as Tools/ExcludeTools match, + // values are JSON Schema objects a call's arguments must validate + // against (every matching rule; allOf). In the pool block it + // applies to every server; a server's own rules add to the pool's, + // and across layered files rules only ever tighten. See + // argumentrules.go. + ArgumentRules map[string]json.RawMessage `json:"argumentRules,omitempty"` // RequiresSecrets names environment variables that must be non-empty for this server to be active. RequiresSecrets []string `json:"requiresSecrets,omitempty"` // RequiresServers names other upstream server namespaces that must be enabled. @@ -468,6 +476,12 @@ type Resolved struct { // daemon policy.write setting (#1979). WritePolicy string + // ArgumentRules is this server's compiled argument rules (#1986): + // the pool block's rules and the server's own, compiled at Resolve + // time so a bad pattern or schema is a load-time error. Consumed by + // the daemon's write-policy gate and by schema advertising. + ArgumentRules *ArgumentRuleSet + // Runtime, when set, returns the value the daemon holds in memory for a // secret: see internal/secrets. It is consulted before this server's own // environment and the daemon's, and nothing here keeps what it returns. @@ -704,6 +718,28 @@ func (c *Config) Resolve(name string) (*Resolved, error) { return nil, fmt.Errorf("server %q: excludeTools: %w", name, err) } + // Argument rules (#1986): pool rules and the server's own add up, + // compiled here so a bad pattern or schema fails the load, naming + // the server, instead of silently constraining nothing at call + // time. Origins name the file each rule came from, so a refusal + // can say whose rule it was. + poolOrigin := "the pool block" + if c.Path != "" { + poolOrigin = "the pool block in " + c.Path + } + serverOrigin := fmt.Sprintf("server %q", name) + if f := c.Origin[name]; f != "" { + serverOrigin = fmt.Sprintf("server %q in %s", name, f) + } else if c.Path != "" { + serverOrigin = fmt.Sprintf("server %q in %s", name, c.Path) + } + rules, err := CompileArgumentRules(append( + argumentRuleSources(d.ArgumentRules, poolOrigin), + argumentRuleSources(ex.ArgumentRules, serverOrigin)...)) + if err != nil { + return nil, fmt.Errorf("server %q: %w", name, err) + } + sharing := Sharing(pick(string(ex.Sharing), string(d.Sharing), string(SharingShared))) switch sharing { case SharingShared, SharingExclusive: @@ -751,6 +787,7 @@ func (c *Config) Resolve(name string) (*Resolved, error) { Tools: allow, ExcludeTools: deny, WritePolicy: pick(ex.WritePolicy, d.WritePolicy), + ArgumentRules: rules, Profiles: append(append([]string{}, d.Profiles...), ex.Profiles...), Tags: append(append([]string{}, d.Tags...), ex.Tags...), ToolTags: mergeToolTags(d.ToolTags, ex.ToolTags), @@ -931,7 +968,20 @@ func LoadFrom(explicit, wd string) (*Config, error) { // taken, so nearer always wins without needing to know which fields exist. func mergeInto(near, far *Config, farPath string) { for name, s := range far.MCPServers { - if _, taken := near.MCPServers[name]; taken { + if existing, taken := near.MCPServers[name]; taken { + // The nearer file's server definition wins, as for + // every other field -- but argument rules are the one + // exception, by their own guarantee (#1986): rules + // only tighten, so a nearer file that repeats a server + // without restating its rules must not silently drop + // the farther file's. Compose them into the surviving + // definition, as mergeExtras does for the pool block. + if s.Mcpx != nil && len(s.Mcpx.ArgumentRules) > 0 { + if existing.Mcpx == nil { + existing.Mcpx = &Extras{} + } + existing.Mcpx.ArgumentRules = mergeArgumentRules(existing.Mcpx.ArgumentRules, s.Mcpx.ArgumentRules) + } continue } near.MCPServers[name] = s @@ -991,6 +1041,10 @@ func mergeExtras(near, far Extras) Extras { } // Appending is the point of the field, across files as within one. near.ExtraIncludeTools = concat(far.ExtraIncludeTools, near.ExtraIncludeTools) + // Rules only tighten (#1986): a farther file's argument rules + // survive into the nearer config, and a key both files use + // composes with allOf rather than being replaced. + near.ArgumentRules = mergeArgumentRules(near.ArgumentRules, far.ArgumentRules) return near } diff --git a/pkgs/mcpx/internal/daemon/argument_rules_test.go b/pkgs/mcpx/internal/daemon/argument_rules_test.go new file mode 100644 index 0000000000..1e7398ba9e --- /dev/null +++ b/pkgs/mcpx/internal/daemon/argument_rules_test.go @@ -0,0 +1,151 @@ +package daemon + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/dezren39/mcpx/internal/config" + "github.com/dezren39/mcpx/internal/mcpclient" + "github.com/dezren39/mcpx/internal/pool" +) + +// Argument rules at the gate (#1986): the view carries a compiled rule +// set, and applyWritePolicy must refuse a violating call before the +// write mode is consulted -- including when no write policy is +// configured at all, because rules are their own opt-in. + +func argumentRuleView(t *testing.T) *config.Resolved { + t.Helper() + set, err := config.CompileArgumentRules([]config.ArgumentRuleSource{ + {Key: "wipe", Origin: "test config", Schema: json.RawMessage( + `{"required": ["confirm"], "properties": {"confirm": {"const": "yes"}}}`)}, + }) + if err != nil { + t.Fatalf("CompileArgumentRules: %v", err) + } + return &config.Resolved{Namespace: "demo", ArgumentRules: set} +} + +func argumentRuleRegistry(t *testing.T, mode string) *Registry { + t.Helper() + r := writePolicyRegistry(mode) + r.views = map[string]*config.Resolved{"demo": argumentRuleView(t)} + return r +} + +func TestArgumentRuleRefusesViolatingCallWithNoWritePolicy(t *testing.T) { + r := argumentRuleRegistry(t, "") + p := writePolicyPool(t, "", ``) + _, err := r.applyWritePolicy(context.Background(), p, "demo", "wipe", + config.CallContext{}, map[string]any{"confirm": "no"}) + var denied ErrArgumentRuleDenied + if !errors.As(err, &denied) { + t.Fatalf("applyWritePolicy = %v, want ErrArgumentRuleDenied", err) + } + if got := failureStatus(err); got != 400 { + t.Errorf("failureStatus(ErrArgumentRuleDenied) = %d, want 400 (HiddenTool style)", got) + } + msg := err.Error() + for _, want := range []string{"$.confirm", `"no"`, "wipe", "test config"} { + if !strings.Contains(msg, want) { + t.Errorf("refusal %q does not name %q", msg, want) + } + } +} + +func TestArgumentRulePassesConformingCall(t *testing.T) { + r := argumentRuleRegistry(t, "") + p := writePolicyPool(t, "", ``) + asked, err := r.applyWritePolicy(context.Background(), p, "demo", "wipe", + config.CallContext{}, map[string]any{"confirm": "yes"}) + if err != nil { + t.Fatalf("conforming call refused: %v", err) + } + if asked { + t.Error("conforming call must not report it asked") + } + // A tool with no rules is untouched. + if _, err := r.applyWritePolicy(context.Background(), p, "demo", "other", + config.CallContext{}, map[string]any{"anything": true}); err != nil { + t.Fatalf("unruled tool refused: %v", err) + } +} + +// A tools/list_changed must not make the daemon acquire a pool +// instance just to re-check dead rules: for a session-scoped server +// at max 1 that evicts the caller's live session. The re-check is +// noted, held while the only catalog on hand is the stale +// pre-change one, and discharged by the next fresh catalog a real +// read observes. +func TestDeadRuleRecheckDefersUntilFreshCatalogObserved(t *testing.T) { + var logs []string + p := pool.New(&config.Resolved{ + Server: &config.Server{Name: "demo", Command: "demo"}, Namespace: "demo"}) + p.SetSchemas([]mcpclient.Tool{{Name: "wipe"}}, nil, nil, "", + time.Now(), time.Time{}, false) + r := &Registry{ + views: map[string]*config.Resolved{"demo": argumentRuleView(t)}, + pools: map[string]*pool.Pool{"demo": p}, + logf: func(format string, args ...any) { + logs = append(logs, fmt.Sprintf(format, args...)) + }, + } + + r.noteDeadRuleRecheck("demo") + if _, pending := r.deadRulePending.Load("demo"); !pending { + t.Fatal("list_changed note did not record a pending re-check") + } + + // The handler invalidated the cache; the tool list it still + // serves is the previous catalog, where wipe still exists. + p.Invalidate() + r.recheckDeadArgumentRules("demo") + if len(logs) != 0 { + t.Fatalf("warned from the stale pre-change catalog: %v", logs) + } + if _, pending := r.deadRulePending.Load("demo"); !pending { + t.Fatal("pending re-check discharged without a fresh catalog") + } + + // A fresh catalog arrives (observed by real work) and wipe is + // gone from it: the rule is dead, warned once, note discharged. + p.SetSchemas([]mcpclient.Tool{{Name: "other"}}, nil, nil, "", + time.Now(), time.Time{}, false) + r.recheckDeadArgumentRules("demo") + if len(logs) != 1 || !strings.Contains(logs[0], `"wipe"`) { + t.Fatalf("want exactly one dead-rule warning for wipe, got %v", logs) + } + if _, pending := r.deadRulePending.Load("demo"); pending { + t.Fatal("pending re-check not discharged after the fresh catalog") + } +} + +// A server with no argument rules takes no note at all: there is +// nothing a changed catalog could orphan. +func TestDeadRuleRecheckNotNotedWithoutRules(t *testing.T) { + r := &Registry{ + views: map[string]*config.Resolved{"plain": {Namespace: "plain"}}, + } + r.noteDeadRuleRecheck("plain") + if _, pending := r.deadRulePending.Load("plain"); pending { + t.Fatal("pending re-check recorded for a server with no argument rules") + } +} + +func TestArgumentRuleFiresBeforeWriteMode(t *testing.T) { + // Mode allow would pass this call; the rule still refuses it, + // because in #2126's order the rules step precedes the mode step. + r := argumentRuleRegistry(t, "allow") + p := writePolicyPool(t, "", ``) + _, err := r.applyWritePolicy(context.Background(), p, "demo", "wipe", + config.CallContext{}, map[string]any{}) + var denied ErrArgumentRuleDenied + if !errors.As(err, &denied) { + t.Fatalf("applyWritePolicy under allow = %v, want ErrArgumentRuleDenied", err) + } +} diff --git a/pkgs/mcpx/internal/daemon/consumer.go b/pkgs/mcpx/internal/daemon/consumer.go index 2b6451675d..821e605e60 100644 --- a/pkgs/mcpx/internal/daemon/consumer.go +++ b/pkgs/mcpx/internal/daemon/consumer.go @@ -426,6 +426,9 @@ func (r *Registry) confirmDestructive(ctx context.Context, p *pool.Pool, tool st Reason: "its annotations could not be read: " + err.Error()} } all = fresh + // This refresh is a genuine catalog observation: discharge + // any dead-rule re-check a list_changed left pending (#1986). + r.recheckDeadArgumentRules(p.Name()) } var found *mcpclient.Tool for i := range all { @@ -478,6 +481,23 @@ func (e ErrWriteDenied) Error() string { "change policy.write, or this server's writePolicy, to allow it", e.Tool, e.Mode, e.Reason) } +// ErrArgumentRuleDenied is returned when an argument rule (#1986) +// refuses a call: the call's arguments broke a JSON Schema constraint +// configured for its tool. Like a hidden tool it is the caller's +// mistake -- the arguments, not the server, are wrong -- so the daemon +// answers 400 (see failureStatus), and the MCP pass-through renders it +// as an isError result carrying this text. +type ErrArgumentRuleDenied struct { + Tool string + Violation *config.ArgumentRuleViolation +} + +func (e ErrArgumentRuleDenied) Error() string { + return fmt.Sprintf("%s was refused by an argument rule: %s; "+ + "change the call's arguments, or the rule in the config it names, to allow it", + e.Tool, e.Violation) +} + // applyWritePolicy is the write policy gate (#1979, Phase 1): before a // call, decide from its tool's annotations and the effective mode // whether it proceeds, asks, or is refused. @@ -496,6 +516,32 @@ func (e ErrWriteDenied) Error() string { // under allow confirmDestructive still runs, which is how the floor // reaches a destructive call the policy let through. func (r *Registry) applyWritePolicy(ctx context.Context, p *pool.Pool, server, tool string, cc config.CallContext, args any) (bool, error) { + // Argument rules (#1986) sit in the evaluator's fixed order + // (#2126) after the hidden-tool check -- which resolveAndGuard has + // already applied -- and the Phase 3 ledger hook (still a no-op), + // and BEFORE the write mode below: a call whose arguments break a + // rule is refused whatever the mode says, and a call that + // satisfies every rule has no opinion from this step and falls + // through to the mode. Rules are read from the requested server's + // VIEW for the same reason writePolicy is: aliases share a pool + // but not a configuration. The check runs even when no write + // policy is configured -- rules are their own opt-in -- and before + // the pool is touched, so a refused call starts nothing. + if view, ok := r.View(server); ok && !view.ArgumentRules.Empty() { + rules := view.ArgumentRules + var violation *config.ArgumentRuleViolation + evaluator := policy.Evaluator{ArgumentRules: func() (policy.Decision, bool) { + if v := rules.Check(tool, args); v != nil { + violation = v + return policy.Decision{Kind: policy.DecideDeny, Reason: v.Error()}, true + } + return policy.Decision{}, false + }} + if d := evaluator.Evaluate(policy.Input{Mode: policy.ModeAllow}); d.Kind == policy.DecideDeny { + return false, ErrArgumentRuleDenied{Tool: p.Namespace() + "." + tool, Violation: violation} + } + } + mode := r.consumer.WritePolicy // The requested server's VIEW carries the override, never the // pool's creating config: pools are shared between aliases, so @@ -545,6 +591,9 @@ func (r *Registry) applyWritePolicy(ctx context.Context, p *pool.Pool, server, t Reason: "write policy: its annotations could not be read: " + err.Error()} } all = fresh + // This refresh is a genuine catalog observation: discharge + // any dead-rule re-check a list_changed left pending (#1986). + r.recheckDeadArgumentRules(p.Name()) } // A tool the schemas do not name is treated as unannotated, which // the specification's defaults read as a possibly destructive diff --git a/pkgs/mcpx/internal/daemon/hooks.go b/pkgs/mcpx/internal/daemon/hooks.go index fadc360af7..ea4eaba1ca 100644 --- a/pkgs/mcpx/internal/daemon/hooks.go +++ b/pkgs/mcpx/internal/daemon/hooks.go @@ -51,6 +51,16 @@ func (r *Registry) InstallHooks(bus *events.Bus, broker *elicit.Broker, roots [] if k != "" { r.publish(events.Event{Kind: k, Server: server}) } + // A changed catalog can orphan an argument rule (#1986): + // note that this server's rules need a re-check. The + // check itself is deferred to the next genuine catalog + // observation -- refreshing here would acquire a pool + // instance solely for a diagnostic and can evict a + // session-scoped caller's live process. See + // noteDeadRuleRecheck. + if kind == "tools" { + r.noteDeadRuleRecheck(server) + } }, OnResourceUpdated: func(server, uri string) { r.publish(events.Event{Kind: events.ResourceUpdated, Server: server, URI: uri}) diff --git a/pkgs/mcpx/internal/daemon/registry.go b/pkgs/mcpx/internal/daemon/registry.go index 97fb029608..a894744ad9 100644 --- a/pkgs/mcpx/internal/daemon/registry.go +++ b/pkgs/mcpx/internal/daemon/registry.go @@ -58,6 +58,18 @@ type Registry struct { embedder catalog.Embedder feedbackStore *logstore.FeedbackStore + // deadRuleWarned records argument rules (#1986) already warned + // about as matching no known tool, keyed server + rule key, so a + // dead rule warns once per registry lifetime instead of on every + // catalog observation. + deadRuleWarned sync.Map + // deadRulePending records servers whose catalog changed + // (list_changed) since the last dead-rule check. The check itself + // is deferred to the next genuine catalog observation, so the + // notification handler never acquires a pool instance just for + // this diagnostic (see noteDeadRuleRecheck). + deadRulePending sync.Map + sessMu sync.Mutex leases map[string]*leaseState @@ -235,9 +247,108 @@ func NewRegistry(cfg *config.Config, paths Paths, logf func(string, ...any)) (*R } sort.Strings(r.order) r.loadCache() + r.warnDeadArgumentRules() return r, nil } +// warnDeadArgumentRules logs each argument rule (#1986) that matches +// no tool in its server's cached catalog: a dead rule constrains +// nothing and is usually a tool name that moved. Called at load (from +// NewRegistry, over the disk-seeded cache), after Warm, and on catalog +// changes; a server whose catalog is not loaded yet warns nothing, and +// each rule warns once per registry lifetime unless it comes back to +// life in between. +func (r *Registry) warnDeadArgumentRules() { + names := r.Names() + for _, name := range names { + // This runs at load and after Warm -- both genuine catalog + // observations -- so any pending post-list_changed re-check + // for the server is discharged here. + r.deadRulePending.Delete(name) + r.warnDeadArgumentRulesFor(name) + } +} + +func (r *Registry) warnDeadArgumentRulesFor(name string) { + view, ok := r.View(name) + if !ok || view.ArgumentRules.Empty() { + return + } + p, ok := r.Pool(name) + if !ok { + return + } + tools, _, at := p.CachedSchemas() + if at.IsZero() || len(tools) == 0 { + // A zero timestamp means the cache was invalidated by a + // list_changed and not yet re-read: the tool list still + // served here is the PREVIOUS catalog, and warning against + // it could condemn a rule the changed catalog keeps alive + // (or clear one it orphaned). Wait for a real observation. + return + } + known := make([]string, 0, len(tools)) + for _, t := range tools { + known = append(known, t.Name) + } + dead := map[string]bool{} + for _, rule := range view.ArgumentRules.DeadRules(known) { + dead[rule.Key] = true + k := name + "\x00" + rule.Key + if _, loaded := r.deadRuleWarned.LoadOrStore(k, true); !loaded { + r.logf("argument rule %q for server %q (%s) matches no known tool; it constrains nothing -- check the tool name", + rule.Key, name, rule.Origin) + } + } + for _, rule := range view.ArgumentRules.Rules() { + if !dead[rule.Key] { + r.deadRuleWarned.Delete(name + "\x00" + rule.Key) + } + } +} + +// noteDeadRuleRecheck records that a server's catalog changed +// (tools/list_changed, #1986), so its argument rules need a fresh +// dead-rule check -- later, at the next genuine catalog observation. +// +// The check must NOT run here. Reading the changed catalog means +// RefreshSchemas, which borrows the pool's separate schema key: for +// a session-scoped server at max 1, acquiring that throwaway +// instance evicts and closes the caller's live session process, +// destroying its state between consecutive calls -- all for a +// diagnostic, and even for servers with no argument rules at all. +// The notification handler therefore only takes a note. The check +// runs in recheckDeadArgumentRules once real work (a guarded call, +// Warm) has refreshed the catalog for its own reasons, and +// warnDeadArgumentRulesFor refuses to judge from the stale +// pre-change list in the meantime. +func (r *Registry) noteDeadRuleRecheck(name string) { + view, ok := r.View(name) + if !ok || view.ArgumentRules.Empty() { + return + } + r.deadRulePending.Store(name, true) +} + +// recheckDeadArgumentRules discharges a pending post-list_changed +// dead-rule check for one server, if a fresh catalog has actually +// been observed since the change. Call it after a RefreshSchemas +// that other work already paid for; it acquires nothing itself. +func (r *Registry) recheckDeadArgumentRules(name string) { + if _, pending := r.deadRulePending.Load(name); !pending { + return + } + p, ok := r.Pool(name) + if !ok { + return + } + if _, _, at := p.CachedSchemas(); at.IsZero() { + return // still no fresh catalog; keep the note for the next one + } + r.deadRulePending.Delete(name) + r.warnDeadArgumentRulesFor(name) +} + // ConfigHash fingerprints the server definitions. func (r *Registry) ConfigHash() string { return r.hash } @@ -403,6 +514,7 @@ func (r *Registry) Warm(ctx context.Context, force bool) map[string]error { // that one of them changed. Recording it here is what lets a diagnostic // say when. r.ObserveCatalog() + r.warnDeadArgumentRules() return errs } @@ -549,7 +661,7 @@ func (r *Registry) Tools(namespaces []string) []ToolInfo { Call: "tools." + view.Namespace + "." + fn + "(args)", Native: view.Namespace + "_" + fn, Description: t.Description, - InputSchema: t.InputSchema, + InputSchema: view.ArgumentRules.EffectiveSchema(t.Name, t.InputSchema), Execution: t.Execution, Title: t.Title, OutputSchema: t.OutputSchema, @@ -962,7 +1074,7 @@ func (r *Registry) CodegenNamespaces(names []string, prof config.Profile) ([]cod Name: t.Name, Description: t.Description, Tags: toolTags(view, t.Name), - InputSchema: t.InputSchema, + InputSchema: view.ArgumentRules.EffectiveSchema(t.Name, t.InputSchema), OutputSchema: t.OutputSchema, }) } @@ -1010,6 +1122,7 @@ func failureStatus(err error) int { var hidden HiddenTool var secret SecretRequired var denied ErrWriteDenied + var argDenied ErrArgumentRuleDenied switch { case errors.As(err, &denied): // The write policy refused the call: a permission answer, not @@ -1019,7 +1132,9 @@ func failureStatus(err error) int { // A conflict with the state of the daemon, not a fault in the request // and not a failure of the server: it can succeed once a value exists. return http.StatusConflict - case errors.As(err, &unknown), errors.As(err, &hidden): + case errors.As(err, &unknown), errors.As(err, &hidden), errors.As(err, &argDenied): + // An argument-rule refusal is 400 like a hidden tool (#1986): + // the caller's arguments broke a configured constraint. return http.StatusBadRequest } return http.StatusBadGateway