Files
archie/internal/infrastructure/taskmcp/mcp_sampling.go
T
sam aa57377c7f fix(staterpc): make model usage writes durable through a State Store outage
A failed RecordUsage was logged and dropped, losing chat, title, sampling
and curator usage that cannot be rebuilt from events. The staterpc Client
now keeps a bounded local outbox: a failed write is queued and retried with
backoff (1s doubling to 1m, 10s per attempt) until the store accepts it, so
records land once the store recovers. The queue is capped at 1024 records;
an overflow is refused so the caller logs the drop. The sampling usage
write is bounded to 5s so a dead store cannot hold a model call.
2026-10-30 00:06:38 +11:00

85 lines
3.1 KiB
Go

package taskmcp
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
"github.com/samcharles93/ai-sdk/chat"
"github.com/samcharles93/ai-sdk/core"
"github.com/samcharles93/ai-sdk/runtime"
"github.com/samcharles93/archie-core/internal/agentexec/modelloop"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/usage"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/tools/mcp"
)
// SamplingHandler answers MCP sampling requests with the task's model.
// Without a runtime or model the request is refused. record receives each
// call's model ref and token usage.
func SamplingHandler(llm *runtime.Runtime, cfg config.TaskConfig, record func(context.Context, string, chat.Usage)) mcp.SamplingHandler {
return func(ctx context.Context, req mcp.SamplingRequest) (mcp.SamplingResult, error) {
if llm == nil {
return mcp.SamplingResult{}, errors.New("mcp sampling: no model runtime is configured")
}
model, err := config.ResolveModel(cfg.Models, "", config.PurposeAgent)
if err != nil {
return mcp.SamplingResult{}, fmt.Errorf("mcp sampling: %w", err)
}
messages, err := modelloop.SamplingMessages(req)
if err != nil {
return mcp.SamplingResult{}, err
}
limits := cfg.ModelLimits[model]
options := core.GenerateOptions{
Messages: messages,
System: req.SystemPrompt,
MaxSteps: 1,
MaxTokens: modelloop.SamplingMaxTokens(req.MaxTokens, limits.MaxOutputTokens),
}
if req.Temperature != nil {
options.Temperature = float32(*req.Temperature)
}
result, err := llm.Chat(ctx, model, options)
record(ctx, model, result.TotalUsage)
if err != nil {
return mcp.SamplingResult{}, fmt.Errorf("mcp sampling: %w", err)
}
return mcp.SamplingResult{
Model: model,
Role: "assistant",
Content: mcp.SamplingContent{Type: "text", Text: result.Text},
StopReason: string(result.FinishReason),
}, nil
}
}
// usageWriteTimeout bounds the usage write: a dead store must not hold the
// sampling result beyond a few seconds.
const usageWriteTimeout = 5 * time.Second
// UsageRecorder records a task's MCP sampling calls against the task.
// A failed write is logged, never fails the call: the store client queues the
// record and retries it until the store accepts it.
func UsageRecorder(store usage.Recorder, t *workflow.Task, log *slog.Logger) func(context.Context, string, chat.Usage) {
return func(ctx context.Context, model string, used chat.Usage) {
if store == nil || t == nil {
return
}
record := usage.Record{
Source: usage.SourceTask, TaskID: t.ID, Attempt: t.Attempt, Workflow: t.Workflow, Step: "mcp-sampling",
InputTokens: int64(used.PromptTokens), OutputTokens: int64(used.CompletionTokens),
CachedTokens: int64(used.CachedTokens), At: time.Now().UTC(),
}.WithRef(model)
writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), usageWriteTimeout)
defer cancel()
if err := store.RecordUsage(writeCtx, record); err != nil && log != nil {
log.WarnContext(ctx, "record model usage failed", "model", model, "err", err)
}
}
}