Files
superbrain/internal/mcpclient/client.go
T
Andrew S Erwin ceb4973359
release gate / check (push) Failing after 6m46s
release / smoke (push) Successful in 10m40s
release / publish (push) Failing after 9m59s
Reset version scheme to 0.x (pre-beta); release 0.2.14
Superbrain is not yet beta, so the release line moves from 1.2.x to 0.2.x.
0.2.14 is the same code as 1.2.14 (the Nextcloud DAV connection fix) under
the new number; future releases continue from 0.2.15. Existing 1.2.x tags
and images stay published and untouched; CHANGELOG keeps the 1.2.x entries
as history and notes the reset.

Bumps in lockstep: federated service VERSION, installer
SUPERBRAIN_IMAGE_VERSION, superbrain-mcp package version (pyproject +
__init__). Also fixes the outbound MCP client implementation string, which
still reported a stale hardcoded 1.2.7, to the release version. README
release examples updated to the new scheme.

The house upgrade flow compares version tags by string equality, so the
1.2.14 -> 0.2.14 transition deploys through the standard update.sh path
(no downgrade special-casing needed).
2026-11-16 21:51:02 -06:00

126 lines
4.0 KiB
Go

// Package mcpclient dials external MCP servers on behalf of users
// (Settings → MCP): Streamable HTTP or SSE, optional Bearer/header auth.
// It is the outbound twin of the superbrain-mcp server in mcp/.
//
// House rules enforced here:
// - every dial goes through internal/netguard; user-supplied hosts get NO
// trusted-range exemption (NETGUARD_TRUSTED_HOSTS is operator-pinned
// hostnames only and is never consulted for user input), and production
// dials are pinned to ports 80/443 like every other outbound integration;
// - sessions are short-lived: connect, list, close. Nothing is pooled, so
// a misbehaving server cannot hold server resources;
// - the standalone SSE stream of the streamable transport is disabled —
// request/response is all the test/list flow needs, and it avoids
// persistent connections to arbitrary third parties.
package mcpclient
import (
"context"
"net"
"net/http"
"strings"
"time"
mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/andrew/superbrain/internal/netguard"
)
// Conn is the dial-relevant projection of a stored McpConnection row plus
// its DECRYPTED secret. Callers own the plaintext lifetime.
type Conn struct {
URL string
Transport string // streamable-http | sse
AuthKind string // none | bearer | header
HeaderName string
Secret string
}
// Tool is the UI-facing tool summary.
type Tool struct {
Name string `json:"name"`
Description string `json:"description"`
}
// dial mirrors internal/ai's netguard-pinned transport.
func dial() *http.Transport {
return &http.Transport{
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
if netguard.AllowPrivate() {
return netguard.DialContext(ctx, network, address)
}
return netguard.DialContextPorts(ctx, network, address, 80, 443)
},
TLSHandshakeTimeout: 10 * time.Second,
ResponseHeaderTimeout: 30 * time.Second,
IdleConnTimeout: 30 * time.Second,
}
}
// authRT injects the connection's credential per request. The secret never
// appears in URLs (Go error strings include URLs and get logged).
type authRT struct {
base http.RoundTripper
conn Conn
}
func (a authRT) RoundTrip(r *http.Request) (*http.Response, error) {
r2 := r.Clone(r.Context())
switch a.conn.AuthKind {
case "bearer":
r2.Header.Set("Authorization", "Bearer "+a.conn.Secret)
case "header":
if name := strings.TrimSpace(a.conn.HeaderName); name != "" {
r2.Header.Set(name, a.conn.Secret)
}
}
return a.base.RoundTrip(r2)
}
func httpClient(conn Conn) *http.Client {
return &http.Client{
Transport: authRT{base: dial(), conn: conn},
Timeout: 45 * time.Second,
// Redirects are not followed: a verified origin must not be bounced
// to another host carrying the credential (same discipline as the
// CardDAV client).
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
}
// ListTools connects, initializes and lists the server's tools, then closes
// the session. The context bounds the whole exchange.
func ListTools(ctx context.Context, conn Conn) ([]Tool, error) {
client := mcpsdk.NewClient(&mcpsdk.Implementation{Name: "superbrain", Version: "0.2.14"}, nil)
var transport mcpsdk.Transport
hc := httpClient(conn)
switch conn.Transport {
case "sse":
transport = &mcpsdk.SSEClientTransport{Endpoint: conn.URL, HTTPClient: hc}
default:
transport = &mcpsdk.StreamableClientTransport{
Endpoint: conn.URL, HTTPClient: hc,
DisableStandaloneSSE: true,
MaxRetries: 0,
}
}
session, err := client.Connect(ctx, transport, nil)
if err != nil {
return nil, err
}
defer session.Close()
res, err := session.ListTools(ctx, &mcpsdk.ListToolsParams{})
if err != nil {
return nil, err
}
out := make([]Tool, 0, len(res.Tools))
for _, t := range res.Tools {
desc := strings.TrimSpace(t.Description)
if len(desc) > 300 {
desc = desc[:300] + "…"
}
out = append(out, Tool{Name: t.Name, Description: desc})
}
return out, nil
}