Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ type: 'user_message' { text, images: Ref[], intent: 'start' | 'queued' | 'stee
| 'command' { command, cwd, exitCode, output, outputTruncated, background: boolean }
| 'file_change' { changes: { path, kind: 'add' | 'update' | 'delete' | 'move', diff }[] }
| 'web_search' { query, results: { url, title }[] }
| 'tool' { name, server: string | null, input, output, isError } // anything else
| 'tool' { name, server: string | null, input, output, isError, icon? } // anything else; icon: the MCP server's own icon as a data: URI, fetched once by the host from the serverInfo icons its results carry
| 'plan' { steps: { text, status }[] }
| 'subagent' { title, agentType, prompt, result, childSessionId: string | null }
| 'request' { requestId } // the card
Expand Down
4 changes: 3 additions & 1 deletion docs/ux.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ A user preference (`quiet`, default on). T3 hides the mechanics of a turn until
first; thinking, plans and approvals do not count). A new tool flies in and knocks the stack, a
change of rank shuffles them like lotto balls, another call to a tool hops its icon, and a tool
whose call failed turns red. That red replaces a "1 failed" count. A finished run in the history
sits still.
sits still. A command is drawn by its program (Python, Git, GitHub, Go, text search, packages,
containers, network; a terminal otherwise), and an MCP tool by its server's own icon when the
server sends one (Obsidian and Telegram do), else a wrench. Steps that look alike count together.
- **A cheeky line beneath a working run** ("Hoarding GPUs…"): typed out, held 20 seconds, struck
through and faded for the next; struck out when the run ends. The list is in
web/src/session/phrases.ts. The `workPhrases` preference turns it off.
Expand Down
2 changes: 2 additions & 0 deletions internal/host/harness/claudecode/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"context"

"github.com/andyjmorgan/outpost/internal/host/harness/feed"
"github.com/andyjmorgan/outpost/internal/host/harness/mcpicon"
"github.com/andyjmorgan/outpost/internal/host/session"
)

Expand Down Expand Up @@ -228,6 +229,7 @@ func (a *Adapter) Open(_ context.Context, s session.Session) (session.Runtime, e
out: feed.New(), waiters: map[string]chan *ControlResponse{}, done: make(chan struct{})}
rt.tr.OnUnknown = a.OnUnknown
rt.tr.OnRateLimit = a.OnRateLimit
rt.tr.Icons.Fetch = mcpicon.Fetch
cmd.Stderr = &rt.stderr
started := func(int) {}
if a.Spawn != nil {
Expand Down
28 changes: 28 additions & 0 deletions internal/host/harness/claudecode/translate.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"strings"
"time"

"github.com/andyjmorgan/outpost/internal/host/harness/mcpicon"
"github.com/andyjmorgan/outpost/internal/host/session"
)

Expand All @@ -26,6 +27,8 @@ type Translator struct {
OnUnknown func(where string, raw json.RawMessage)
// OnRateLimit is given each rate_limit_event line (the account's limits, during a turn).
OnRateLimit func(raw json.RawMessage)
// Icons are the MCP servers' icons, passed on with their tool steps once Icons.Fetch is set.
Icons mcpicon.Servers

inTurn bool
interrupting bool
Expand Down Expand Up @@ -836,6 +839,9 @@ func (t *Translator) toolUse(id, name string, input json.RawMessage, parent stri
server = parts[1]
}
tl.body = map[string]any{"name": name, "server": server, "input": in, "output": "", "isError": false}
if s, ok := server.(string); ok {
mcpicon.Attach(tl.body, t.Icons.Known(s))
}
}
t.tools[id] = tl
return tl.event(session.ItemRunning)
Expand Down Expand Up @@ -918,6 +924,7 @@ func (t *Translator) toolResult(id string, content json.RawMessage, isError bool
tl.body["output"], tl.body["outputTruncated"] = text, cut
case "tool":
tl.body["output"] = text
t.reicon(tl, structured)
}
return tl.event(session.ItemRunning), true
}
Expand Down Expand Up @@ -960,6 +967,7 @@ func (t *Translator) toolResult(id string, content json.RawMessage, isError bool
tl.body["result"] = text
case "tool":
tl.body["output"], tl.body["isError"] = text, isError
t.reicon(tl, structured)
}
return tl.event(status), true
}
Expand Down Expand Up @@ -1151,3 +1159,23 @@ func compaction(key, status string, before, after int64) session.AdapterEvent {
raw, _ := json.Marshal(body)
return session.AdapterEvent{Kind: session.EventItem, Item: &session.ItemUpdate{Key: key, Type: "compaction", Status: status, Body: raw}}
}

// reicon puts the server's icon on a tool step whose output has just come in: learnt from the
// result if it offers one, and checked again against the body limit now the output is there.
func (t *Translator) reicon(tl *tool, structured json.RawMessage) {
server, _ := tl.body["server"].(string)
icon, _ := tl.body["icon"].(string)
delete(tl.body, "icon")
var r struct {
Meta json.RawMessage `json:"_meta"`
}
_ = json.Unmarshal(structured, &r)
if r.Meta != nil {
if learnt := t.Icons.Learn(server, r.Meta); learnt != "" {
icon = learnt
}
} else if icon == "" {
icon = t.Icons.Known(server)
}
mcpicon.Attach(tl.body, icon)
}
27 changes: 27 additions & 0 deletions internal/host/harness/claudecode/translate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package claudecode
import (
"bufio"
"encoding/json"
"fmt"
"os"
"path/filepath"
"reflect"
Expand Down Expand Up @@ -782,3 +783,29 @@ func TestAnInterruptedTurnsSteersAreNotRestarted(t *testing.T) {
t.Fatal("the steer's own turn was not stopped")
}
}

func TestMCPServerIconRidesOnItsSteps(t *testing.T) {
tr := NewTranslator()
tr.Icons.Fetch = func(src string) string { return "data:image/svg+xml;base64,PHN2Zy8+" }
tool := func(res Result) map[string]any {
var body map[string]any
for _, e := range res.Events {
if e.Kind == session.EventItem && e.Item.Type == "tool" {
_ = json.Unmarshal(e.Item.Body, &body)
}
}
return body
}
start := `{"type":"assistant","message":{"id":"m%d","content":[{"type":"tool_use","id":"toolu_%d","name":"mcp__obsidian__list_vaults","input":{}}]}}`
result := `{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_%d","content":"{}"}]},"tool_use_result":{"content":"{}","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"obsidian","icons":[{"src":"https://x/obsidian.svg","mimeType":"image/svg+xml","sizes":["any"]}]}}}}`
if b := tool(tr.Line(fmt.Appendf(nil, start, 1, 1))); b["icon"] != nil {
t.Fatalf("icon before the server showed one: %v", b["icon"])
}
tool(tr.Line(fmt.Appendf(nil, result, 1)))
for tr.Icons.Known("obsidian") == "" {
time.Sleep(time.Millisecond)
}
if b := tool(tr.Line(fmt.Appendf(nil, start, 2, 2))); b["icon"] != "data:image/svg+xml;base64,PHN2Zy8+" {
t.Fatalf("a later step of the same server: %v", b)
}
}
2 changes: 2 additions & 0 deletions internal/host/harness/codex/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"time"

"github.com/andyjmorgan/outpost/internal/host/harness/feed"
"github.com/andyjmorgan/outpost/internal/host/harness/mcpicon"
"github.com/andyjmorgan/outpost/internal/host/session"
)

Expand Down Expand Up @@ -123,6 +124,7 @@ func (a *Adapter) start(dir string, s session.Session) (*runtime, error) {
rt := &runtime{a: a, cmd: cmd, stdin: stdin, tr: NewTranslator(), conf: s,
out: feed.New(), waiters: map[string]chan *Response{}, done: make(chan struct{})}
rt.tr.OnUnknown, rt.tr.OnRateLimits = a.OnUnknown, a.OnRateLimits
rt.tr.Icons.Fetch = mcpicon.Fetch
cmd.Stderr = &rt.stderr
started := func(int) {}
if a.Spawn != nil && s.ID != "" {
Expand Down
14 changes: 13 additions & 1 deletion internal/host/harness/codex/translate.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"strings"
"time"

"github.com/andyjmorgan/outpost/internal/host/harness/mcpicon"
"github.com/andyjmorgan/outpost/internal/host/session"
)

Expand All @@ -22,6 +23,8 @@ type Translator struct {
OnUnknown func(where string, raw json.RawMessage)
// OnRateLimits is given the account's limits whenever the app-server reports them.
OnRateLimits func(raw json.RawMessage)
// Icons are the MCP servers' icons, passed on with their tool steps once Icons.Fetch is set.
Icons mcpicon.Servers

threadID string
turnID string
Expand Down Expand Up @@ -701,6 +704,7 @@ func (t *Translator) item(raw json.RawMessage, completed bool) (session.AdapterE
Result *struct {
Content []json.RawMessage `json:"content"`
Structured json.RawMessage `json:"structuredContent"`
Meta json.RawMessage `json:"_meta"`
} `json:"result"`
Error *struct {
Message string `json:"message"`
Expand Down Expand Up @@ -843,7 +847,15 @@ func (t *Translator) item(raw json.RawMessage, completed bool) (session.AdapterE
if completed && isError {
status = session.ItemFailed
}
return emit("tool", status, map[string]any{"name": name, "server": server, "input": input, "output": output, "isError": isError})
body := map[string]any{"name": name, "server": server, "input": input, "output": output, "isError": isError}
if it.Type == "mcpToolCall" {
icon := t.Icons.Known(it.Server)
if it.Result != nil && it.Result.Meta != nil {
icon = t.Icons.Learn(it.Server, it.Result.Meta)
}
mcpicon.Attach(body, icon)
}
return emit("tool", status, body)
case "webSearch":
return emit("web_search", done, map[string]any{"query": it.Query, "results": []any{}})
case "subAgentActivity":
Expand Down
199 changes: 199 additions & 0 deletions internal/host/harness/mcpicon/mcpicon.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
// Package mcpicon passes on what an MCP server looks like.
//
// A server can say so: its tool results carry its info, icons included, under
// _meta["io.modelcontextprotocol/serverInfo"]. The web client only shows images it is handed,
// never ones it would fetch from elsewhere, so the host fetches a server's icon once and passes
// it on as a data URI on that server's tool steps. Claude Code and Codex both pass _meta through.
package mcpicon

import (
"encoding/base64"
"encoding/json"
"errors"
"io"
"mime"
"net"
"net/http"
"strconv"
"strings"
"sync"
"syscall"
"time"

"github.com/andyjmorgan/outpost/internal/host/session"
)

const iconMax = 24 << 10

var (
// The address comes from a tool server, so the host only goes to public addresses, over
// https all the way: never to itself or its own network, not even by a redirect.
iconClient = &http.Client{
Timeout: 5 * time.Second,
Transport: &http.Transport{
Proxy: nil,
DialContext: (&net.Dialer{Timeout: 3 * time.Second, Control: publicOnly}).DialContext,
TLSHandshakeTimeout: 3 * time.Second,
},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 3 || req.URL.Scheme != "https" {
return errors.New("not followed")
}
return nil
},
}
iconCache sync.Map // src -> data URI, or "" when it could not be had
// Shared address space (100.64.0.0/10): carrier NAT and Tailscale, never the public internet.
cgnat = &net.IPNet{IP: net.IPv4(100, 64, 0, 0), Mask: net.CIDRMask(10, 32)}
// public says whether an address may be fetched from; tests widen it to their own server.
public = func(ip net.IP) bool {
return !(cgnat.Contains(ip) || ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsUnspecified() || ip.IsMulticast() || ip.IsInterfaceLocalMulticast())
}
)

// publicOnly refuses a connection to anything but a public address, checked on the address
// actually dialled so a name that resolves somewhere private is refused too.
func publicOnly(_, address string, _ syscall.RawConn) error {
host, _, err := net.SplitHostPort(address)
if err != nil {
return err
}
if ip := net.ParseIP(host); ip == nil || !public(ip) {
return errors.New("icon address is not public")
}
return nil
}

// Pick is the icon a tool result's _meta offers for its server: a vector, else the bitmap
// nearest 32 pixels. "" when it offers none.
func Pick(meta json.RawMessage) string {
var r struct {
Server struct {
Icons []struct {
Src string `json:"src"`
MimeType string `json:"mimeType"`
Sizes []string `json:"sizes"`
} `json:"icons"`
} `json:"io.modelcontextprotocol/serverInfo"`
}
if json.Unmarshal(meta, &r) != nil {
return ""
}
best, score := "", -1
for _, ic := range r.Server.Icons {
if !strings.HasPrefix(ic.Src, "https://") && !strings.HasPrefix(ic.Src, "data:image/") {
continue
}
s := 0
switch {
case ic.MimeType == "image/svg+xml" || strings.HasSuffix(ic.Src, ".svg"):
s = 1000
default:
for _, size := range ic.Sizes {
ws, _, _ := strings.Cut(size, "x")
if w, err := strconv.Atoi(ws); err == nil {
d := w - 32
if d < 0 {
d = -d * 3 // smaller than 32 looks worse than larger
}
s = max(s, 500-d)
}
}
}
if s > score {
best, score = ic.Src, s
}
}
return best
}

// Fetch turns an icon's address into a data URI, once per address for the life of the host.
// Only https, only images, and only small ones; anything else is remembered as missing.
func Fetch(src string) string {
if strings.HasPrefix(src, "data:image/") {
if len(src) > iconMax*2 {
return ""
}
return src
}
if v, ok := iconCache.Load(src); ok {
return v.(string)
}
uri := ""
defer func() { iconCache.Store(src, uri) }()
if !strings.HasPrefix(src, "https://") {
return ""
}
res, err := iconClient.Get(src)
if err != nil {
return ""
}
defer res.Body.Close()
ct, _, _ := mime.ParseMediaType(res.Header.Get("Content-Type"))
if res.StatusCode != http.StatusOK || (ct != "image/svg+xml" && ct != "image/png" && ct != "image/webp" && ct != "image/jpeg") {
return ""
}
b, err := io.ReadAll(io.LimitReader(res.Body, iconMax+1))
if err != nil || len(b) > iconMax || len(b) == 0 {
return ""
}
uri = "data:" + ct + ";base64," + base64.StdEncoding.EncodeToString(b)
return uri
}

// Attach puts the icon on a tool step's body unless that would make the body too big to keep:
// a picture is never worth losing the step's input and output for.
func Attach(body map[string]any, icon string) {
if icon == "" {
return
}
body["icon"] = icon
if b, err := json.Marshal(body); err != nil || len(b) > session.MaxItemBody {
delete(body, "icon")
}
}

// Servers remembers each server's icon for one session, so a server's later steps show it. The
// icon is fetched in the background, so a slow or missing picture never holds up the session:
// the step that first offers it goes on without, and the steps after it carry it. The zero value
// passes nothing on until Fetch is set.
type Servers struct {
Fetch func(src string) string
mu sync.Mutex
icons map[string]string // server -> data URI, "" while fetching or once known to have none
}

// Known is the server's icon if it has been fetched.
func (s *Servers) Known(server string) string {
s.mu.Lock()
defer s.mu.Unlock()
return s.icons[server]
}

// Learn takes the icon a result's _meta offers for its server and fetches it once, in the
// background. It says the icon if it is already to hand.
func (s *Servers) Learn(server string, meta json.RawMessage) string {
if server == "" || s.Fetch == nil {
return ""
}
s.mu.Lock()
defer s.mu.Unlock()
if icon, ok := s.icons[server]; ok {
return icon
}
src := Pick(meta)
if src == "" {
return ""
}
if s.icons == nil {
s.icons = map[string]string{}
}
s.icons[server] = ""
go func() {
icon := s.Fetch(src)
s.mu.Lock()
s.icons[server] = icon
s.mu.Unlock()
}()
return ""
}
Loading
Loading