?

A interface

internal/tools/tool.go (parafraseado):

type Tool interface {
    Name() string
    Description() string
    InputSchema() map[string]any
    Execute(ctx context.Context, input json.RawMessage) (string, error)
}

Quatro métodos, sem ciclo de vida. Ferramentas são stateless da perspectiva do loop — qualquer estado que a ferramenta precisa (um cache de regex compilada, um índice in-process) é um campo privado no tipo concreto.

Skeleton para uma nova ferramenta

Vamos adicionar uma ferramenta http_get hipotética que faz fetch de uma URL e retorna seu body.

Passo 1 — O tipo

package builtin

import (
    "context"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "time"

    "github.com/sebastienrousseau/rousseau-agent/internal/tools"
)

// HTTPGetTool fetches a URL over HTTPS and returns the response body.
type HTTPGetTool struct {
    Timeout time.Duration
    client  *http.Client
}

// NewHTTPGetTool constructs an HTTPGetTool. Zero timeout uses 30s.
func NewHTTPGetTool(timeout time.Duration) *HTTPGetTool {
    if timeout == 0 {
        timeout = 30 * time.Second
    }
    return &HTTPGetTool{
        Timeout: timeout,
        client:  &http.Client{Timeout: timeout},
    }
}

Passo 2 — Metadata

// Name satisfies tools.Tool.
func (*HTTPGetTool) Name() string { return "http_get" }

// Description satisfies tools.Tool.
func (*HTTPGetTool) Description() string {
    return "Fetch an HTTPS URL and return the response body. Input: url (string). Redirects are followed up to 10 hops. Response is capped at 1 MiB."
}

A description é voltada ao modelo. Deve se ler como uma docstring curta para outro engenheiro — o que a ferramenta faz, o que as entradas significam, qual a forma da saída.

Passo 3 — Schema de entrada

// InputSchema satisfies tools.Tool.
func (*HTTPGetTool) InputSchema() map[string]any {
    return map[string]any{
        "type": "object",
        "properties": map[string]any{
            "url": map[string]any{
                "type":        "string",
                "description": "Absolute HTTPS URL to fetch.",
            },
        },
        "required": []string{"url"},
    }
}

Mantenha o schema estrito. Cada property recebe uma description. O array required é reforçado pelo validador de tool-use do modelo — campos faltantes causam um retry de tool_use, não um erro de runtime.

Passo 4 — Execute

type httpGetInput struct {
    URL string `json:"url"`
}

// Execute satisfies tools.Tool.
func (t *HTTPGetTool) Execute(ctx context.Context, raw json.RawMessage) (string, error) {
    var in httpGetInput
    if err := json.Unmarshal(raw, &in); err != nil {
        return "", fmt.Errorf("http_get: parse input: %w", err)
    }
    if in.URL == "" {
        return "", fmt.Errorf("http_get: url is required")
    }
    // Refuse plaintext HTTP; refuse non-http schemes.
    if !strings.HasPrefix(in.URL, "https://") {
        return "", fmt.Errorf("http_get: only https:// URLs are permitted")
    }

    req, err := http.NewRequestWithContext(ctx, http.MethodGet, in.URL, nil)
    if err != nil {
        return "", fmt.Errorf("http_get: build request: %w", err)
    }
    req.Header.Set("user-agent", "rousseau-agent/http_get")

    resp, err := t.client.Do(req)
    if err != nil {
        return "", fmt.Errorf("http_get: transport: %w", err)
    }
    defer func() { _ = resp.Body.Close() }()

    body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
    if err != nil {
        return "", fmt.Errorf("http_get: read body: %w", err)
    }
    return fmt.Sprintf("HTTP %d\n%s", resp.StatusCode, string(body)), nil
}

// Compile-time interface satisfaction check.
var _ tools.Tool = (*HTTPGetTool)(nil)

Passo 5 — Registro

Conecte em internal/cli/chat.go (e cada outro comando que constrói um registry — faça grep por registry.MustRegister para encontrá-los):

registry.MustRegister(builtin.NewHTTPGetTool(30 * time.Second))

Uma vez registrada, a ferramenta fica disponível ao modelo em cada turno.

Passo 6 — Testes

Siga internal/tools/builtin/read_test.go para o padrão:

func TestHTTPGetTool_Execute_Success(t *testing.T) {
    srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
        _, _ = w.Write([]byte("hello"))
    }))
    defer srv.Close()

    // The tool refuses plaintext HTTP; wrap the test server behind httptest.NewTLSServer instead
    // for a real integration test, or expose an internal seam that permits `http://` in tests only.
    // The skeleton here is illustrative.
}

func TestHTTPGetTool_Execute_RejectsPlaintextHTTP(t *testing.T) {
    tool := builtin.NewHTTPGetTool(0)
    _, err := tool.Execute(context.Background(), json.RawMessage(`{"url":"http://example.com"}`))
    require.Error(t, err)
    require.Contains(t, err.Error(), "only https")
}

Passo 7 — Política de aprovação

A ferramenta agora está disponível ao modelo, sujeita à política de aprovação. Recomende uma regra de deny nos docs para a postura padrão:

deny:
  - {tool: http_get, match: "\"url\":\"https://(169\\.254|10\\.|192\\.168\\.|172\\.(1[6-9]|2[0-9]|3[01])\\.)"}

Isso bloqueia a ferramenta de chamar AWS IMDS ou espaço privado RFC1918 — um pedido comum para ferramentas de HTTP fetching.

Passo 8 — Docs

Adicione uma seção a content/user-guide/tools.md descrevendo a nova ferramenta: schema, semântica, notas de segurança. Siga a forma das cinco ferramentas existentes.

Detalhes do contrato

  • Statelessness: Execute não deve carregar estado entre calls que não seja explicitamente privado aos campos da própria ferramenta. Dois turnos concorrentes em duas sessões podem chamar a mesma ferramenta simultaneamente.
  • Respeito ao context: Execute deve honrar o cancelamento de ctx. Trabalho de longa duração deve checar ctx.Err() periodicamente ou rotear o trabalho por uma chamada de biblioteca ciente de context.
  • Sem panics: retorne erros no lugar. O agent loop converte um erro em um tool_result com IsError: true, ao qual o modelo pode se adaptar.
  • Formato de retorno: a saída é uma string simples, alimentada de volta ao modelo no próximo turno. Inclua estrutura suficiente (por exemplo, números de linha, códigos de status) para o modelo raciocinar sobre ela.

Ferramentas customizadas sem tocar no source

Se você não quer fazer fork do rousseau, embuta o agent loop no seu próprio binário e registre suas ferramentas ali:

registry := tools.NewRegistry()
registry.MustRegister(builtin.NewReadTool())
registry.MustRegister(builtin.NewWriteTool())
// ...
registry.MustRegister(mypkg.NewMyTool())

ag := agent.New(provider, registry, logger, agent.Options{})

Veja examples/embed-agent/ na árvore de código para um exemplo de embedding completo.

Armadilhas comuns

  • Schema muito amplo. Exigir apenas type: object não dá ajuda ao modelo. Enumere cada property, descreva cada campo.
  • Bloquear em I/O sem um deadline. Sempre use NewRequestWithContext, sempre defina um http.Client{Timeout: ...}, sempre honre ctx.
  • Retornar demais. A saída é alimentada de volta ao modelo no próximo turno. Uma resposta de 1 MB queima tokens; limite.
  • Efeitos colaterais escapando. Uma ferramenta que muta o mundo deve logar o que fez na string de retorno para que a trilha de auditoria do approver seja completa.
  • Esquecer a checagem de interface em compile time. var _ tools.Tool = (*MyTool)(nil) no escopo do pacote pega interface drift em build time.

Próximo

Type to search 150+ pages. Ranking: BM25 with title/description boost.