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:
2026-11-09 16:34:21 +00:00
parent 3ab029cd7b
commit 9791f09230
33 changed files with 2308 additions and 7 deletions
+49
View File
@@ -0,0 +1,49 @@
package chattools
import (
"encoding/json"
"strings"
)
// ClaudeMCPConfig is the inline JSON Claude Code takes as --mcp-config.
func ClaudeMCPConfig(url string) string {
data, _ := json.Marshal(map[string]any{"mcpServers": map[string]any{
ServerName: map[string]any{"type": "http", "url": url},
}})
return string(data)
}
// ClaudeAllowedTools pre-approves every Pipelines tool, so a call never waits
// on a permission card: the tools only present content to the operator.
func ClaudeAllowedTools() string { return "mcp__" + ServerName }
// CodexConfig is the thread/start (and thread/resume) config override that
// registers the endpoint as a streamable HTTP MCP server for one thread.
func CodexConfig(url string) map[string]any {
return map[string]any{"mcp_servers": map[string]any{
ServerName: map[string]any{"url": url},
}}
}
// OpenCodeConfig is the OpenCode config fragment registering the endpoint as a
// remote MCP server.
func OpenCodeConfig(url string) map[string]any {
return map[string]any{"mcp": map[string]any{
ServerName: map[string]any{"type": "remote", "url": url, "enabled": true},
}}
}
// HarnessToolNames are the names one tool has in each harness's transcript.
func HarnessToolNames(tool string) []string {
return []string{"mcp__" + ServerName + "__" + tool, ServerName + "_" + tool, ServerName + "/" + tool}
}
// ToolFromHarnessName returns the Pipelines tool a harness tool name denotes.
func ToolFromHarnessName(name string) (string, bool) {
for _, prefix := range []string{"mcp__" + ServerName + "__", ServerName + "_", ServerName + "/"} {
if tool, ok := strings.CutPrefix(name, prefix); ok && IsTool(tool) {
return tool, true
}
}
return "", false
}
+172
View File
@@ -0,0 +1,172 @@
package chattools
import (
"context"
"encoding/json"
"errors"
"io"
"net"
"net/http"
"slices"
)
// MaxRequestBytes bounds one MCP request body: a full show_html document plus
// JSON escaping and the envelope.
const MaxRequestBytes = 4 << 20
// LatestProtocolVersion is the MCP revision this server implements. Older
// revisions a client asks for are accepted: the subset used here (initialize,
// tools/list, tools/call, ping over streamable HTTP with JSON responses) is the
// same in each.
const LatestProtocolVersion = "2025-06-18"
var protocolVersions = []string{"2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"}
// Result is one tool call's outcome: short text for the model.
type Result struct {
Text string
IsError bool
}
// Service executes tool calls for the chat an endpoint token serves.
type Service interface {
// Known reports whether token is an issued endpoint token.
Known(ctx context.Context, token string) bool
// Call runs one tool. arguments is the raw JSON object the model sent.
Call(ctx context.Context, token, tool string, arguments json.RawMessage) Result
}
// Handler serves the MCP streamable HTTP transport for one endpoint token.
type Handler struct {
Service Service
Version string
}
type rpcRequest struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id,omitempty"`
Method string `json:"method"`
Params json.RawMessage `json:"params,omitempty"`
}
type rpcError struct {
Code int `json:"code"`
Message string `json:"message"`
}
type rpcResponse struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id"`
Result any `json:"result,omitempty"`
Error *rpcError `json:"error,omitempty"`
}
// Loopback reports whether a request came over the loopback interface. The
// endpoint is for harness processes on this machine only.
func Loopback(r *http.Request) bool {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return false
}
ip := net.ParseIP(host)
return ip != nil && ip.IsLoopback()
}
// ServeHTTP answers one POSTed JSON-RPC message. A browser request (any Origin
// header) and a non-loopback peer are refused, an unknown token is 404, and
// GET (the optional server-to-client stream) is not offered.
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, token string) {
if r.Header.Get("Origin") != "" || !Loopback(r) {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
if h.Service == nil || !h.Service.Known(r.Context(), token) {
http.NotFound(w, r)
return
}
if r.Method != http.MethodPost {
w.Header().Set("Allow", http.MethodPost)
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, MaxRequestBytes))
if err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
writeRPC(w, rpcResponse{JSONRPC: "2.0", ID: json.RawMessage("null"), Error: &rpcError{Code: -32600, Message: "request exceeds 4 MiB"}})
return
}
http.Error(w, "unreadable request", http.StatusBadRequest)
return
}
var request rpcRequest
if err := json.Unmarshal(body, &request); err != nil || request.JSONRPC != "2.0" || request.Method == "" {
writeRPC(w, rpcResponse{JSONRPC: "2.0", ID: json.RawMessage("null"), Error: &rpcError{Code: -32700, Message: "expected one JSON-RPC 2.0 request"}})
return
}
if len(request.ID) == 0 || string(request.ID) == "null" {
// A notification (notifications/initialized, cancellations) has no reply.
w.WriteHeader(http.StatusAccepted)
return
}
response := rpcResponse{JSONRPC: "2.0", ID: request.ID}
response.Result, response.Error = h.dispatch(r.Context(), token, request)
writeRPC(w, response)
}
func (h Handler) dispatch(ctx context.Context, token string, request rpcRequest) (any, *rpcError) {
switch request.Method {
case "initialize":
var params struct {
ProtocolVersion string `json:"protocolVersion"`
}
_ = json.Unmarshal(request.Params, &params)
version := LatestProtocolVersion
if slices.Contains(protocolVersions, params.ProtocolVersion) {
version = params.ProtocolVersion
}
return map[string]any{
"protocolVersion": version,
"capabilities": map[string]any{"tools": map[string]any{"listChanged": false}},
"serverInfo": map[string]any{"name": ServerName, "title": "Pipelines", "version": h.version()},
"instructions": Instructions,
}, nil
case "ping":
return map[string]any{}, nil
case "tools/list":
return map[string]any{"tools": definitions()}, nil
case "tools/call":
var params struct {
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
}
if err := json.Unmarshal(request.Params, &params); err != nil || params.Name == "" {
return nil, &rpcError{Code: -32602, Message: "tools/call needs a tool name"}
}
if !IsTool(params.Name) {
return nil, &rpcError{Code: -32602, Message: "unknown tool: " + params.Name}
}
if len(params.Arguments) == 0 || string(params.Arguments) == "null" {
params.Arguments = json.RawMessage("{}")
}
result := h.Service.Call(ctx, token, params.Name, params.Arguments)
return map[string]any{
"content": []map[string]any{{"type": "text", "text": result.Text}},
"isError": result.IsError,
}, nil
}
return nil, &rpcError{Code: -32601, Message: "method not found: " + request.Method}
}
func (h Handler) version() string {
if h.Version == "" {
return "dev"
}
return h.Version
}
func writeRPC(w http.ResponseWriter, response rpcResponse) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
_ = json.NewEncoder(w).Encode(response)
}
+169
View File
@@ -0,0 +1,169 @@
package chattools
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
type fakeService struct {
known map[string]bool
calls []string
}
func (f *fakeService) Known(_ context.Context, token string) bool { return f.known[token] }
func (f *fakeService) Call(_ context.Context, token, tool string, arguments json.RawMessage) Result {
f.calls = append(f.calls, token+" "+tool+" "+string(arguments))
return Result{Text: "ok " + tool}
}
func post(t *testing.T, h Handler, token, body string, mutate func(*http.Request)) *httptest.ResponseRecorder {
t.Helper()
request := httptest.NewRequest(http.MethodPost, "/mcp/chat/"+token, strings.NewReader(body))
request.RemoteAddr = "127.0.0.1:50000"
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json, text/event-stream")
if mutate != nil {
mutate(request)
}
recorder := httptest.NewRecorder()
h.ServeHTTP(recorder, request, token)
return recorder
}
func decode(t *testing.T, recorder *httptest.ResponseRecorder) map[string]any {
t.Helper()
var out map[string]any
if err := json.Unmarshal(recorder.Body.Bytes(), &out); err != nil {
t.Fatalf("response %d %q: %v", recorder.Code, recorder.Body.String(), err)
}
return out
}
func TestHandshakeListAndCall(t *testing.T) {
service := &fakeService{known: map[string]bool{"tok": true}}
h := Handler{Service: service, Version: "1.2.3"}
init := decode(t, post(t, h, "tok", `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"x","version":"1"}}}`, nil))
result := init["result"].(map[string]any)
if result["protocolVersion"] != "2025-03-26" {
t.Fatalf("a supported requested version must be echoed: %v", result)
}
if result["serverInfo"].(map[string]any)["name"] != ServerName || result["capabilities"].(map[string]any)["tools"] == nil {
t.Fatalf("initialize result = %v", result)
}
unknown := decode(t, post(t, h, "tok", `{"jsonrpc":"2.0","id":2,"method":"initialize","params":{"protocolVersion":"1999-01-01"}}`, nil))
if unknown["result"].(map[string]any)["protocolVersion"] != LatestProtocolVersion {
t.Fatalf("an unknown version must get the latest: %v", unknown)
}
if got := post(t, h, "tok", `{"jsonrpc":"2.0","method":"notifications/initialized"}`, nil); got.Code != http.StatusAccepted || got.Body.Len() != 0 {
t.Fatalf("a notification must be 202 with no body: %d %q", got.Code, got.Body.String())
}
list := decode(t, post(t, h, "tok", `{"jsonrpc":"2.0","id":"l","method":"tools/list"}`, nil))
tools := list["result"].(map[string]any)["tools"].([]any)
var names []string
for _, tool := range tools {
entry := tool.(map[string]any)
names = append(names, entry["name"].(string))
if entry["description"] == "" || entry["inputSchema"].(map[string]any)["type"] != "object" {
t.Fatalf("tool without description or schema: %v", entry)
}
}
if strings.Join(names, ",") != "show_file,show_image,show_html,notify" {
t.Fatalf("tools = %v", names)
}
if list["id"] != "l" {
t.Fatalf("a string id must be echoed: %v", list)
}
call := decode(t, post(t, h, "tok", `{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"show_html","arguments":{"html":"<b>x</b>"}}}`, nil))
content := call["result"].(map[string]any)["content"].([]any)[0].(map[string]any)
if content["type"] != "text" || content["text"] != "ok show_html" || call["result"].(map[string]any)["isError"] != false {
t.Fatalf("call result = %v", call)
}
if len(service.calls) != 1 || service.calls[0] != `tok show_html {"html":"<b>x</b>"}` {
t.Fatalf("service calls = %v", service.calls)
}
bad := decode(t, post(t, h, "tok", `{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"rm_rf"}}`, nil))
if bad["error"].(map[string]any)["code"].(float64) != -32602 {
t.Fatalf("an unknown tool must be invalid params: %v", bad)
}
missing := decode(t, post(t, h, "tok", `{"jsonrpc":"2.0","id":5,"method":"resources/list"}`, nil))
if missing["error"].(map[string]any)["code"].(float64) != -32601 {
t.Fatalf("an unknown method must be method-not-found: %v", missing)
}
parse := decode(t, post(t, h, "tok", `[{"jsonrpc":"2.0","id":6,"method":"ping"}]`, nil))
if parse["error"].(map[string]any)["code"].(float64) != -32700 {
t.Fatalf("a batch is refused: %v", parse)
}
if len(service.calls) != 1 {
t.Fatalf("refused requests must not call tools: %v", service.calls)
}
}
func TestEndpointRefusesUnknownTokensBrowsersRemotePeersAndGET(t *testing.T) {
service := &fakeService{known: map[string]bool{"tok": true}}
h := Handler{Service: service}
ping := `{"jsonrpc":"2.0","id":1,"method":"ping"}`
if got := post(t, h, "other", ping, nil); got.Code != http.StatusNotFound {
t.Fatalf("unknown token = %d", got.Code)
}
if got := post(t, h, "tok", ping, func(r *http.Request) { r.Header.Set("Origin", "https://evil.example") }); got.Code != http.StatusForbidden {
t.Fatalf("browser origin = %d", got.Code)
}
if got := post(t, h, "tok", ping, func(r *http.Request) { r.RemoteAddr = "100.64.0.9:4000" }); got.Code != http.StatusForbidden {
t.Fatalf("remote peer = %d", got.Code)
}
if got := post(t, h, "tok", ping, func(r *http.Request) { r.RemoteAddr = "[::1]:4000" }); got.Code != http.StatusOK {
t.Fatalf("IPv6 loopback = %d", got.Code)
}
if got := post(t, h, "tok", "", func(r *http.Request) { r.Method = http.MethodGet }); got.Code != http.StatusMethodNotAllowed {
t.Fatalf("GET = %d", got.Code)
}
large := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"show_html","arguments":{"html":"` + strings.Repeat("a", MaxRequestBytes) + `"}}}`
if got := decode(t, post(t, h, "tok", large, nil)); got["error"] == nil {
t.Fatalf("an oversized request must be refused: %v", got)
}
if len(service.calls) != 0 {
t.Fatalf("refused requests reached the service: %v", service.calls)
}
}
func TestHarnessRegistrationConfig(t *testing.T) {
url := "http://127.0.0.1:8080/mcp/chat/abc"
var claude map[string]map[string]map[string]string
if err := json.Unmarshal([]byte(ClaudeMCPConfig(url)), &claude); err != nil {
t.Fatal(err)
}
if got := claude["mcpServers"]["pipelines"]; got["type"] != "http" || got["url"] != url {
t.Fatalf("claude config = %v", claude)
}
if ClaudeAllowedTools() != "mcp__pipelines" {
t.Fatalf("claude allowed tools = %q", ClaudeAllowedTools())
}
codex := CodexConfig(url)["mcp_servers"].(map[string]any)["pipelines"].(map[string]any)
if codex["url"] != url {
t.Fatalf("codex config = %v", codex)
}
open := OpenCodeConfig(url)["mcp"].(map[string]any)["pipelines"].(map[string]any)
if open["type"] != "remote" || open["url"] != url || open["enabled"] != true {
t.Fatalf("opencode config = %v", open)
}
for _, name := range HarnessToolNames(ToolShowFile) {
if tool, ok := ToolFromHarnessName(name); !ok || tool != ToolShowFile {
t.Fatalf("%s not recognised", name)
}
}
for _, name := range []string{"pipelines_rm", "mcp__other__show_file", "show_file", "bash"} {
if _, ok := ToolFromHarnessName(name); ok {
t.Fatalf("%s must not be a Pipelines tool", name)
}
}
}
+53
View File
@@ -0,0 +1,53 @@
// Package chattools is the harness-neutral half of the Pipelines chat tools:
// the MCP server a chat's model calls to show the operator a file, an image or
// an HTML view, or to notify their phone. The tools act on Pipelines itself,
// never on the harness or the workspace.
//
// The server (internal/server) owns tokens, persistence and the tool effects.
// The harness adapters (claude, codex, opencode) only need the endpoint URL to
// register, which they obtain from the Registry configured here, so none of
// them imports the server.
package chattools
import "sync"
// ServerName is the MCP server name every harness registers. It fixes the tool
// names the harnesses report: Claude "mcp__pipelines__show_file", OpenCode
// "pipelines_show_file", Codex "pipelines/show_file".
const ServerName = "pipelines"
// Registry issues the loopback MCP endpoint URLs harnesses register. Each URL
// embeds an unguessable token the server resolves to the chat it serves.
type Registry interface {
// SessionURL is the endpoint dedicated to one chat session, stable across
// server restarts so a detached harness process keeps working.
SessionURL(sessionID string) (string, error)
// PendingURL is an endpoint for a chat whose id the harness assigns when
// it creates it (a Codex thread). bind attaches it to that id; calls are
// refused until then.
PendingURL() (url string, bind func(sessionID string) error, err error)
// InstanceURL is the endpoint of one harness process that serves many
// chats (the OpenCode service). Its calls are attributed only to the one
// chat whose matching tool call is running at that moment.
InstanceURL(harness string) (string, error)
}
var (
mu sync.RWMutex
current Registry
)
// Configure installs the registry the harness adapters use. A nil registry
// disables registration: chats start without the Pipelines tools.
func Configure(registry Registry) {
mu.Lock()
defer mu.Unlock()
current = registry
}
// Current returns the configured registry, or nil when tools are disabled.
func Current() Registry {
mu.RLock()
defer mu.RUnlock()
return current
}
+101
View File
@@ -0,0 +1,101 @@
package chattools
// The tool names, as the MCP server lists them.
const (
ToolShowFile = "show_file"
ToolShowImage = "show_image"
ToolShowHTML = "show_html"
ToolNotify = "notify"
)
// MaxHTMLBytes bounds one show_html document. A larger one is refused, never
// truncated: a cut document would render as something the model did not write.
const MaxHTMLBytes = 512 << 10
// IsTool reports whether name is one of the Pipelines tools.
func IsTool(name string) bool {
switch name {
case ToolShowFile, ToolShowImage, ToolShowHTML, ToolNotify:
return true
}
return false
}
// Instructions is the MCP initialize instructions text.
const Instructions = "These tools act on Pipelines, the app the operator reads this chat in, not on your workspace. " +
"Use show_file / show_image instead of telling the operator a path to open, show_html for diagrams, charts or small visual views, " +
"and notify only when the operator should look at their phone now."
type toolDefinition struct {
Name string `json:"name"`
Title string `json:"title,omitempty"`
Description string `json:"description"`
InputSchema map[string]any `json:"inputSchema"`
Annotations map[string]any `json:"annotations,omitempty"`
}
func stringProperty(description string) map[string]any {
return map[string]any{"type": "string", "description": description}
}
func objectSchema(required []string, properties map[string]any) map[string]any {
return map[string]any{"type": "object", "properties": properties, "required": required, "additionalProperties": false}
}
// definitions is the tools/list result, in a fixed order.
func definitions() []toolDefinition {
return []toolDefinition{
{
Name: ToolShowFile,
Title: "Show a file in the chat",
Description: "Show the operator an existing file from this machine directly in the Pipelines chat: images appear inline, " +
"documents (PDF, Markdown, text, CSV, HTML, and others) as a preview card they can tap to open or download. " +
"Use this instead of telling the operator a path to navigate to. The file must be inside the operator's home directory. " +
"A relative path is resolved against the chat's working directory.",
InputSchema: objectSchema([]string{"path"}, map[string]any{
"path": stringProperty("Absolute path, ~/path, or a path relative to the chat's working directory."),
"title": stringProperty("Optional short caption shown above the file."),
}),
Annotations: map[string]any{"readOnlyHint": true, "openWorldHint": false},
},
{
Name: ToolShowImage,
Title: "Show an image in the chat",
Description: "Show the operator an image inline in the Pipelines chat, from a file on this machine (inside the operator's home) " +
"or from an https:// URL. The URL is loaded by the operator's device without cookies.",
InputSchema: objectSchema([]string{"url_or_path"}, map[string]any{
"url_or_path": stringProperty("An https:// image URL, or a file path as for show_file."),
"title": stringProperty("Optional short caption."),
"alt": stringProperty("Optional description of the image for accessibility."),
}),
Annotations: map[string]any{"readOnlyHint": true},
},
{
Name: ToolShowHTML,
Title: "Show an HTML view in the chat",
Description: "Render a self-contained HTML or SVG document inline in the Pipelines chat: diagrams, charts, tables, small visual views. " +
"It is shown in a sandbox with no scripts, no network and no access to the app: use inline CSS and inline SVG, " +
"<details> for expandable parts and CSS :hover for interaction; JavaScript does not run and external resources do not load. " +
"The operator can open it full screen. At most 512 KiB.",
InputSchema: objectSchema([]string{"html"}, map[string]any{
"html": stringProperty("The complete HTML (or a bare <svg>) document."),
"title": stringProperty("Optional short caption."),
"height_hint": map[string]any{"type": "integer", "description": "Optional preferred inline height in logical pixels (120-600)."},
}),
Annotations: map[string]any{"readOnlyHint": true, "openWorldHint": false},
},
{
Name: ToolNotify,
Title: "Notify the operator's phone",
Description: "Send a push notification to the operator's phone that opens this chat when tapped. " +
"Use it sparingly, for things they should know now (a long task finished, you are blocked on them). " +
"Limited to 5 per minute per chat. Returns whether delivery was accepted.",
InputSchema: objectSchema([]string{"title", "message"}, map[string]any{
"title": stringProperty("Short notification title (one line)."),
"message": stringProperty("Notification text (one or two sentences)."),
"priority": map[string]any{"type": "string", "enum": []string{"low", "default", "high"}, "description": "Optional priority; default is default."},
}),
Annotations: map[string]any{"readOnlyHint": false, "destructiveHint": false, "openWorldHint": true},
},
}
}