Outbound MCP connections: Notion-style client integrations (Settings -> MCP)
Superbrain dials external MCP servers as a client (official modelcontextprotocol/go-sdk): Streamable HTTP or SSE, none/bearer/header auth. Management surface /api/mcp/connections (CRUD + test) with the house disciplines: - secrets encrypted at rest (internal/crypto), masked in every response, write-only (mask or omission keeps the stored value); authKind none clears them - mutating PATCH carries version (409 on stale); mask-only PATCH is a documented no-op returning the current projection - dials netguard-pinned (public ranges, ports 80/443 outside tests), no redirect following, header names restricted to RFC 7230 tokens - test endpoint: per-user limiter + shared outbound budget; 502 with an error class on dial/auth failure, never a silent ok; returns the tool list for the UI - cap of 10 connections per user under the user lock UI: Settings -> MCP tab (components/mcp-settings.tsx) — list with enable switch, add/edit dialog (secret never prefilled), Test showing the live tool list or the server's error verbatim. Migration 018 + schema.sql; integration test drives a go-sdk fake MCP server (incl. a Bearer-secured one) end to end. Tool USE by the assistant is phase 2.
This commit is contained in:
@@ -0,0 +1,125 @@
|
||||
// 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: "1.2.7"}, 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
|
||||
}
|
||||
Reference in New Issue
Block a user