feat(19.7-01): SDK-free pact contracts for MCP, account contributions and prompted actions

- pact/mcp.go: HasMCP, MCP, MCPTool, MCPPrompt, MCPGuard, MCPGuards,
  MCPSubject, MCPDispatch, MCPTokenVerifier, MCPGrant, ErrMCPTokenInvalid,
  MCPPersonalTokenResolver, MCPLinkedBackendResolver, LinkedBackendUser,
  MCPSubjectChanged and its kinds, FrontendPermission, HasFrontendPermissions
- capabilities.go: AdminActionPrompt, AdminRecordAction.Prompt,
  AdminRecordActionInput.Value, HasAccountContributions, AccountContribution,
  AccountAction, AccountActionInput, AccountActionResult
- discovery tests, MCPGuards registry test and a go list -deps assertion
  that pact names neither the MCP SDK, jsonschema-go nor bouncer
- pact README and docs/plugins/registration.md rows
This commit is contained in:
Jakub Zych
2026-10-22 16:16:35 +02:00
parent 5c15dea569
commit 6887abf575
5 changed files with 630 additions and 7 deletions

View File

@@ -3,7 +3,9 @@ package pact
import (
"context"
"errors"
"fmt"
"io/fs"
"os/exec"
"reflect"
"strings"
"testing"
@@ -392,8 +394,9 @@ func TestPhase121ContractsOnSampleController(t *testing.T) {
if err != nil || out.Message != "acme::lang.reinstated" || one.Confirm != "" {
t.Fatalf("record result = %+v err=%v", out, err)
}
if fields := reflect.TypeOf(AdminRecordActionInput{}).NumField(); fields != 2 {
t.Fatalf("AdminRecordActionInput has %d fields, want RecordID and Record", fields)
// RecordID, Record and (phase 19.7) the prompt Value: still no id list.
if fields := reflect.TypeOf(AdminRecordActionInput{}).NumField(); fields != 3 {
t.Fatalf("AdminRecordActionInput has %d fields, want RecordID, Record and Value", fields)
}
if strings.Join(ran, ",") != "bulk,record" {
t.Fatalf("ran = %v", ran)
@@ -430,3 +433,218 @@ func TestPhase121ContractsOnSampleController(t *testing.T) {
}
}
}
// samplePier is a plugin value that implements the phase 19.7 contracts:
// MCP tools and prompts, frontend permission codes and a My account
// contribution with a prompted record action on another controller.
type samplePier struct{}
type samplePostInput struct {
ID uint `path:"id"`
Query string `query:"q"`
Title string `json:"title" jsonschema:"the post title"`
}
func (samplePier) MCP() MCP {
ro := true
return MCP{
Tools: []MCPTool{{
Name: "show_post", Title: "Show a post", Description: "Returns one post.",
Guard: "backend", Method: "GET", Path: "/_blog/api/v1/posts/{id}",
Input: samplePostInput{}, Permissions: []string{"acme.blog.access_posts"}, ReadOnly: &ro,
}},
Prompts: []MCPPrompt{{
Name: "draft_post", Title: "Draft a post", Guard: "backend",
Arguments: []MCPPromptArgument{{Name: "topic", Required: true}},
Render: func(_ context.Context, args map[string]string) ([]MCPPromptMessage, error) {
return []MCPPromptMessage{{Role: "user", Text: "Draft a post about " + args["topic"]}}, nil
},
}},
}
}
func (samplePier) FrontendPermissions() []FrontendPermission {
return []FrontendPermission{{Code: "acme.blog.comment", Label: "acme::lang.comment", Tab: "acme::lang.tab"}}
}
func (samplePier) AccountContributions() []AccountContribution {
return []AccountContribution{{
Name: "site_link", Label: "acme::lang.site_link", Description: "acme::lang.site_link_hint",
Status: func(_ context.Context, adminID uint) (string, error) { return "linked", nil },
Actions: []AccountAction{{
Name: "link", Label: "acme::lang.link", Confirm: "acme::lang.link_confirm",
Applies: func(_ context.Context, adminID uint) (bool, error) { return adminID != 0, nil },
Run: func(_ context.Context, in AccountActionInput) (AccountActionResult, error) {
return AccountActionResult{Message: "acme::lang.linked", URL: "https://blog.example.com/link"}, nil
},
}},
}}
}
func (samplePier) AdminActionExtensions() []AdminActionExtension {
return []AdminActionExtension{{
Controller: "summercms.cabana.users",
RecordActions: []AdminRecordAction{{
Name: "link_site_account", Label: "acme::lang.link_site_account",
Prompt: &AdminActionPrompt{Label: "acme::lang.site_login", MaxLength: 64},
Run: func(_ context.Context, in AdminRecordActionInput) (AdminRecordActionResult, error) {
return AdminRecordActionResult{Message: "linked " + in.Value}, nil
},
}},
}}
}
var (
_ HasMCP = samplePier{}
_ HasFrontendPermissions = samplePier{}
_ HasAccountContributions = samplePier{}
_ HasAdminActionExtensions = samplePier{}
)
// sampleGuard is a guard provider with a fixed name.
type sampleGuard struct{ name string }
func (g sampleGuard) MCPGuardName() string { return g.name }
func (sampleGuard) MCPTokenGuarded(middleware []string) bool {
return strings.Contains(strings.Join(middleware, " "), "api_token")
}
func (sampleGuard) MCPRequirements(middleware []string) (MCPRequirements, error) {
return MCPRequirements{Scopes: []string{"read"}}, nil
}
func (sampleGuard) MCPAllows(context.Context, MCPSubject, MCPRequirements, []string) (bool, error) {
return true, nil
}
func (sampleGuard) MCPDispatch(context.Context, MCPSubject, string) (MCPDispatch, error) {
return MCPDispatch{Principal: "principal", Guards: []string{"api_token"}}, nil
}
// TestPhase197ContractsOnSamplePlugin: the MCP, frontend permission, account
// contribution and prompted record action contracts are discovered by type
// assertion on a plugin value and carry the documented fields.
func TestPhase197ContractsOnSamplePlugin(t *testing.T) {
var plugin any = samplePier{}
mcp, ok := plugin.(HasMCP)
if !ok {
t.Fatal("HasMCP is not discovered")
}
decl := mcp.MCP()
if len(decl.Tools) != 1 || len(decl.Prompts) != 1 {
t.Fatalf("declaration = %+v", decl)
}
tool := decl.Tools[0]
if tool.Name != "show_post" || tool.Guard != "backend" || tool.Method != "GET" || tool.Path != "/_blog/api/v1/posts/{id}" || tool.ReadOnly == nil || !*tool.ReadOnly || tool.Destructive != nil {
t.Fatalf("tool = %+v", tool)
}
if _, isStruct := tool.Input.(samplePostInput); !isStruct || tool.Output != nil {
t.Fatalf("tool input/output = %T %T", tool.Input, tool.Output)
}
prompt := decl.Prompts[0]
msgs, err := prompt.Render(t.Context(), map[string]string{"topic": "beaches"})
if err != nil || len(msgs) != 1 || msgs[0].Role != "user" || !strings.HasSuffix(msgs[0].Text, "beaches") || !prompt.Arguments[0].Required {
t.Fatalf("prompt = %+v msgs=%v err=%v", prompt, msgs, err)
}
fp, ok := plugin.(HasFrontendPermissions)
if !ok || len(fp.FrontendPermissions()) != 1 || fp.FrontendPermissions()[0].Code != "acme.blog.comment" {
t.Fatal("HasFrontendPermissions is not discovered")
}
ac, ok := plugin.(HasAccountContributions)
if !ok || len(ac.AccountContributions()) != 1 {
t.Fatal("HasAccountContributions is not discovered")
}
section := ac.AccountContributions()[0]
status, err := section.Status(t.Context(), 7)
if err != nil || status != "linked" || section.Name != "site_link" || len(section.Actions) != 1 {
t.Fatalf("section = %+v status=%q err=%v", section, status, err)
}
action := section.Actions[0]
if applies, err := action.Applies(t.Context(), 0); err != nil || applies {
t.Fatalf("Applies(0) = %v err=%v", applies, err)
}
res, err := action.Run(t.Context(), AccountActionInput{AdminID: 7})
if err != nil || res.URL == "" || res.Message != "acme::lang.linked" {
t.Fatalf("account action result = %+v err=%v", res, err)
}
// The input of an account action is the signed-in admin and nothing else.
if n := reflect.TypeOf(AccountActionInput{}).NumField(); n != 1 {
t.Fatalf("AccountActionInput has %d fields, want only AdminID", n)
}
ext := plugin.(HasAdminActionExtensions).AdminActionExtensions()[0].RecordActions[0]
if ext.Prompt == nil || ext.Prompt.Label == "" || ext.Prompt.MaxLength != 64 {
t.Fatalf("prompted action = %+v", ext)
}
out, err := ext.Run(t.Context(), AdminRecordActionInput{RecordID: 3, Value: "editor"})
if err != nil || out.Message != "linked editor" {
t.Fatalf("prompted run = %+v err=%v", out, err)
}
if len(MCPSubjectChanged{Guard: "backend", UserID: 7, Kind: MCPSubjectLink}.Kind) == 0 || MCPSubjectPermissions == MCPSubjectRevoked || MCPSubjectDeleted == "" {
t.Fatal("subject change kinds")
}
if grant := (MCPGrant{UserID: 1, Scopes: []string{"read"}}); grant.ExpiresAt.IsZero() != true || !errors.Is(fmt.Errorf("wrap: %w", ErrMCPTokenInvalid), ErrMCPTokenInvalid) {
t.Fatal("grant and sentinel")
}
var _ LinkedBackendUser = LinkedBackendUser{ID: 1, Login: "admin", DisplayName: "Admin"}
var _ MCPSubject = MCPSubject{Guard: "user", UserID: 1, Scopes: []string{"read"}, ClientID: "cli", TokenID: 0}
}
// TestMCPGuardsRegistry: register, duplicate and empty names refused with a
// pact error naming the guard, lookup, and sorted names.
func TestMCPGuardsRegistry(t *testing.T) {
reg := NewMCPGuards()
for _, name := range []string{"user", "backend"} {
if err := reg.Register(sampleGuard{name: name}); err != nil {
t.Fatal(err)
}
}
err := reg.Register(sampleGuard{name: "user"})
if err == nil || !strings.Contains(err.Error(), `pact: mcp guard "user"`) {
t.Fatalf("duplicate: %v", err)
}
if err := reg.Register(sampleGuard{}); err == nil || !strings.HasPrefix(err.Error(), "pact: ") {
t.Fatalf("empty name: %v", err)
}
if err := reg.Register(nil); err == nil || !strings.HasPrefix(err.Error(), "pact: ") {
t.Fatalf("nil provider: %v", err)
}
if got := reg.Names(); strings.Join(got, ",") != "backend,user" {
t.Fatalf("Names = %v", got)
}
g, ok := reg.Lookup("backend")
if !ok || g.MCPGuardName() != "backend" || !g.MCPTokenGuarded([]string{"user.api_token"}) {
t.Fatalf("Lookup(backend) = %v %v", g, ok)
}
if _, ok := reg.Lookup("other"); ok {
t.Fatal("Lookup found an unregistered guard")
}
d, err := g.MCPDispatch(t.Context(), MCPSubject{Guard: "backend", UserID: 1}, "GET")
if err != nil || d.Principal != "principal" || len(d.Guards) != 1 {
t.Fatalf("dispatch = %+v err=%v", d, err)
}
var nilReg *MCPGuards
if _, ok := nilReg.Lookup("user"); ok || nilReg.Names() != nil || nilReg.Register(sampleGuard{name: "x"}) == nil {
t.Fatal("nil registry is not inert")
}
}
// TestPactStaysSDKFree: the package's dependency list names neither the MCP
// SDK, the JSON schema library nor bouncer, so plugins compile without them.
func TestPactStaysSDKFree(t *testing.T) {
goTool, err := exec.LookPath("go")
if err != nil {
t.Skip("go tool not on PATH")
}
out, err := exec.Command(goTool, "list", "-deps", ".").Output()
if err != nil {
t.Fatalf("go list -deps: %v", err)
}
for _, dep := range strings.Split(string(out), "\n") {
for _, banned := range []string{"modelcontextprotocol", "jsonschema-go", "modules/bouncer"} {
if strings.Contains(dep, banned) {
t.Fatalf("pact depends on %s", dep)
}
}
}
}