mcpField
C
custom-builtin-functions

custom-builtin-functions

github.com/chainloop-dev开发60738 次安装今天更新
代码仓库

关于 custom-builtin-functions

用于指导开发者以 Go 为 OPA/Rego 策略引擎扩展自定义内置函数,涵盖命名空间、错误处理、取消支持和函数文档规范。

主要功能

  1. 01以 Go 实现自定义内置函数
  2. 02使用 chainloop.* 命名空间
  3. 03标记非限制性服务调用
  4. 04支持上下文超时与取消
  5. 05记录函数签名与行为

适用场景

  1. 01为 Rego 策略添加领域函数
  2. 02在策略函数中调用第三方服务

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/chainloop-dev/chainloop --skill custom-builtin-functions

安装后在 Claude Code 中输入/custom-builtin-functions确认已加载。

详细介绍

策略引擎扩展

OPA/Rego 策略引擎支持使用 Go 编写的自定义内置函数。

添加自定义内置函数:

  1. 创建内置函数实现(例如,pkg/policies/engine/rego/builtins/myfeature.go):
package builtins

import (
    "github.com/open-policy-agent/opa/ast"
    "github.com/open-policy-agent/opa/topdown"
    "github.com/open-policy-agent/opa/types"
)

const myFuncName = "chainloop.my_function"

func RegisterMyBuiltins() error {
    return Register(&ast.Builtin{
        Name: myFuncName,
        Description: "Description of what this function does",
        Decl: types.NewFunction(
            types.Args(types.Named("input", types.S).Description("this is the input")),
            types.Named("result", types.S).Description("this is the result"),
        ),
    }, myFunctionImpl)
}

func myFunctionImpl(bctx topdown.BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
    // Extract arguments
    input, ok := operands[0].Value.(ast.String)
    if !ok {
        return fmt.Errorf("input must be a string")
    }

    // Implement logic
    result := processInput(string(input))

    // Return result
    return iter(ast.StringTerm(result))
}

// Autoregisters on package load
func init() {
    if err := RegisterMyBuiltins(); err != nil {
        panic(fmt.Sprintf("failed to register built-ins: %v", err))
    }
}
  1. 在策略中使用(*.rego):
package example
import rego.v1

result := {
    "violations": violations,
    "skipped": false
}

violations contains msg if {
    output := chainloop.my_function(input.value)
    output != "expected"
    msg := "Function returned unexpected value"
}

指南:

  • 所有自定义内置函数均使用 chainloop.* 命名空间
  • 调用第三方服务的函数应通过在内置函数定义中添加 NonRestrictiveBuiltin 类别,将其标记为非限制性
  • 始终妥善处理错误,并返回有意义的错误消息
  • 使用 BuiltinContext 中的上下文来支持超时和取消操作
  • 在 Description 字段和参数定义中说明函数签名和行为

评论

支持 Markdown