Serve the Pipelines chat tools over a loopback MCP endpoint and register it with Claude Code, Codex and OpenCode chats
This commit is contained in:
@@ -74,6 +74,9 @@ type chatHub struct {
|
||||
// and its sequence source (chat_activity.go).
|
||||
activity map[string]protocol.ChatActivity
|
||||
activitySeq int64
|
||||
// shown holds the items chats showed through the Pipelines tools; the
|
||||
// subscribe reply carries a chat's retained list. nil records none.
|
||||
shown chatShownStore
|
||||
}
|
||||
|
||||
// chatPart is the retained form of one part. Text and reasoning deltas append to
|
||||
|
||||
@@ -230,7 +230,7 @@ func handleChatSubscribe(request protocol.Message, broker chatBroker, hub *chatH
|
||||
// The reply carries the prompts the server still holds for the session, so
|
||||
// a reloaded client draws them as Queued without any device storage.
|
||||
queue := hub.queueFrame(query.SessionID)
|
||||
_ = write(protocol.Message{Type: protocol.ChatSubscribe, ID: request.ID, ChatQueue: &queue})
|
||||
_ = write(protocol.Message{Type: protocol.ChatSubscribe, ID: request.ID, ChatQueue: &queue, ChatShown: hub.shownFrame(query.SessionID)})
|
||||
if err := hub.ensureObserving(sub.room, broker); err != nil {
|
||||
sub.close()
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "could not observe session " + query.SessionID})
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// awaitToolCallSession attributes a call on a shared harness endpoint (one
|
||||
// OpenCode service serves every chat, and its MCP requests carry no session)
|
||||
// to the chat whose retained stream shows a running tool part with one of
|
||||
// names and exactly these arguments. The harness reports the part as running
|
||||
// before or while it calls the tool, so this waits up to wait for it. It
|
||||
// returns "" when no chat matches, and ambiguous when several distinct chats
|
||||
// do: a call is never guessed into a chat.
|
||||
func (h *chatHub) awaitToolCallSession(ctx context.Context, names []string, arguments json.RawMessage, wait time.Duration) (string, bool) {
|
||||
var want any
|
||||
if json.Unmarshal(arguments, &want) != nil {
|
||||
return "", false
|
||||
}
|
||||
deadline := time.Now().Add(wait)
|
||||
for {
|
||||
sessions := h.runningToolCallSessions(names, want)
|
||||
switch {
|
||||
case len(sessions) == 1:
|
||||
return sessions[0], false
|
||||
case len(sessions) > 1:
|
||||
return "", true
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return "", false
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return "", false
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *chatHub) runningToolCallSessions(names []string, want any) []string {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
var sessions []string
|
||||
for sessionID, turn := range h.turns {
|
||||
if turnHasToolCall(turn, names, want) {
|
||||
sessions = append(sessions, sessionID)
|
||||
}
|
||||
}
|
||||
slices.Sort(sessions)
|
||||
return sessions
|
||||
}
|
||||
|
||||
func turnHasToolCall(turn *chatTurn, names []string, want any) bool {
|
||||
for _, message := range turn.messages {
|
||||
for _, part := range message.parts {
|
||||
p := part.part
|
||||
if p.Type != "tool" || p.State == nil || !slices.Contains(names, p.Name) {
|
||||
continue
|
||||
}
|
||||
if p.State.Status != protocol.ChatToolRunning && p.State.Status != "pending" {
|
||||
continue
|
||||
}
|
||||
var got any
|
||||
if json.Unmarshal(p.State.Input, &got) == nil && reflect.DeepEqual(got, want) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// shownFile is a resolved file inside the operator's home.
|
||||
type shownFile struct {
|
||||
path string
|
||||
name string
|
||||
size int64
|
||||
mime string
|
||||
}
|
||||
|
||||
func (f shownFile) item(kind, title string) protocol.ChatShownItem {
|
||||
return protocol.ChatShownItem{Kind: kind, Title: title, Path: f.path, Name: f.name, Size: f.size, Mime: f.mime}
|
||||
}
|
||||
|
||||
// resolveShownFile applies the /files endpoint's containment rules to a model
|
||||
// supplied path: it must name an existing regular file whose real path (every
|
||||
// symlink resolved) is inside the operator's home and not on a special
|
||||
// filesystem. A relative path is taken from the chat's working directory.
|
||||
func (s *chatToolService) resolveShownFile(ctx context.Context, sessionID, requested string) (shownFile, error) {
|
||||
requested = strings.TrimSpace(requested)
|
||||
if requested == "" {
|
||||
return shownFile{}, errors.New("a path is required")
|
||||
}
|
||||
home, err := s.home()
|
||||
if err != nil {
|
||||
return shownFile{}, err
|
||||
}
|
||||
home = filepath.Clean(home)
|
||||
realHome, err := filepath.EvalSymlinks(home)
|
||||
if err != nil {
|
||||
return shownFile{}, errors.New("the operator's home directory is not available")
|
||||
}
|
||||
if !filepath.IsAbs(requested) && !strings.HasPrefix(requested, "~") {
|
||||
directory := s.chatSessionDirectory(ctx, sessionID)
|
||||
if directory == "" {
|
||||
return shownFile{}, errors.New("path " + requested + " is relative and this chat has no recorded working directory; pass an absolute path")
|
||||
}
|
||||
requested = filepath.Join(directory, requested)
|
||||
}
|
||||
target, err := expandHomePath(home, requested)
|
||||
if err != nil {
|
||||
return shownFile{}, err
|
||||
}
|
||||
_, realTarget, err := resolveInsideHome(realHome, target)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "outside the home directory") {
|
||||
return shownFile{}, errors.New("path " + requested + " is outside the operator's home directory; only files inside home can be shown")
|
||||
}
|
||||
return shownFile{}, err
|
||||
}
|
||||
info, err := os.Stat(realTarget)
|
||||
if err != nil {
|
||||
return shownFile{}, describePathError(requested, err)
|
||||
}
|
||||
if info.IsDir() {
|
||||
return shownFile{}, errors.New(requested + " is a directory; show one file")
|
||||
}
|
||||
if !info.Mode().IsRegular() || specialFilesystem(realTarget) {
|
||||
return shownFile{}, errors.New(requested + " is not a regular file")
|
||||
}
|
||||
return shownFile{path: realTarget, name: filepath.Base(realTarget), size: info.Size(), mime: shownFileMime(realTarget)}, nil
|
||||
}
|
||||
|
||||
// shownFileMime is the type the /files endpoint will serve: by extension, else
|
||||
// sniffed from the first bytes.
|
||||
func shownFileMime(path string) string {
|
||||
if byExtension := mime.TypeByExtension(filepath.Ext(path)); byExtension != "" {
|
||||
media, _, err := mime.ParseMediaType(byExtension)
|
||||
if err == nil {
|
||||
return media
|
||||
}
|
||||
}
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "application/octet-stream"
|
||||
}
|
||||
defer file.Close()
|
||||
var sample [512]byte
|
||||
n, err := file.Read(sample[:])
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
return "application/octet-stream"
|
||||
}
|
||||
media, _, _ := mime.ParseMediaType(http.DetectContentType(sample[:n]))
|
||||
if media == "" {
|
||||
return "application/octet-stream"
|
||||
}
|
||||
return media
|
||||
}
|
||||
|
||||
// shownImageURL accepts only an absolute https URL without credentials.
|
||||
func shownImageURL(raw string) (string, error) {
|
||||
if len(raw) > 2048 {
|
||||
return "", errors.New("the image URL is longer than 2048 characters")
|
||||
}
|
||||
parsed, err := url.Parse(raw)
|
||||
if err != nil || parsed.Host == "" {
|
||||
return "", errors.New("the image URL is not a valid absolute URL")
|
||||
}
|
||||
if parsed.Scheme != "https" {
|
||||
return "", errors.New("only https:// image URLs can be shown")
|
||||
}
|
||||
if parsed.User != nil {
|
||||
return "", errors.New("the image URL must not carry credentials")
|
||||
}
|
||||
return parsed.String(), nil
|
||||
}
|
||||
|
||||
// chatToolNotifier sends one model-requested phone notification for a chat and
|
||||
// reports whether ntfy accepted it, or why not.
|
||||
type chatToolNotifier func(ctx context.Context, sessionID, title, message string) (bool, string)
|
||||
|
||||
// publishToolNotification publishes through the operator's existing "system"
|
||||
// ntfy destination (the one chat attention uses), honoring their ntfy switch.
|
||||
// Tapping it opens the chat (pipelines://chat/<id>).
|
||||
func (h *chatHub) publishToolNotification(ctx context.Context, sessionID, title, message string) (bool, string) {
|
||||
if !chatAttentionConfigured() {
|
||||
return false, "phone notifications (ntfy) are not configured on this Pipelines server"
|
||||
}
|
||||
if !chatNotificationSettings(ctx, h.settings).NtfyEnabled {
|
||||
return false, "the operator has turned phone notifications off"
|
||||
}
|
||||
click, views := chatAttentionLinks(sessionID)
|
||||
if _, err := chatAttentionPublish(ctx, "system", truncateUTF8(title, 256), truncateUTF8(message, 2000), "", nil, click, views...); err != nil {
|
||||
log.Printf("chat tool notification session=%s: %v", sessionID, err)
|
||||
return false, "the notification service refused it: " + err.Error()
|
||||
}
|
||||
return true, ""
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/chattools"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
)
|
||||
|
||||
// The endpoint is served on the server's own listener: a harness registers
|
||||
// the URL the registry issues and calls show_html over it.
|
||||
func TestChatToolsEndpointOnTheServerListener(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "tools-http.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
handler := HandlerWithOptions(ctx, Options{}, store)
|
||||
defer func() { cancel(); WaitRuns(handler) }()
|
||||
srv := httptest.NewServer(handler)
|
||||
defer srv.Close()
|
||||
|
||||
if err := ConfigureChatTools(store, strings.TrimPrefix(srv.URL, "http://")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer chattools.Configure(nil)
|
||||
url, err := chattools.Current().SessionURL("ses_http")
|
||||
if err != nil || !strings.HasPrefix(url, srv.URL+"/mcp/chat/") {
|
||||
t.Fatalf("session url = %q %v", url, err)
|
||||
}
|
||||
rpc := func(target, body string) (int, map[string]any) {
|
||||
request, _ := http.NewRequestWithContext(ctx, http.MethodPost, target, strings.NewReader(body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("Accept", "application/json, text/event-stream")
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
var out map[string]any
|
||||
_ = json.NewDecoder(response.Body).Decode(&out)
|
||||
return response.StatusCode, out
|
||||
}
|
||||
if code, out := rpc(url, `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}`); code != 200 || out["result"] == nil {
|
||||
t.Fatalf("initialize = %d %v", code, out)
|
||||
}
|
||||
code, out := rpc(url, `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"show_html","arguments":{"html":"<svg/>"}}}`)
|
||||
if code != 200 || out["result"].(map[string]any)["isError"] != false {
|
||||
t.Fatalf("tools/call = %d %v", code, out)
|
||||
}
|
||||
if items, _ := store.ChatShownItems(ctx, "ses_http"); len(items) != 1 {
|
||||
t.Fatalf("items = %v", items)
|
||||
}
|
||||
if code, _ := rpc(srv.URL+"/mcp/chat/"+strings.Repeat("f", 64), `{"jsonrpc":"2.0","id":1,"method":"ping"}`); code != http.StatusNotFound {
|
||||
t.Fatalf("unknown token = %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoopbackBase(t *testing.T) {
|
||||
for addr, want := range map[string]string{
|
||||
"127.0.0.1:8080": "http://127.0.0.1:8080",
|
||||
":8080": "http://127.0.0.1:8080",
|
||||
"0.0.0.0:9": "http://127.0.0.1:9",
|
||||
"[::]:9": "http://127.0.0.1:9",
|
||||
"[::1]:9": "http://[::1]:9",
|
||||
"localhost:7": "http://localhost:7",
|
||||
} {
|
||||
if got, err := loopbackBase(addr); err != nil || got != want {
|
||||
t.Fatalf("%s = %q %v", addr, got, err)
|
||||
}
|
||||
}
|
||||
if _, err := loopbackBase("100.64.0.2:8080"); err == nil {
|
||||
t.Fatal("a non-loopback listener cannot serve the loopback-only endpoint")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/chattools"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// run executes one tool for sessionID. A non-nil item is recorded and shown;
|
||||
// the result is the short text the model reads.
|
||||
func (s *chatToolService) run(ctx context.Context, sessionID, tool string, arguments json.RawMessage) (*protocol.ChatShownItem, chattools.Result) {
|
||||
fail := func(format string, args ...any) (*protocol.ChatShownItem, chattools.Result) {
|
||||
return nil, chattools.Result{Text: fmt.Sprintf(format, args...), IsError: true}
|
||||
}
|
||||
var in struct {
|
||||
Path string `json:"path"`
|
||||
URLOrPath string `json:"url_or_path"`
|
||||
Title string `json:"title"`
|
||||
Alt string `json:"alt"`
|
||||
HTML string `json:"html"`
|
||||
HeightHint int `json:"height_hint"`
|
||||
Message string `json:"message"`
|
||||
Priority string `json:"priority"`
|
||||
}
|
||||
if err := json.Unmarshal(arguments, &in); err != nil {
|
||||
return fail("The arguments must be a JSON object matching the %s schema: %v", tool, err)
|
||||
}
|
||||
title := boundedLine(in.Title, 200)
|
||||
switch tool {
|
||||
case chattools.ToolShowFile:
|
||||
file, err := s.resolveShownFile(ctx, sessionID, in.Path)
|
||||
if err != nil {
|
||||
return fail("Nothing was shown: %v", err)
|
||||
}
|
||||
item := file.item(protocol.ChatShownFile, title)
|
||||
return &item, chattools.Result{Text: fmt.Sprintf("Shown in the operator's Pipelines chat: %s (%s).", file.name, humanBytes(file.size))}
|
||||
case chattools.ToolShowImage:
|
||||
source := strings.TrimSpace(in.URLOrPath)
|
||||
alt := boundedLine(in.Alt, 500)
|
||||
if strings.Contains(source, "://") {
|
||||
address, err := shownImageURL(source)
|
||||
if err != nil {
|
||||
return fail("Nothing was shown: %v", err)
|
||||
}
|
||||
item := protocol.ChatShownItem{Kind: protocol.ChatShownImage, Title: title, URL: address, Alt: alt}
|
||||
return &item, chattools.Result{Text: "Shown in the operator's Pipelines chat: the image at " + address + "."}
|
||||
}
|
||||
file, err := s.resolveShownFile(ctx, sessionID, source)
|
||||
if err != nil {
|
||||
return fail("Nothing was shown: %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(file.mime, "image/") {
|
||||
return fail("Nothing was shown: %s is %s, not an image; use show_file for documents.", file.name, file.mime)
|
||||
}
|
||||
item := file.item(protocol.ChatShownImage, title)
|
||||
item.Alt = alt
|
||||
return &item, chattools.Result{Text: fmt.Sprintf("Shown in the operator's Pipelines chat: the image %s (%s).", file.name, humanBytes(file.size))}
|
||||
case chattools.ToolShowHTML:
|
||||
if strings.TrimSpace(in.HTML) == "" {
|
||||
return fail("Nothing was shown: html is empty.")
|
||||
}
|
||||
if len(in.HTML) > chattools.MaxHTMLBytes {
|
||||
return fail("Nothing was shown: the document is %s; the limit is 512 KiB. Simplify it (inline SVG, fewer data points) and call show_html again.", humanBytes(int64(len(in.HTML))))
|
||||
}
|
||||
if !utf8.ValidString(in.HTML) {
|
||||
return fail("Nothing was shown: html is not valid UTF-8.")
|
||||
}
|
||||
item := protocol.ChatShownItem{Kind: protocol.ChatShownHTML, Title: title, HTML: in.HTML, HTMLBytes: len(in.HTML), HeightHint: clampHeightHint(in.HeightHint)}
|
||||
return &item, chattools.Result{Text: fmt.Sprintf("Shown in the operator's Pipelines chat (%s, sandboxed: scripts and network are disabled).", humanBytes(int64(len(in.HTML))))}
|
||||
case chattools.ToolNotify:
|
||||
return s.runNotify(ctx, sessionID, title, in.Message, in.Priority)
|
||||
}
|
||||
return fail("Unknown tool %s.", tool)
|
||||
}
|
||||
|
||||
func (s *chatToolService) runNotify(ctx context.Context, sessionID, title, message, priority string) (*protocol.ChatShownItem, chattools.Result) {
|
||||
message = boundedLine(message, 2000)
|
||||
if title == "" || message == "" {
|
||||
return nil, chattools.Result{Text: "Not sent: title and message are both required.", IsError: true}
|
||||
}
|
||||
switch priority {
|
||||
case "":
|
||||
priority = "default"
|
||||
case "low", "default", "high":
|
||||
default:
|
||||
return nil, chattools.Result{Text: "Not sent: priority must be low, default or high.", IsError: true}
|
||||
}
|
||||
if !s.limiter.allow(sessionID, s.now()) {
|
||||
return nil, chattools.Result{Text: "Not sent: this chat already sent 5 notifications in the last minute. Wait before notifying again.", IsError: true}
|
||||
}
|
||||
delivered, detail := s.notify(ctx, sessionID, title, message)
|
||||
item := protocol.ChatShownItem{Kind: protocol.ChatShownNotify, Title: title, Message: message, Priority: priority, Delivered: delivered, Detail: detail}
|
||||
if !delivered {
|
||||
return &item, chattools.Result{Text: "Not delivered: " + detail + ".", IsError: true}
|
||||
}
|
||||
return &item, chattools.Result{Text: "Delivery accepted: the notification was handed to the operator's phone notification service (ntfy)."}
|
||||
}
|
||||
|
||||
// boundedLine folds text to one line of at most limit bytes.
|
||||
func boundedLine(text string, limit int) string {
|
||||
return truncateUTF8(singleLine(text), limit)
|
||||
}
|
||||
|
||||
func clampHeightHint(hint int) int {
|
||||
switch {
|
||||
case hint <= 0:
|
||||
return 0
|
||||
case hint < 120:
|
||||
return 120
|
||||
case hint > 600:
|
||||
return 600
|
||||
}
|
||||
return hint
|
||||
}
|
||||
|
||||
func humanBytes(n int64) string {
|
||||
switch {
|
||||
case n >= 1<<20:
|
||||
return fmt.Sprintf("%.1f MiB", float64(n)/(1<<20))
|
||||
case n >= 1<<10:
|
||||
return fmt.Sprintf("%.1f KiB", float64(n)/(1<<10))
|
||||
}
|
||||
return fmt.Sprintf("%d bytes", n)
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/chattools"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// chatShownStore persists the items a chat's model showed (pipeline.Store).
|
||||
type chatShownStore interface {
|
||||
AppendChatShownItem(ctx context.Context, sessionID string, item protocol.ChatShownItem) error
|
||||
ChatShownItems(ctx context.Context, sessionID string) ([]protocol.ChatShownItem, error)
|
||||
}
|
||||
|
||||
// chatToolCorrelationWait is how long a call on a shared (instance) endpoint
|
||||
// waits for the harness stream to report the matching running tool call.
|
||||
var chatToolCorrelationWait = 3 * time.Second
|
||||
|
||||
// chatToolService runs the Pipelines tools (chattools.Service) for the chat an
|
||||
// endpoint token serves, records each shown item and pushes it to the chat's
|
||||
// subscribers.
|
||||
type chatToolService struct {
|
||||
tokens chatToolTokenStore
|
||||
shown chatShownStore
|
||||
hub *chatHub
|
||||
registry operatorRegistry
|
||||
home func() (string, error)
|
||||
notify chatToolNotifier
|
||||
limiter *chatNotifyLimiter
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func newChatToolService(tokens chatToolTokenStore, shown chatShownStore, hub *chatHub, registry operatorRegistry) *chatToolService {
|
||||
return &chatToolService{tokens: tokens, shown: shown, hub: hub, registry: registry, home: OperatorHomeDirectory,
|
||||
notify: hub.publishToolNotification, limiter: newChatNotifyLimiter(5, time.Minute), now: time.Now}
|
||||
}
|
||||
|
||||
// registerChatTools serves the MCP endpoint on mux. The route exists only on
|
||||
// the server's own listener; neither the web proxy nor the peer relay forwards
|
||||
// it.
|
||||
func registerChatTools(mux *http.ServeMux, service *chatToolService, version string) {
|
||||
handler := chattools.Handler{Service: service, Version: version}
|
||||
mux.HandleFunc(chatToolPath+"{token}", func(w http.ResponseWriter, r *http.Request) {
|
||||
handler.ServeHTTP(w, r, r.PathValue("token"))
|
||||
})
|
||||
}
|
||||
|
||||
func (s *chatToolService) Known(ctx context.Context, token string) bool {
|
||||
if s == nil || s.tokens == nil || len(token) != 64 {
|
||||
return false
|
||||
}
|
||||
_, found, err := s.tokens.ChatToolScope(ctx, token)
|
||||
return err == nil && found
|
||||
}
|
||||
|
||||
func (s *chatToolService) Call(ctx context.Context, token, tool string, arguments json.RawMessage) chattools.Result {
|
||||
sessionID, refusal := s.session(ctx, token, tool, arguments)
|
||||
if refusal != "" {
|
||||
return chattools.Result{Text: refusal, IsError: true}
|
||||
}
|
||||
item, result := s.run(ctx, sessionID, tool, arguments)
|
||||
if item == nil {
|
||||
return result
|
||||
}
|
||||
item.ID = newChatShownID()
|
||||
item.CreatedAt = s.now().UnixMilli()
|
||||
if s.shown != nil {
|
||||
if err := s.shown.AppendChatShownItem(ctx, sessionID, *item); err != nil {
|
||||
log.Printf("chat tools session=%s: record %s: %v", sessionID, tool, err)
|
||||
return chattools.Result{Text: "Pipelines could not record this item: " + err.Error(), IsError: true}
|
||||
}
|
||||
}
|
||||
if s.hub != nil {
|
||||
s.hub.fanout(sessionID, protocol.Message{Type: protocol.ChatShown,
|
||||
ChatShown: &protocol.ChatShownFrame{SessionID: sessionID, Items: []protocol.ChatShownItem{*item}}}, "")
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// session resolves the chat a call belongs to. A session token names it; a
|
||||
// shared harness instance token is attributed to the one chat whose stream
|
||||
// shows this exact call running, and refused when none or several do.
|
||||
func (s *chatToolService) session(ctx context.Context, token, tool string, arguments json.RawMessage) (string, string) {
|
||||
scope, found, err := s.tokens.ChatToolScope(ctx, token)
|
||||
if err != nil || !found {
|
||||
return "", "This Pipelines endpoint is not recognised."
|
||||
}
|
||||
if id, ok := strings.CutPrefix(scope, chatToolSessionScope); ok && id != "" {
|
||||
return id, ""
|
||||
}
|
||||
if _, ok := strings.CutPrefix(scope, chatToolInstanceScope); ok && s.hub != nil {
|
||||
id, ambiguous := s.hub.awaitToolCallSession(ctx, chattools.HarnessToolNames(tool), arguments, chatToolCorrelationWait)
|
||||
if ambiguous {
|
||||
return "", "Pipelines could not tell which chat made this call (another chat made an identical one); retry with a different title."
|
||||
}
|
||||
if id == "" {
|
||||
return "", "Pipelines could not match this call to a chat it is showing; the tools work only in chats opened through Pipelines."
|
||||
}
|
||||
return id, ""
|
||||
}
|
||||
return "", "This chat is not ready for Pipelines tools yet."
|
||||
}
|
||||
|
||||
// chatSessionDirectory is the chat's recorded working directory, or "".
|
||||
func (s *chatToolService) chatSessionDirectory(ctx context.Context, sessionID string) string {
|
||||
if s.registry == nil {
|
||||
return ""
|
||||
}
|
||||
session, found, err := s.registry.OperatorSession(ctx, sessionID)
|
||||
if err != nil || !found {
|
||||
return ""
|
||||
}
|
||||
return session.Directory
|
||||
}
|
||||
|
||||
func (s *chatToolService) chatTitle(ctx context.Context, sessionID string) string {
|
||||
if s.registry == nil {
|
||||
return ""
|
||||
}
|
||||
session, found, err := s.registry.OperatorSession(ctx, sessionID)
|
||||
if err != nil || !found {
|
||||
return ""
|
||||
}
|
||||
return session.Title
|
||||
}
|
||||
|
||||
func newChatShownID() string {
|
||||
var b [12]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
return "shown_" + hex.EncodeToString(b[:])
|
||||
}
|
||||
|
||||
// chatNotifyLimiter is a per-chat sliding-window rate limit.
|
||||
type chatNotifyLimiter struct {
|
||||
mu sync.Mutex
|
||||
limit int
|
||||
window time.Duration
|
||||
sent map[string][]time.Time
|
||||
}
|
||||
|
||||
func newChatNotifyLimiter(limit int, window time.Duration) *chatNotifyLimiter {
|
||||
return &chatNotifyLimiter{limit: limit, window: window, sent: map[string][]time.Time{}}
|
||||
}
|
||||
|
||||
// allow records one notification for sessionID at now unless the window is
|
||||
// full.
|
||||
func (l *chatNotifyLimiter) allow(sessionID string, now time.Time) bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
kept := l.sent[sessionID][:0]
|
||||
for _, at := range l.sent[sessionID] {
|
||||
if now.Sub(at) < l.window {
|
||||
kept = append(kept, at)
|
||||
}
|
||||
}
|
||||
if len(kept) >= l.limit {
|
||||
l.sent[sessionID] = kept
|
||||
return false
|
||||
}
|
||||
l.sent[sessionID] = append(kept, now)
|
||||
return true
|
||||
}
|
||||
|
||||
// shownFrame is a chat's retained shown items for its subscribe reply, or nil
|
||||
// when it has none (or none are recorded on this server).
|
||||
func (h *chatHub) shownFrame(sessionID string) *protocol.ChatShownFrame {
|
||||
if h == nil || h.shown == nil {
|
||||
return nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(h.baseCtx, 5*time.Second)
|
||||
defer cancel()
|
||||
items, err := h.shown.ChatShownItems(ctx, sessionID)
|
||||
if err != nil {
|
||||
log.Printf("chat shown items session=%s: %v", sessionID, err)
|
||||
return nil
|
||||
}
|
||||
if len(items) == 0 {
|
||||
return nil
|
||||
}
|
||||
return &protocol.ChatShownFrame{SessionID: sessionID, Items: items}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/chattools"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
type chatToolFixture struct {
|
||||
store *pipeline.Store
|
||||
service *chatToolService
|
||||
hub *chatHub
|
||||
home string
|
||||
notified []string
|
||||
}
|
||||
|
||||
func newChatToolFixture(t *testing.T) *chatToolFixture {
|
||||
t.Helper()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "tools.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { store.Close() })
|
||||
f := &chatToolFixture{store: store, hub: newChatHub(), home: t.TempDir()}
|
||||
f.hub.shown = store
|
||||
f.service = newChatToolService(store, store, f.hub, store)
|
||||
f.service.home = func() (string, error) { return f.home, nil }
|
||||
f.service.notify = func(_ context.Context, sessionID, title, message string) (bool, string) {
|
||||
f.notified = append(f.notified, sessionID+": "+title)
|
||||
return true, ""
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *chatToolFixture) token(t *testing.T, scope string) string {
|
||||
t.Helper()
|
||||
token, err := f.store.ChatToolToken(context.Background(), scope)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
func (f *chatToolFixture) call(token, tool, arguments string) chattools.Result {
|
||||
return f.service.Call(context.Background(), token, tool, json.RawMessage(arguments))
|
||||
}
|
||||
|
||||
func (f *chatToolFixture) items(t *testing.T, sessionID string) []protocol.ChatShownItem {
|
||||
t.Helper()
|
||||
items, err := f.store.ChatShownItems(context.Background(), sessionID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func TestChatToolTokensAttributeCallsToExactlyOneChat(t *testing.T) {
|
||||
f := newChatToolFixture(t)
|
||||
a, b := f.token(t, chatToolSessionScope+"ses_a"), f.token(t, chatToolSessionScope+"ses_b")
|
||||
if a == b || len(a) != 64 || !f.service.Known(context.Background(), a) {
|
||||
t.Fatalf("tokens must be distinct 256-bit values: %q %q", a, b)
|
||||
}
|
||||
if again := f.token(t, chatToolSessionScope+"ses_a"); again != a {
|
||||
t.Fatal("a session keeps its token (a detached harness keeps its endpoint)")
|
||||
}
|
||||
if f.service.Known(context.Background(), strings.Repeat("0", 64)) {
|
||||
t.Fatal("an unknown token must be refused")
|
||||
}
|
||||
if r := f.call(a, "show_html", `{"html":"<p>A</p>","title":"For A"}`); r.IsError {
|
||||
t.Fatal(r.Text)
|
||||
}
|
||||
if got := f.items(t, "ses_a"); len(got) != 1 || got[0].Kind != protocol.ChatShownHTML || got[0].Title != "For A" || got[0].HTML != "<p>A</p>" || got[0].ID == "" || got[0].CreatedAt == 0 {
|
||||
t.Fatalf("ses_a items = %+v", got)
|
||||
}
|
||||
if got := f.items(t, "ses_b"); len(got) != 0 {
|
||||
t.Fatalf("another chat must not receive the item: %+v", got)
|
||||
}
|
||||
frame := f.hub.shownFrame("ses_a")
|
||||
if frame == nil || frame.SessionID != "ses_a" || len(frame.Items) != 1 {
|
||||
t.Fatalf("subscribe frame = %+v", frame)
|
||||
}
|
||||
if f.hub.shownFrame("ses_b") != nil {
|
||||
t.Fatal("a chat with no items has no frame")
|
||||
}
|
||||
|
||||
registry := chatToolRegistry{store: f.store, base: "http://127.0.0.1:1"}
|
||||
url, bind, err := registry.PendingURL()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pending := strings.TrimPrefix(url, "http://127.0.0.1:1"+chatToolPath)
|
||||
if r := f.call(pending, "show_html", `{"html":"x"}`); !r.IsError {
|
||||
t.Fatal("an unbound pending token must not show anything")
|
||||
}
|
||||
if err := bind("019a6f7e-1c2d-7e3f-8a9b-0c1d2e3f4a5b"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r := f.call(pending, "show_html", `{"html":"x"}`); r.IsError || len(f.items(t, "019a6f7e-1c2d-7e3f-8a9b-0c1d2e3f4a5b")) != 1 {
|
||||
t.Fatalf("a bound token serves its thread: %v", r)
|
||||
}
|
||||
}
|
||||
|
||||
func TestShowFileStaysInsideHome(t *testing.T) {
|
||||
f := newChatToolFixture(t)
|
||||
token := f.token(t, chatToolSessionScope+"ses_f")
|
||||
inside := filepath.Join(f.home, "work", "report.md")
|
||||
if err := os.MkdirAll(filepath.Dir(inside), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(inside, []byte("# Report\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outside := filepath.Join(t.TempDir(), "secret.txt")
|
||||
if err := os.WriteFile(outside, []byte("secret"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(outside, filepath.Join(f.home, "link.txt")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.store.RecordOperatorSession(context.Background(), "ses_f", filepath.Join(f.home, "work"), "Files", protocol.ChatSessionTagOperator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
r := f.call(token, "show_file", `{"path":"`+inside+`","title":"The report"}`)
|
||||
if r.IsError || !strings.Contains(r.Text, "report.md") {
|
||||
t.Fatalf("inside home: %v", r)
|
||||
}
|
||||
realHome, _ := filepath.EvalSymlinks(f.home)
|
||||
got := f.items(t, "ses_f")
|
||||
if len(got) != 1 || got[0].Path != filepath.Join(realHome, "work", "report.md") || got[0].Name != "report.md" || got[0].Size != 9 || !strings.HasPrefix(got[0].Mime, "text/") {
|
||||
t.Fatalf("item = %+v", got)
|
||||
}
|
||||
if r := f.call(token, "show_file", `{"path":"report.md"}`); r.IsError {
|
||||
t.Fatalf("a relative path resolves against the chat's directory: %v", r)
|
||||
}
|
||||
if r := f.call(token, "show_file", `{"path":"~/work/report.md"}`); r.IsError {
|
||||
t.Fatalf("a ~/ path resolves in home: %v", r)
|
||||
}
|
||||
for _, refused := range []string{outside, filepath.Join(f.home, "link.txt"), filepath.Join(f.home, "work"), filepath.Join(f.home, "missing.png"), "../../../etc/passwd", ""} {
|
||||
if r := f.call(token, "show_file", `{"path":"`+refused+`"}`); !r.IsError {
|
||||
t.Fatalf("%q must be refused: %v", refused, r)
|
||||
}
|
||||
}
|
||||
if len(f.items(t, "ses_f")) != 3 {
|
||||
t.Fatal("refused paths must record nothing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestShowImageAcceptsHomeImagesAndHTTPSOnly(t *testing.T) {
|
||||
f := newChatToolFixture(t)
|
||||
token := f.token(t, chatToolSessionScope+"ses_i")
|
||||
image := filepath.Join(f.home, "plot.png")
|
||||
if err := os.WriteFile(image, []byte("\x89PNG\r\n\x1a\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(f.home, "notes.txt"), []byte("x"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r := f.call(token, "show_image", `{"url_or_path":"`+image+`","alt":"A plot"}`); r.IsError {
|
||||
t.Fatal(r.Text)
|
||||
}
|
||||
if r := f.call(token, "show_image", `{"url_or_path":"https://example.com/a.png","title":"Remote"}`); r.IsError {
|
||||
t.Fatal(r.Text)
|
||||
}
|
||||
for _, refused := range []string{"http://example.com/a.png", "https://user:pw@example.com/a.png", "javascript:alert(1)", "file:///etc/passwd", filepath.Join(f.home, "notes.txt")} {
|
||||
if r := f.call(token, "show_image", `{"url_or_path":"`+refused+`"}`); !r.IsError {
|
||||
t.Fatalf("%q must be refused: %v", refused, r)
|
||||
}
|
||||
}
|
||||
got := f.items(t, "ses_i")
|
||||
if len(got) != 2 || got[0].Kind != protocol.ChatShownImage || got[0].Mime != "image/png" || got[0].Alt != "A plot" || got[1].URL != "https://example.com/a.png" || got[1].Path != "" {
|
||||
t.Fatalf("items = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestShowHTMLSizeLimitAndRetention(t *testing.T) {
|
||||
f := newChatToolFixture(t)
|
||||
token := f.token(t, chatToolSessionScope+"ses_h")
|
||||
if r := f.call(token, "show_html", `{"html":"`+strings.Repeat("a", chattools.MaxHTMLBytes+1)+`"}`); !r.IsError || !strings.Contains(r.Text, "512 KiB") {
|
||||
t.Fatalf("an oversized document must be refused with the limit: %v", r)
|
||||
}
|
||||
if r := f.call(token, "show_html", `{"html":" "}`); !r.IsError {
|
||||
t.Fatal("an empty document must be refused")
|
||||
}
|
||||
if len(f.items(t, "ses_h")) != 0 {
|
||||
t.Fatal("refused documents must record nothing")
|
||||
}
|
||||
full := strings.Repeat("b", chattools.MaxHTMLBytes)
|
||||
for range 5 {
|
||||
if r := f.call(token, "show_html", `{"html":"`+full+`","height_hint":5000}`); r.IsError {
|
||||
t.Fatal(r.Text)
|
||||
}
|
||||
}
|
||||
got := f.items(t, "ses_h")
|
||||
if len(got) != 5 || got[0].HeightHint != 600 {
|
||||
t.Fatalf("items = %d, hint %d", len(got), got[0].HeightHint)
|
||||
}
|
||||
// 2 MiB of HTML is retained: the newest four bodies, the oldest expired.
|
||||
if !got[0].Expired || got[0].HTML != "" || got[0].HTMLBytes != chattools.MaxHTMLBytes {
|
||||
t.Fatalf("the oldest body must be dropped under the budget: expired=%v len=%d", got[0].Expired, len(got[0].HTML))
|
||||
}
|
||||
for _, item := range got[1:] {
|
||||
if item.Expired || len(item.HTML) != chattools.MaxHTMLBytes {
|
||||
t.Fatal("the newest bodies must be kept")
|
||||
}
|
||||
}
|
||||
for range protocol.ChatShownLimit + 5 {
|
||||
f.service.now = func() time.Time { return time.Now().Add(time.Hour) }
|
||||
if r := f.call(token, "show_html", `{"html":"<i>x</i>"}`); r.IsError {
|
||||
t.Fatal(r.Text)
|
||||
}
|
||||
}
|
||||
if got := f.items(t, "ses_h"); len(got) != protocol.ChatShownLimit {
|
||||
t.Fatalf("a chat retains at most %d items, got %d", protocol.ChatShownLimit, len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotifyIsRateLimitedPerChat(t *testing.T) {
|
||||
f := newChatToolFixture(t)
|
||||
a, b := f.token(t, chatToolSessionScope+"ses_n1"), f.token(t, chatToolSessionScope+"ses_n2")
|
||||
now := time.Unix(1_800_000_000, 0)
|
||||
f.service.now = func() time.Time { return now }
|
||||
for i := range 5 {
|
||||
if r := f.call(a, "notify", `{"title":"Done","message":"Build finished","priority":"high"}`); r.IsError {
|
||||
t.Fatalf("notification %d: %v", i, r)
|
||||
}
|
||||
}
|
||||
if r := f.call(a, "notify", `{"title":"Done","message":"again"}`); !r.IsError || !strings.Contains(r.Text, "5 notifications") {
|
||||
t.Fatalf("the sixth in a minute must be refused: %v", r)
|
||||
}
|
||||
if r := f.call(b, "notify", `{"title":"Other","message":"chat"}`); r.IsError {
|
||||
t.Fatalf("another chat has its own limit: %v", r)
|
||||
}
|
||||
now = now.Add(61 * time.Second)
|
||||
if r := f.call(a, "notify", `{"title":"Later","message":"ok"}`); r.IsError {
|
||||
t.Fatalf("the window slides: %v", r)
|
||||
}
|
||||
if r := f.call(a, "notify", `{"title":"Bad","message":"x","priority":"urgent"}`); !r.IsError {
|
||||
t.Fatal("an unknown priority must be refused")
|
||||
}
|
||||
if len(f.notified) != 7 || f.notified[0] != "ses_n1: Done" {
|
||||
t.Fatalf("notified = %v", f.notified)
|
||||
}
|
||||
got := f.items(t, "ses_n1")
|
||||
if len(got) != 6 || got[0].Kind != protocol.ChatShownNotify || !got[0].Delivered || got[0].Priority != "high" {
|
||||
t.Fatalf("items = %+v", got)
|
||||
}
|
||||
|
||||
f.service.notify = func(context.Context, string, string, string) (bool, string) { return false, "ntfy is not configured" }
|
||||
r := f.call(b, "notify", `{"title":"Fails","message":"x"}`)
|
||||
if !r.IsError || !strings.Contains(r.Text, "ntfy is not configured") {
|
||||
t.Fatalf("an undelivered notification is reported: %v", r)
|
||||
}
|
||||
if last := f.items(t, "ses_n2"); len(last) != 2 || last[1].Delivered || last[1].Detail != "ntfy is not configured" {
|
||||
t.Fatalf("the undelivered entry is recorded: %+v", last)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstanceTokenCallsNeedOneMatchingRunningToolCall(t *testing.T) {
|
||||
f := newChatToolFixture(t)
|
||||
token := f.token(t, chatToolInstanceScope+"opencode")
|
||||
saved := chatToolCorrelationWait
|
||||
chatToolCorrelationWait = 100 * time.Millisecond
|
||||
t.Cleanup(func() { chatToolCorrelationWait = saved })
|
||||
arguments := `{"html":"<p>diagram</p>","title":"Plan"}`
|
||||
if r := f.call(token, "show_html", arguments); !r.IsError {
|
||||
t.Fatal("a shared-instance call with no running tool call must be refused")
|
||||
}
|
||||
running := func(sessionID, name, input string) {
|
||||
f.hub.apply(protocol.ChatEventFrame{SessionID: sessionID, MessageID: "msg_" + sessionID, Kind: protocol.ChatEventTool,
|
||||
Part: &protocol.ChatPart{Type: "tool", ID: "prt_" + sessionID, Name: name, State: &protocol.ChatToolState{Status: protocol.ChatToolRunning, Input: json.RawMessage(input)}}})
|
||||
}
|
||||
running("ses_x", "pipelines_show_html", `{"title":"Plan","html":"<p>diagram</p>"}`)
|
||||
running("ses_y", "pipelines_show_html", `{"html":"<p>other</p>"}`)
|
||||
running("ses_z", "bash", arguments)
|
||||
if r := f.call(token, "show_html", arguments); r.IsError {
|
||||
t.Fatal(r.Text)
|
||||
}
|
||||
if len(f.items(t, "ses_x")) != 1 || len(f.items(t, "ses_y"))+len(f.items(t, "ses_z")) != 0 {
|
||||
t.Fatal("the call belongs to the chat running exactly this call")
|
||||
}
|
||||
running("ses_y", "pipelines_show_html", arguments)
|
||||
if r := f.call(token, "show_html", arguments); !r.IsError || !strings.Contains(r.Text, "identical") {
|
||||
t.Fatalf("two chats running the same call must be refused: %v", r)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/chattools"
|
||||
)
|
||||
|
||||
// chatToolTokenStore persists the MCP endpoint tokens (pipeline.Store).
|
||||
type chatToolTokenStore interface {
|
||||
ChatToolToken(ctx context.Context, scope string) (string, error)
|
||||
IssueChatToolToken(ctx context.Context, scope string) (string, error)
|
||||
ChatToolScope(ctx context.Context, token string) (string, bool, error)
|
||||
BindChatToolToken(ctx context.Context, token, scope string) error
|
||||
}
|
||||
|
||||
// The token scopes.
|
||||
const (
|
||||
chatToolSessionScope = "session:"
|
||||
chatToolPendingScope = "pending:"
|
||||
chatToolInstanceScope = "instance:"
|
||||
)
|
||||
|
||||
// chatToolPath is the loopback route prefix of the MCP endpoint. The web proxy
|
||||
// and the peer relay forward an allowlist that does not include it.
|
||||
const chatToolPath = "/mcp/chat/"
|
||||
|
||||
// chatToolRegistry issues the endpoint URLs harnesses register
|
||||
// (chattools.Registry) on the server's own loopback listener.
|
||||
type chatToolRegistry struct {
|
||||
store chatToolTokenStore
|
||||
base string
|
||||
}
|
||||
|
||||
func (r chatToolRegistry) url(token string) string { return r.base + chatToolPath + token }
|
||||
|
||||
func (r chatToolRegistry) SessionURL(sessionID string) (string, error) {
|
||||
if !validChatSessionID(sessionID) {
|
||||
return "", errors.New("invalid chat session id")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
token, err := r.store.ChatToolToken(ctx, chatToolSessionScope+sessionID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return r.url(token), nil
|
||||
}
|
||||
|
||||
func (r chatToolRegistry) PendingURL() (string, func(string) error, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
token, err := r.store.IssueChatToolToken(ctx, chatToolPendingScope)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
bind := func(sessionID string) error {
|
||||
if !validChatSessionID(sessionID) {
|
||||
return errors.New("invalid chat session id")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
return r.store.BindChatToolToken(ctx, token, chatToolSessionScope+sessionID)
|
||||
}
|
||||
return r.url(token), bind, nil
|
||||
}
|
||||
|
||||
func (r chatToolRegistry) InstanceURL(harness string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
token, err := r.store.ChatToolToken(ctx, chatToolInstanceScope+harness)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return r.url(token), nil
|
||||
}
|
||||
|
||||
// loopbackBase is the http origin harnesses on this machine use to reach a
|
||||
// server listening on addr: a wildcard or blank host becomes 127.0.0.1. A
|
||||
// server bound only to a non-loopback address cannot serve the tools: the
|
||||
// endpoint answers loopback peers alone.
|
||||
func loopbackBase(addr string) (string, error) {
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
ip := net.ParseIP(host)
|
||||
switch {
|
||||
case host == "localhost" || (ip != nil && ip.IsLoopback()):
|
||||
return "http://" + net.JoinHostPort(host, port), nil
|
||||
case host == "" || (ip != nil && ip.IsUnspecified()):
|
||||
return "http://" + net.JoinHostPort("127.0.0.1", port), nil
|
||||
}
|
||||
return "", errors.New("the chat tools need a loopback or wildcard listen address, not " + addr)
|
||||
}
|
||||
|
||||
// ConfigureChatTools makes every chat harness Pipelines launches register the
|
||||
// Pipelines MCP server on the listener at addr. It is called once at startup,
|
||||
// before any harness starts.
|
||||
func ConfigureChatTools(store chatToolTokenStore, addr string) error {
|
||||
base, err := loopbackBase(addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
chattools.Configure(chatToolRegistry{store: store, base: base})
|
||||
return nil
|
||||
}
|
||||
@@ -153,6 +153,11 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
}
|
||||
runs.serveArtifact(w, r)
|
||||
})
|
||||
if len(stores) > 0 {
|
||||
// The Pipelines chat tools' MCP endpoint, for harnesses on this machine.
|
||||
hub.shown = stores[0]
|
||||
registerChatTools(mux, newChatToolService(stores[0], stores[0], hub, registry), build.Version)
|
||||
}
|
||||
mux.HandleFunc("GET /discovery", serveServerDiscovery)
|
||||
mux.HandleFunc("GET /files", serveHomeFile)
|
||||
mux.HandleFunc("POST /files", serveHomeFileUpload)
|
||||
|
||||
Reference in New Issue
Block a user