refactor(mcp): use the official MCP Go SDK for the client
Deletes the hand-written internal/tools/mcp client and transports. The provider talks to an SDK ClientSession over CommandTransport, StreamableClientTransport or SSEClientTransport, and reconnects when the server exits. The http transport now keeps a real streamable session instead of stateless POSTs. Sampling goes through one adapter, since the SDK marks it deprecated (SEP-2577). message_endpoint is removed: the SSE transport takes the POST URL from the server's endpoint event.
This commit is contained in:
21 files changed
+369
-2122
No files matched your search
@@ -46,10 +46,13 @@ require (
|
||||
github.com/philhofer/fwd v1.2.1 // indirect
|
||||
github.com/pjbgf/sha1cd v0.7.0 // indirect
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
|
||||
github.com/segmentio/asm v1.2.1 // indirect
|
||||
github.com/segmentio/encoding v0.5.4 // indirect
|
||||
github.com/sergi/go-diff v1.4.0 // indirect
|
||||
github.com/sethvargo/go-retry v0.5.0 // indirect
|
||||
github.com/tinylib/msgp v1.6.5 // indirect
|
||||
github.com/x448/float16 v0.8.4 // indirect
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/otel/log v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.47.0 // indirect
|
||||
@@ -82,6 +85,7 @@ require (
|
||||
github.com/klauspost/compress v1.20.4
|
||||
github.com/moby/moby/api v1.56.1
|
||||
github.com/moby/moby/client v0.6.2
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0
|
||||
github.com/nats-io/nats-server/v2 v2.15.3
|
||||
github.com/nats-io/nats.go v1.55.0
|
||||
github.com/opencontainers/go-digest v1.0.0
|
||||
|
||||
@@ -139,6 +139,8 @@ github.com/moby/moby/api v1.56.1 h1:PpWkvVPB7Fr/No8w+TfyJ/I6rWZ2YPZhT3JorIg+06c=
|
||||
github.com/moby/moby/api v1.56.1/go.mod h1:sZ+THbVWkjOmBPPfbnzdD/G1LuIexWhqlSHHPTDQ1Uk=
|
||||
github.com/moby/moby/client v0.6.2 h1:ekSPlMccrZGcw6Scb8T9D39qE0mB+XupU/yS0zNw9N4=
|
||||
github.com/moby/moby/client v0.6.2/go.mod h1:DGcnO7qmPJrqobx/ggQgQ/AUk+2wgVdQv7uxB0/mEsc=
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
|
||||
github.com/nats-io/jwt/v2 v2.8.3 h1:pqImTmlqH2zPHKNdRXO0YRyWif2diGRlrtLFJ2RxM2I=
|
||||
github.com/nats-io/jwt/v2 v2.8.3/go.mod h1:OOY2rP/UU8tcfoqhbHmBKcNdpFMKvmxIkmFFa16M4wI=
|
||||
github.com/nats-io/nats-server/v2 v2.15.3 h1:IgHIKL4DYN9mEfwtPcdM39muvXG8v9FBADQn0f4Whs0=
|
||||
@@ -172,6 +174,10 @@ github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0t
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/samcharles93/ai-sdk v0.6.0 h1:ANHutwvl/K233Dkflc2vKT48qsXRT1iRwjL5S1Dm+jY=
|
||||
github.com/samcharles93/ai-sdk v0.6.0/go.mod h1:NNkiUZ2qfezDHhmF8zHibKsPgpU8b5jphDQ0n2t1KL0=
|
||||
github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0=
|
||||
github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
|
||||
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
|
||||
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
|
||||
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
|
||||
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
|
||||
github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY=
|
||||
@@ -187,6 +193,8 @@ github.com/tinylib/msgp v1.6.5 h1:iAH6XTP7BpzErjBZlujJQXxA+GmRi2YWs6M4KdLtNbE=
|
||||
github.com/tinylib/msgp v1.6.5/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
|
||||
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
|
||||
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0 h1:Tq+E65HaNbZTeqcLw6QUhsV+/EIWdkfUH2CQzcrlE5M=
|
||||
@@ -246,6 +254,8 @@ golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
|
||||
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
|
||||
golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE=
|
||||
golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s=
|
||||
golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a h1:Yqozs0FNPRoPGS4hNGlrNwRENWr5H5nVG9sN/f+5640=
|
||||
golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20261110000943-09e21b237f2c h1:ofk4SEqvpf6M5VWh88xRp42IYgdVOh7gffebnDj3OqU=
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
|
||||
"github.com/samcharles93/ai-sdk/chat"
|
||||
|
||||
protocol "github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
protocol "github.com/samcharles93/archie-core/internal/tools/provider/mcp"
|
||||
)
|
||||
|
||||
// DefaultSamplingMaxTokens bounds a server-requested completion when the
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec/modelloop"
|
||||
"github.com/samcharles93/archie-core/internal/domain/usage"
|
||||
"github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
mcp "github.com/samcharles93/archie-core/internal/tools/provider/mcp"
|
||||
)
|
||||
|
||||
// mcpSamplingHandler answers an MCP server's sampling/createMessage request
|
||||
@@ -53,12 +53,7 @@ func (b *server) mcpSamplingHandler() mcp.SamplingHandler {
|
||||
if err != nil {
|
||||
return mcp.SamplingResult{}, fmt.Errorf("mcp sampling: %w", err)
|
||||
}
|
||||
return mcp.SamplingResult{
|
||||
Model: model,
|
||||
Role: "assistant",
|
||||
Content: mcp.SamplingContent{Type: "text", Text: result.Text},
|
||||
StopReason: string(result.FinishReason),
|
||||
}, nil
|
||||
return mcp.SamplingResult{Model: model, Text: result.Text, StopReason: string(result.FinishReason)}, nil
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -22,10 +22,10 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/taskmcp"
|
||||
"github.com/samcharles93/archie-core/internal/plugin"
|
||||
"github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
minimaxtool "github.com/samcharles93/archie-core/internal/tools/minimax"
|
||||
toolprovider "github.com/samcharles93/archie-core/internal/tools/provider"
|
||||
builtintoolprovider "github.com/samcharles93/archie-core/internal/tools/provider/builtin"
|
||||
mcptoolprovider "github.com/samcharles93/archie-core/internal/tools/provider/mcp"
|
||||
"github.com/samcharles93/archie-core/internal/tools/sendfile"
|
||||
"github.com/samcharles93/archie-core/internal/tools/webfetch"
|
||||
)
|
||||
@@ -221,7 +221,7 @@ func isWithin(base, target string) bool {
|
||||
return rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
|
||||
}
|
||||
|
||||
func configuredMCPProvider(server config.MCPServer, workDir string, sampling mcp.SamplingHandler) (toolprovider.Engine, error) {
|
||||
func configuredMCPProvider(server config.MCPServer, workDir string, sampling mcptoolprovider.SamplingHandler) (toolprovider.Engine, error) {
|
||||
cacheDir := ""
|
||||
if workDir != "" {
|
||||
cacheDir = filepath.Join(workDir, "mcp-npm-cache")
|
||||
|
||||
@@ -272,9 +272,6 @@ type MCPServer struct {
|
||||
Headers map[string]string `toml:"headers" yaml:"headers" json:"headers,omitempty"`
|
||||
// SSEEndpoint is the GET URL for the server→client event stream.
|
||||
SSEEndpoint string `toml:"sse_endpoint" yaml:"sse_endpoint" json:"sse_endpoint,omitempty"`
|
||||
// MessageEndpoint is the POST URL for client→server messages. When
|
||||
// empty, the client discovers it from the server's "endpoint" SSE event.
|
||||
MessageEndpoint string `toml:"message_endpoint" yaml:"message_endpoint" json:"message_endpoint,omitempty"`
|
||||
|
||||
// ParallelToolCalls allows concurrent tool calls to this server. Default
|
||||
// false: one call at a time.
|
||||
|
||||
@@ -179,7 +179,6 @@ func runtimeToolConfigFrom(ctx context.Context, reader controlplanerpc.ResourceR
|
||||
URL: server.URL,
|
||||
Headers: headers[server.Name],
|
||||
SSEEndpoint: server.SSEEndpoint,
|
||||
MessageEndpoint: server.MessageEndpoint,
|
||||
ParallelToolCalls: parallelToolCalls,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -15,14 +15,13 @@ type toolSettings struct {
|
||||
}
|
||||
|
||||
type mcpServerSettings struct {
|
||||
Name string `json:"name"`
|
||||
Transport string `json:"transport"`
|
||||
Command string `json:"command,omitempty"`
|
||||
Args []string `json:"args,omitempty"`
|
||||
WorkDir string `json:"work_dir,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
SSEEndpoint string `json:"sse_endpoint,omitempty"`
|
||||
MessageEndpoint string `json:"message_endpoint,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Transport string `json:"transport"`
|
||||
Command string `json:"command,omitempty"`
|
||||
Args []string `json:"args,omitempty"`
|
||||
WorkDir string `json:"work_dir,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
SSEEndpoint string `json:"sse_endpoint,omitempty"`
|
||||
// ParallelToolCalls is nil when not stored, keeping the file's value.
|
||||
ParallelToolCalls *bool `json:"parallel_tool_calls,omitempty"`
|
||||
HeadersConfigured bool `json:"headers_configured"`
|
||||
@@ -49,7 +48,6 @@ func seedTools(cfg config.Config) any {
|
||||
WorkDir: server.WorkDir,
|
||||
URL: server.URL,
|
||||
SSEEndpoint: server.SSEEndpoint,
|
||||
MessageEndpoint: server.MessageEndpoint,
|
||||
ParallelToolCalls: ¶llelToolCalls,
|
||||
HeadersConfigured: len(server.Headers) > 0,
|
||||
})
|
||||
|
||||
@@ -5,11 +5,16 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
sdk "github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
"github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
toolprovider "github.com/samcharles93/archie-core/internal/tools/provider"
|
||||
mcptoolprovider "github.com/samcharles93/archie-core/internal/tools/provider/mcp"
|
||||
)
|
||||
@@ -22,7 +27,7 @@ type Set struct {
|
||||
Registry *tools.Registry
|
||||
}
|
||||
|
||||
type mcpProviderBuilder func(config.MCPServer, mcp.SamplingHandler) (toolprovider.Engine, string, error)
|
||||
type mcpProviderBuilder func(config.MCPServer, mcptoolprovider.SamplingHandler) (toolprovider.Engine, string, error)
|
||||
|
||||
// Start starts the configured MCP servers and registers their
|
||||
// tools. sampling answers sampling requests when non-nil. Returns nil with
|
||||
@@ -30,11 +35,11 @@ type mcpProviderBuilder func(config.MCPServer, mcp.SamplingHandler) (toolprovide
|
||||
func Start(
|
||||
ctx context.Context,
|
||||
servers []config.MCPServer,
|
||||
sampling mcp.SamplingHandler,
|
||||
sampling mcptoolprovider.SamplingHandler,
|
||||
log *slog.Logger,
|
||||
cacheDir string,
|
||||
) (*Set, error) {
|
||||
return startWith(ctx, servers, sampling, log, func(server config.MCPServer, sampling mcp.SamplingHandler) (toolprovider.Engine, string, error) {
|
||||
return startWith(ctx, servers, sampling, log, func(server config.MCPServer, sampling mcptoolprovider.SamplingHandler) (toolprovider.Engine, string, error) {
|
||||
return NewProvider(server, sampling, cacheDir)
|
||||
})
|
||||
}
|
||||
@@ -42,7 +47,7 @@ func Start(
|
||||
func startWith(
|
||||
ctx context.Context,
|
||||
servers []config.MCPServer,
|
||||
sampling mcp.SamplingHandler,
|
||||
sampling mcptoolprovider.SamplingHandler,
|
||||
log *slog.Logger,
|
||||
build mcpProviderBuilder,
|
||||
) (*Set, error) {
|
||||
@@ -87,7 +92,7 @@ func startWith(
|
||||
}
|
||||
|
||||
// NewProvider builds the same transport and tool names for chat and tasks.
|
||||
func NewProvider(server config.MCPServer, sampling mcp.SamplingHandler, cacheDir string) (toolprovider.Engine, string, error) {
|
||||
func NewProvider(server config.MCPServer, sampling mcptoolprovider.SamplingHandler, cacheDir string) (toolprovider.Engine, string, error) {
|
||||
name := strings.TrimSpace(server.Name)
|
||||
transportType := strings.ToLower(strings.TrimSpace(server.Transport))
|
||||
if transportType == "" {
|
||||
@@ -97,56 +102,81 @@ func NewProvider(server config.MCPServer, sampling mcp.SamplingHandler, cacheDir
|
||||
if name == "" {
|
||||
return nil, transportType, fmt.Errorf("MCP server name is required")
|
||||
}
|
||||
transport, err := mcpTransportForServer(name, transportType, server, cacheDir)
|
||||
connect, err := mcpConnector(name, transportType, server, cacheDir)
|
||||
if err != nil {
|
||||
return nil, transportType, err
|
||||
}
|
||||
return mcptoolprovider.New(name, transport, server.ParallelToolCalls, mcptoolprovider.WithSamplingHandler(sampling)), transportType, nil
|
||||
return mcptoolprovider.New(name, connect, server.ParallelToolCalls, sampling), transportType, nil
|
||||
}
|
||||
|
||||
func mcpTransportForServer(
|
||||
name string,
|
||||
transportType string,
|
||||
server config.MCPServer,
|
||||
cacheDir string,
|
||||
) (mcptoolprovider.LifecycleTransport, error) {
|
||||
func mcpConnector(name, transportType string, server config.MCPServer, cacheDir string) (mcptoolprovider.Connector, error) {
|
||||
switch transportType {
|
||||
case "stdio":
|
||||
command := strings.TrimSpace(server.Command)
|
||||
if command == "" {
|
||||
return nil, fmt.Errorf("MCP stdio server %q requires a command", name)
|
||||
}
|
||||
// Keep npx packages in the caller's cache.
|
||||
return mcp.NewStdioTransport(mcp.StdioTransportConfig{
|
||||
Command: command,
|
||||
Args: append([]string(nil), server.Args...),
|
||||
Dir: server.WorkDir,
|
||||
Env: mcp.NpmCacheEnv(command, cacheDir),
|
||||
}), nil
|
||||
args := append([]string(nil), server.Args...)
|
||||
return func(ctx context.Context) (sdk.Transport, error) {
|
||||
cmd := exec.CommandContext(ctx, command, args...) //nolint:gosec // G204: the operator configures the MCP server command.
|
||||
cmd.Dir = server.WorkDir
|
||||
cmd.Env = append(os.Environ(), npmCacheEnv(command, cacheDir)...)
|
||||
return &sdk.CommandTransport{Command: cmd}, nil
|
||||
}, nil
|
||||
case "http", "streamablehttp":
|
||||
url := strings.TrimSpace(server.URL)
|
||||
if url == "" {
|
||||
return nil, fmt.Errorf("MCP http server %q requires a url", name)
|
||||
}
|
||||
return mcp.NewHTTPTransport(mcp.HTTPTransportConfig{
|
||||
Endpoint: url,
|
||||
Headers: server.Headers,
|
||||
}), nil
|
||||
client := headerClient(server.Headers)
|
||||
return func(context.Context) (sdk.Transport, error) {
|
||||
return &sdk.StreamableClientTransport{Endpoint: url, HTTPClient: client}, nil
|
||||
}, nil
|
||||
case "sse":
|
||||
sseEndpoint := strings.TrimSpace(server.SSEEndpoint)
|
||||
if sseEndpoint == "" {
|
||||
endpoint := strings.TrimSpace(server.SSEEndpoint)
|
||||
if endpoint == "" {
|
||||
return nil, fmt.Errorf("MCP sse server %q requires an sse_endpoint", name)
|
||||
}
|
||||
return mcp.NewSSETransport(mcp.SSETransportConfig{
|
||||
SSEEndpoint: sseEndpoint,
|
||||
MessageEndpoint: strings.TrimSpace(server.MessageEndpoint),
|
||||
Headers: server.Headers,
|
||||
}), nil
|
||||
client := headerClient(server.Headers)
|
||||
return func(context.Context) (sdk.Transport, error) {
|
||||
return &sdk.SSEClientTransport{Endpoint: endpoint, HTTPClient: client}, nil
|
||||
}, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("%w: %s", errUnknownMCPTransport, transportType)
|
||||
}
|
||||
}
|
||||
|
||||
// npmCacheEnv points npx's package cache at cacheDir, so packages persist
|
||||
// across tasks. Empty unless the command is npx and cacheDir is set.
|
||||
func npmCacheEnv(command, cacheDir string) []string {
|
||||
if filepath.Base(command) != "npx" || cacheDir == "" {
|
||||
return nil
|
||||
}
|
||||
return []string{"NPM_CONFIG_CACHE=" + cacheDir, "NPM_CONFIG_PREFER_OFFLINE=true"}
|
||||
}
|
||||
|
||||
// headerClient sends the server's configured headers (auth, API keys) on
|
||||
// every request.
|
||||
func headerClient(headers map[string]string) *http.Client {
|
||||
if len(headers) == 0 {
|
||||
return http.DefaultClient
|
||||
}
|
||||
return &http.Client{Transport: headerTransport{headers: headers, base: http.DefaultTransport}}
|
||||
}
|
||||
|
||||
type headerTransport struct {
|
||||
headers map[string]string
|
||||
base http.RoundTripper
|
||||
}
|
||||
|
||||
func (t headerTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
r = r.Clone(r.Context())
|
||||
for k, v := range t.headers {
|
||||
r.Header.Set(k, v)
|
||||
}
|
||||
return t.base.RoundTrip(r)
|
||||
}
|
||||
|
||||
func startMCPProvider(
|
||||
ctx context.Context,
|
||||
name string,
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/usage"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
mcp "github.com/samcharles93/archie-core/internal/tools/provider/mcp"
|
||||
)
|
||||
|
||||
// SamplingHandler answers MCP sampling requests with the task's model.
|
||||
@@ -49,12 +49,7 @@ func SamplingHandler(llm *runtime.Runtime, cfg config.TaskConfig, record func(co
|
||||
if err != nil {
|
||||
return mcp.SamplingResult{}, fmt.Errorf("mcp sampling: %w", err)
|
||||
}
|
||||
return mcp.SamplingResult{
|
||||
Model: model,
|
||||
Role: "assistant",
|
||||
Content: mcp.SamplingContent{Type: "text", Text: result.Text},
|
||||
StopReason: string(result.FinishReason),
|
||||
}, nil
|
||||
return mcp.SamplingResult{Model: model, Text: result.Text, StopReason: string(result.FinishReason)}, nil
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/agentexec/modelloop"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/agentrun"
|
||||
protocol "github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
protocol "github.com/samcharles93/archie-core/internal/tools/provider/mcp"
|
||||
)
|
||||
|
||||
func TestSamplingKeepsTaskCredentialsAndUsage(t *testing.T) {
|
||||
@@ -51,7 +51,7 @@ func TestSamplingKeepsTaskCredentialsAndUsage(t *testing.T) {
|
||||
if os.Getenv("ARCHIE_SAMPLING_FIXTURE_KEY") != "instance-key" {
|
||||
t.Fatal("sampling changed process-wide credentials")
|
||||
}
|
||||
if !recorded || result.Model != "fixture/task-model" || result.Content.Text != "sampled" {
|
||||
if !recorded || result.Model != "fixture/task-model" || result.Text != "sampled" {
|
||||
t.Fatalf("sampling result %+v, recorded %v", result, recorded)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,263 +0,0 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
// protocolVersion is the MCP protocol version this client speaks.
|
||||
const protocolVersion = "2024-11-05"
|
||||
|
||||
// Transport sends requests and notifications to an MCP server.
|
||||
type Transport interface {
|
||||
Send(ctx context.Context, body []byte) ([]byte, error)
|
||||
Notify(ctx context.Context, body []byte) error
|
||||
}
|
||||
|
||||
// Client speaks the MCP JSON-RPC protocol (initialize, tools/list,
|
||||
// tools/call) over a [Transport]. It does not manage the transport's
|
||||
// lifecycle (Start/Stop) -- callers start the transport first, then
|
||||
// build a Client on top of it.
|
||||
type Client struct {
|
||||
transport Transport
|
||||
serverName string
|
||||
nextID atomic.Int64
|
||||
// callMu serializes tools/call to this server. Nil allows concurrent calls.
|
||||
callMu *sync.Mutex
|
||||
// samplingHandler answers server-initiated sampling/createMessage
|
||||
// requests. Set once at construction, so reading it from a transport
|
||||
// reader goroutine needs no lock. Nil means the method is refused.
|
||||
samplingHandler SamplingHandler
|
||||
}
|
||||
|
||||
// ClientOption adjusts a Client at construction.
|
||||
type ClientOption func(*Client)
|
||||
|
||||
// WithSamplingHandler answers server-initiated sampling/createMessage
|
||||
// requests from the supplied handler. Without it the client answers the
|
||||
// method with a JSON-RPC method-not-found error, per the MCP spec -- never
|
||||
// a silent drop.
|
||||
func WithSamplingHandler(handler SamplingHandler) ClientOption {
|
||||
return func(c *Client) { c.samplingHandler = handler }
|
||||
}
|
||||
|
||||
// NewClient builds a Client over transport. parallelToolCalls allows
|
||||
// concurrent tools/call. The client handles server-initiated requests when
|
||||
// the transport supports them.
|
||||
func NewClient(transport Transport, serverName string, parallelToolCalls bool, opts ...ClientOption) *Client {
|
||||
c := &Client{transport: transport, serverName: serverName}
|
||||
if !parallelToolCalls {
|
||||
c.callMu = &sync.Mutex{}
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(c)
|
||||
}
|
||||
if router, ok := transport.(serverRequestRouter); ok {
|
||||
router.SetServerRequestHandler(c.handleServerRequest)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// handleServerRequest answers sampling/createMessage and returns
|
||||
// method-not-found for anything else.
|
||||
func (c *Client) handleServerRequest(ctx context.Context, method string, params json.RawMessage) (json.RawMessage, *ErrorData) {
|
||||
if method != "sampling/createMessage" {
|
||||
return nil, &ErrorData{Code: ErrCodeMethodNotFound, Message: "method not found: " + method}
|
||||
}
|
||||
if c.samplingHandler == nil {
|
||||
return nil, &ErrorData{
|
||||
Code: ErrCodeMethodNotFound,
|
||||
Message: "sampling/createMessage is not supported: no sampling handler is configured",
|
||||
}
|
||||
}
|
||||
var req SamplingRequest
|
||||
if err := json.Unmarshal(params, &req); err != nil {
|
||||
return nil, &ErrorData{Code: ErrCodeInvalidParams, Message: "invalid sampling/createMessage params: " + err.Error()}
|
||||
}
|
||||
result, err := c.samplingHandler(ctx, req)
|
||||
if err != nil {
|
||||
return nil, &ErrorData{Code: ErrCodeInternal, Message: err.Error()}
|
||||
}
|
||||
body, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
return nil, &ErrorData{Code: ErrCodeInternal, Message: "marshal sampling result: " + err.Error()}
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// InitializeResult is the server's response to initialize.
|
||||
type InitializeResult struct {
|
||||
ProtocolVersion string `json:"protocolVersion"`
|
||||
ServerInfo ServerInfo `json:"serverInfo"`
|
||||
Capabilities Capabilities `json:"capabilities"`
|
||||
}
|
||||
|
||||
// ServerInfo identifies the MCP server implementation.
|
||||
type ServerInfo struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
|
||||
// Capabilities describes what the server supports. Fields are omitted
|
||||
// (left as raw presence checks) rather than fully modeled -- archie-core
|
||||
// only needs tool discovery today.
|
||||
type Capabilities struct {
|
||||
Tools json.RawMessage `json:"tools,omitempty"`
|
||||
}
|
||||
|
||||
// ToolSchema is one tool as advertised by tools/list.
|
||||
type ToolSchema struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
InputSchema tools.JSONSchema `json:"inputSchema"`
|
||||
Annotations struct {
|
||||
ReadOnlyHint bool `json:"readOnlyHint"`
|
||||
} `json:"annotations"`
|
||||
}
|
||||
|
||||
// ContentBlock is one block of a tools/call result. Per the MCP spec a
|
||||
// block is one of: text (Text set), image/audio (Data+MimeType set), or
|
||||
// resource (Resource set, itself either inline text or a base64 blob).
|
||||
type ContentBlock struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text,omitempty"`
|
||||
Data string `json:"data,omitempty"` // base64, for type "image"/"audio"
|
||||
MimeType string `json:"mimeType,omitempty"`
|
||||
Resource *ResourceContent `json:"resource,omitempty"`
|
||||
}
|
||||
|
||||
// ResourceContent is an embedded resource, for a ContentBlock of type
|
||||
// "resource". Exactly one of Text or Blob is set: Text for inline
|
||||
// textual resources (treated as plain text, not media), Blob
|
||||
// (base64-encoded) for binary resources (treated as media).
|
||||
type ResourceContent struct {
|
||||
URI string `json:"uri"`
|
||||
MimeType string `json:"mimeType,omitempty"`
|
||||
Text string `json:"text,omitempty"`
|
||||
Blob string `json:"blob,omitempty"`
|
||||
}
|
||||
|
||||
// CallToolResult is a tools/call result. IsError reports a tool-level
|
||||
// failure.
|
||||
type CallToolResult struct {
|
||||
Content []ContentBlock `json:"content"`
|
||||
IsError bool `json:"isError,omitempty"`
|
||||
}
|
||||
|
||||
// Initialize performs the MCP handshake: sends initialize, then the
|
||||
// notifications/initialized notification the spec requires after a
|
||||
// successful initialize response. Must be called once before ListTools
|
||||
// or CallTool.
|
||||
func (c *Client) Initialize(ctx context.Context) (InitializeResult, error) {
|
||||
params := map[string]any{
|
||||
"protocolVersion": protocolVersion,
|
||||
"capabilities": map[string]any{},
|
||||
"clientInfo": map[string]any{"name": "archie-core", "version": "1.0.0"},
|
||||
}
|
||||
var result InitializeResult
|
||||
if err := c.call(ctx, "initialize", params, &result); err != nil {
|
||||
return InitializeResult{}, fmt.Errorf("mcp: initialize %s: %w", c.serverName, err)
|
||||
}
|
||||
if err := c.notify(ctx, "notifications/initialized", nil); err != nil {
|
||||
return InitializeResult{}, fmt.Errorf("mcp: notifications/initialized %s: %w", c.serverName, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ListTools returns every tool the server advertises, following the
|
||||
// cursor-based pagination the spec defines until the server stops
|
||||
// returning nextCursor.
|
||||
func (c *Client) ListTools(ctx context.Context) ([]ToolSchema, error) {
|
||||
var all []ToolSchema
|
||||
cursor := ""
|
||||
for {
|
||||
params := map[string]any{}
|
||||
if cursor != "" {
|
||||
params["cursor"] = cursor
|
||||
}
|
||||
var page struct {
|
||||
Tools []ToolSchema `json:"tools"`
|
||||
NextCursor string `json:"nextCursor,omitempty"`
|
||||
}
|
||||
if err := c.call(ctx, "tools/list", params, &page); err != nil {
|
||||
return nil, fmt.Errorf("mcp: tools/list %s: %w", c.serverName, err)
|
||||
}
|
||||
all = append(all, page.Tools...)
|
||||
if page.NextCursor == "" {
|
||||
return all, nil
|
||||
}
|
||||
cursor = page.NextCursor
|
||||
}
|
||||
}
|
||||
|
||||
// CallTool calls a tool. A Go error means the call failed; a tool failure is
|
||||
// CallToolResult.IsError.
|
||||
func (c *Client) CallTool(ctx context.Context, name string, arguments map[string]any) (CallToolResult, error) {
|
||||
if c.callMu != nil {
|
||||
c.callMu.Lock()
|
||||
defer c.callMu.Unlock()
|
||||
}
|
||||
|
||||
params := map[string]any{"name": name, "arguments": arguments}
|
||||
var result CallToolResult
|
||||
if err := c.call(ctx, "tools/call", params, &result); err != nil {
|
||||
return CallToolResult{}, fmt.Errorf("mcp: tools/call %s.%s: %w", c.serverName, name, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// call sends a JSON-RPC request and decodes its result into out. It
|
||||
// returns an error for a transport failure, a JSON-RPC error response,
|
||||
// or a malformed result payload.
|
||||
func (c *Client) call(ctx context.Context, method string, params, out any) error {
|
||||
id := c.nextID.Add(1)
|
||||
req := struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID int64 `json:"id"`
|
||||
Method string `json:"method"`
|
||||
Params any `json:"params,omitempty"`
|
||||
}{JSONRPC: "2.0", ID: id, Method: method, Params: params}
|
||||
|
||||
body, err := json.Marshal(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal request: %w", err)
|
||||
}
|
||||
respBody, err := c.transport.Send(ctx, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var resp Message
|
||||
if err := json.Unmarshal(respBody, &resp); err != nil {
|
||||
return fmt.Errorf("unmarshal response: %w", err)
|
||||
}
|
||||
if resp.Error != nil {
|
||||
return fmt.Errorf("rpc error %d: %s", resp.Error.Code, resp.Error.Message)
|
||||
}
|
||||
if out == nil || len(resp.Result) == 0 {
|
||||
return nil
|
||||
}
|
||||
if err := json.Unmarshal(resp.Result, out); err != nil {
|
||||
return fmt.Errorf("unmarshal result: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// notify sends a JSON-RPC notification (no id, no response expected).
|
||||
func (c *Client) notify(ctx context.Context, method string, params any) error {
|
||||
req := struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
Method string `json:"method"`
|
||||
Params any `json:"params,omitempty"`
|
||||
}{JSONRPC: "2.0", Method: method, Params: params}
|
||||
|
||||
body, err := json.Marshal(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal notification: %w", err)
|
||||
}
|
||||
return c.transport.Notify(ctx, body)
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// maxMessageSize is the maximum allowed MCP message body size (4 MB).
|
||||
const maxMessageSize = 4 * 1024 * 1024
|
||||
|
||||
// writeMessage writes one newline-delimited JSON-RPC message. MCP stdio uses
|
||||
// one compact JSON object per line; Content-Length framing belongs to LSP and
|
||||
// is not understood by servers built with the official MCP SDKs.
|
||||
func writeMessage(w io.Writer, data []byte) error {
|
||||
if _, err := w.Write(data); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := io.WriteString(w, "\n")
|
||||
return err
|
||||
}
|
||||
|
||||
// readMessage reads one newline-delimited JSON-RPC message from r, which must
|
||||
// be a reused *bufio.Reader.
|
||||
func readMessage(r io.Reader) ([]byte, error) {
|
||||
br, ok := r.(*bufio.Reader)
|
||||
if !ok {
|
||||
// Caller passed a plain io.Reader without managing the
|
||||
// buffer -- warn them once and wrap anyway. Multi-message
|
||||
// streams will lose data after the first read.
|
||||
br = bufio.NewReader(r)
|
||||
}
|
||||
return readMessageFromBufio(br)
|
||||
}
|
||||
|
||||
func readMessageFromBufio(br *bufio.Reader) ([]byte, error) {
|
||||
message := make([]byte, 0, 4096)
|
||||
for {
|
||||
chunk, err := br.ReadSlice('\n')
|
||||
if len(message)+len(chunk) > maxMessageSize+1 {
|
||||
return nil, fmt.Errorf("message exceeds maximum %d bytes", maxMessageSize)
|
||||
}
|
||||
message = append(message, chunk...)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
if !errors.Is(err, bufio.ErrBufferFull) {
|
||||
if err == io.EOF && len(message) > 0 {
|
||||
return nil, fmt.Errorf("read message: missing newline: %w", io.ErrUnexpectedEOF)
|
||||
}
|
||||
return nil, fmt.Errorf("read message: %w", err)
|
||||
}
|
||||
}
|
||||
message = message[:len(message)-1]
|
||||
if len(message) > 0 && message[len(message)-1] == '\r' {
|
||||
message = message[:len(message)-1]
|
||||
}
|
||||
return message, nil
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package mcp
|
||||
|
||||
import "path/filepath"
|
||||
|
||||
// NpmCacheEnv returns env vars pointing npx's package cache at cacheDir. Empty
|
||||
// unless command's base name is npx and cacheDir is set.
|
||||
func NpmCacheEnv(command, cacheDir string) []string {
|
||||
if filepath.Base(command) != "npx" || cacheDir == "" {
|
||||
return nil
|
||||
}
|
||||
return []string{
|
||||
"NPM_CONFIG_CACHE=" + cacheDir,
|
||||
"NPM_CONFIG_PREFER_OFFLINE=true",
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
// JSON-RPC 2.0 error codes used when answering a server-initiated request.
|
||||
// These are spec-defined and part of the MCP wire contract: the server
|
||||
// distinguishes "this client cannot do that" from "the request was
|
||||
// malformed" from "the handler failed" by the code, not the message.
|
||||
const (
|
||||
// ErrCodeMethodNotFound is returned when this client has no idea how
|
||||
// to answer the requested method, including a sampling request when no
|
||||
// sampling handler is configured. It is never a silent drop.
|
||||
ErrCodeMethodNotFound = -32601
|
||||
// ErrCodeInvalidParams is returned when the request's params cannot be
|
||||
// decoded into the method's shape.
|
||||
ErrCodeInvalidParams = -32602
|
||||
// ErrCodeInternal is returned when the configured handler ran but
|
||||
// failed. The message carries the handler's own error text.
|
||||
ErrCodeInternal = -32603
|
||||
)
|
||||
|
||||
// SamplingContent is one content block in a sampling message. The MCP
|
||||
// sampling method sends text today; the type field is carried so an
|
||||
// unsupported block is rejected explicitly rather than silently emptied.
|
||||
type SamplingContent struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text,omitempty"`
|
||||
}
|
||||
|
||||
// SamplingMessage is one conversation message supplied by the MCP server.
|
||||
type SamplingMessage struct {
|
||||
Role string `json:"role"`
|
||||
Content SamplingContent `json:"content"`
|
||||
}
|
||||
|
||||
// SamplingRequest is the params of a sampling/createMessage request: the
|
||||
// server asks this client to run a completion on its behalf.
|
||||
type SamplingRequest struct {
|
||||
Messages []SamplingMessage `json:"messages"`
|
||||
SystemPrompt string `json:"systemPrompt,omitempty"`
|
||||
MaxTokens int `json:"maxTokens,omitempty"`
|
||||
Temperature *float64 `json:"temperature,omitempty"`
|
||||
StopSequences []string `json:"stopSequences,omitempty"`
|
||||
}
|
||||
|
||||
// SamplingResult is the result of a sampling/createMessage request.
|
||||
type SamplingResult struct {
|
||||
Model string `json:"model"`
|
||||
Role string `json:"role"`
|
||||
Content SamplingContent `json:"content"`
|
||||
StopReason string `json:"stopReason,omitempty"`
|
||||
}
|
||||
|
||||
// SamplingHandler answers a server's sampling request. Errors become JSON-RPC
|
||||
// internal errors.
|
||||
type SamplingHandler func(ctx context.Context, req SamplingRequest) (SamplingResult, error)
|
||||
|
||||
// ServerRequestHandler answers one request the MCP server sent to this
|
||||
// client. A non-nil *ErrorData becomes a JSON-RPC error response;
|
||||
// otherwise result becomes the success response. The MCP wire contract
|
||||
// permits both, and a client must never drop a request it cannot answer.
|
||||
type ServerRequestHandler func(ctx context.Context, method string, params json.RawMessage) (json.RawMessage, *ErrorData)
|
||||
|
||||
// serverRequestRouter is implemented by transports that can receive
|
||||
// server-initiated requests over their server→client channel. The
|
||||
// stateless HTTP transport cannot (it has no persistent stream) and
|
||||
// therefore does not implement it.
|
||||
type serverRequestRouter interface {
|
||||
SetServerRequestHandler(handler ServerRequestHandler)
|
||||
}
|
||||
@@ -1,719 +0,0 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ── Errors ──────────────────────────────────────────────────────────────
|
||||
|
||||
var (
|
||||
// ErrTransportStopped is returned when attempting to send on a stopped transport.
|
||||
ErrTransportStopped = errors.New("mcp: transport is stopped")
|
||||
// ErrTransportError is returned when the transport is in a permanent error state.
|
||||
ErrTransportError = errors.New("mcp: transport is in error state")
|
||||
// ErrMissingCommand is returned when Start is called with an empty command.
|
||||
ErrMissingCommand = errors.New("mcp: Command is required")
|
||||
)
|
||||
|
||||
// ── Config ──────────────────────────────────────────────────────────────
|
||||
|
||||
// StdioTransportConfig configures the stdio MCP transport.
|
||||
type StdioTransportConfig struct {
|
||||
// Command is the MCP server executable path. Required.
|
||||
Command string
|
||||
// Args are passed to the server executable.
|
||||
Args []string
|
||||
// Dir is the subprocess working directory. Empty inherits the daemon's
|
||||
// working directory.
|
||||
Dir string
|
||||
// Env is additional environment variables in NAME=value format.
|
||||
// The subprocess inherits the parent process environment; these are added
|
||||
// on top of it.
|
||||
Env []string
|
||||
|
||||
// InitialBackoff is the starting delay before the first auto-restart.
|
||||
// Default: 500ms.
|
||||
InitialBackoff time.Duration
|
||||
// MaxBackoff caps the exponential backoff delay. Default: 30s.
|
||||
MaxBackoff time.Duration
|
||||
// MaxRetries caps restart attempts. 0 means unlimited (default).
|
||||
MaxRetries int
|
||||
// SendTimeout is how long to wait for the write to complete (not the
|
||||
// response). 0 means no timeout.
|
||||
SendTimeout time.Duration
|
||||
|
||||
// ShutdownGrace is how long Stop waits for the subprocess to exit
|
||||
// after an interrupt signal before forcibly killing it.
|
||||
// Default: 5s.
|
||||
ShutdownGrace time.Duration
|
||||
}
|
||||
|
||||
func (c StdioTransportConfig) effectiveInitialBackoff() time.Duration {
|
||||
if c.InitialBackoff <= 0 {
|
||||
return 500 * time.Millisecond
|
||||
}
|
||||
return c.InitialBackoff
|
||||
}
|
||||
|
||||
func (c StdioTransportConfig) effectiveMaxBackoff() time.Duration {
|
||||
if c.MaxBackoff <= 0 {
|
||||
return 30 * time.Second
|
||||
}
|
||||
return c.MaxBackoff
|
||||
}
|
||||
|
||||
func (c StdioTransportConfig) effectiveShutdownGrace() time.Duration {
|
||||
if c.ShutdownGrace <= 0 {
|
||||
return 5 * time.Second
|
||||
}
|
||||
return c.ShutdownGrace
|
||||
}
|
||||
|
||||
// ── Transport ───────────────────────────────────────────────────────────
|
||||
|
||||
// StdioTransport runs an MCP server subprocess, exchanging newline-delimited
|
||||
// JSON-RPC over stdin/stdout, and restarts it with backoff when it dies.
|
||||
type StdioTransport struct {
|
||||
config StdioTransportConfig
|
||||
|
||||
mu sync.Mutex
|
||||
state TransportState
|
||||
cmd *exec.Cmd
|
||||
stdin io.WriteCloser
|
||||
|
||||
// writeMu serialises writes to stdin so that header and body from
|
||||
// different goroutines are not interleaved.
|
||||
writeMu sync.Mutex
|
||||
|
||||
// pending maps message IDs (as raw JSON) to response channels.
|
||||
pending map[string]chan []byte
|
||||
|
||||
// stopCh is closed by Stop(). Background goroutines select on this.
|
||||
stopCh chan struct{}
|
||||
|
||||
// readerWg tracks the reader goroutine so Stop can wait for it.
|
||||
readerWg sync.WaitGroup
|
||||
|
||||
// crashCount is incremented on each unexpected subprocess death and is
|
||||
// used to compute the exponential backoff delay. Reset to 0 on explicit
|
||||
// Start (not on auto-restart), so repeated crash loops produce
|
||||
// increasingly long backoff intervals up to MaxBackoff.
|
||||
crashCount int
|
||||
|
||||
// startupFailures tracks consecutive spawn failures (command not found,
|
||||
// permissions, etc.). Reset to 0 on a successful spawn. When MaxRetries
|
||||
// is set and this exceeds it, the transport enters StateError.
|
||||
startupFailures int
|
||||
|
||||
// serverRequestHandler answers requests the server sends to this client
|
||||
// (sampling/createMessage). Nil until a Client registers itself.
|
||||
serverRequestHandler ServerRequestHandler
|
||||
// handlerCancel ends the lifecycle context handed to the server-request
|
||||
// handler, so an in-flight sampling completion is not left running after
|
||||
// the transport is gone. The handler context itself is carried through
|
||||
// the reader call chain rather than stored.
|
||||
handlerCancel context.CancelFunc
|
||||
// serverRequestWg tracks in-flight handler goroutines so Stop can wait
|
||||
// for their responses to be written before the transport goes away.
|
||||
serverRequestWg sync.WaitGroup
|
||||
}
|
||||
|
||||
// SetServerRequestHandler registers the handler for server-initiated
|
||||
// requests. It implements serverRequestRouter.
|
||||
func (t *StdioTransport) SetServerRequestHandler(handler ServerRequestHandler) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.serverRequestHandler = handler
|
||||
}
|
||||
|
||||
// NewStdioTransport creates a new transport with the given config.
|
||||
// Callers must call [*StdioTransport.Start] before sending messages.
|
||||
func NewStdioTransport(config StdioTransportConfig) *StdioTransport {
|
||||
return &StdioTransport{
|
||||
config: config,
|
||||
state: StateStopped,
|
||||
pending: make(map[string]chan []byte),
|
||||
}
|
||||
}
|
||||
|
||||
// State returns the current transport state.
|
||||
func (t *StdioTransport) State() TransportState {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
return t.state
|
||||
}
|
||||
|
||||
// Start spawns the MCP server subprocess and begins reading responses.
|
||||
// It returns after the process has started successfully. If the context
|
||||
// is cancelled before the process is ready, Start returns the context error.
|
||||
func (t *StdioTransport) Start(ctx context.Context) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if t.config.Command == "" {
|
||||
return ErrMissingCommand
|
||||
}
|
||||
|
||||
t.mu.Lock()
|
||||
if t.state == StateRunning {
|
||||
t.mu.Unlock()
|
||||
return fmt.Errorf("mcp: already running")
|
||||
}
|
||||
if t.state == StateStarting {
|
||||
t.mu.Unlock()
|
||||
return fmt.Errorf("mcp: already starting")
|
||||
}
|
||||
if t.state == StateStopping {
|
||||
t.mu.Unlock()
|
||||
return fmt.Errorf("mcp: stop in progress")
|
||||
}
|
||||
t.state = StateStarting
|
||||
// Create a fresh stop channel for this lifecycle. If we're restarting
|
||||
// from Error state, the previous stop channel is already closed.
|
||||
if t.stopCh != nil {
|
||||
select {
|
||||
case <-t.stopCh:
|
||||
default:
|
||||
close(t.stopCh)
|
||||
}
|
||||
}
|
||||
t.stopCh = make(chan struct{})
|
||||
// The reader (and thus every server-request handler it dispatches) runs
|
||||
// on a cancelable context derived from the caller's, decoupled from the
|
||||
// caller's own cancellation the same way the subprocess is. Stop cancels
|
||||
// it so an in-flight sampling completion ends with the transport.
|
||||
handlerCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
|
||||
t.handlerCancel = cancel
|
||||
// Reset crash and failure counters on explicit user start.
|
||||
t.crashCount = 0
|
||||
t.startupFailures = 0
|
||||
t.mu.Unlock()
|
||||
|
||||
return t.startSubprocess(handlerCtx)
|
||||
}
|
||||
|
||||
// stopSubprocess kills the current subprocess and waits for it to exit.
|
||||
// Must be called with t.mu NOT held (it waits for process exit).
|
||||
func (t *StdioTransport) stopSubprocess() {
|
||||
t.mu.Lock()
|
||||
cmd := t.cmd
|
||||
stdin := t.stdin
|
||||
t.cmd = nil
|
||||
t.stdin = nil
|
||||
t.mu.Unlock()
|
||||
|
||||
// Close stdin first to signal the server to exit.
|
||||
if stdin != nil {
|
||||
_ = stdin.Close()
|
||||
}
|
||||
|
||||
// Kill the process.
|
||||
if cmd != nil && cmd.Process != nil {
|
||||
// Try graceful shutdown via SIGTERM first.
|
||||
_ = cmd.Process.Signal(os.Interrupt)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
_ = cmd.Wait()
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(t.config.effectiveShutdownGrace()):
|
||||
_ = cmd.Process.Kill()
|
||||
<-done
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Stop gracefully shuts down the transport. It kills the subprocess,
|
||||
// cancels pending requests, and waits for background goroutines. Calling
|
||||
// Stop on a stopped or never-started transport is a no-op.
|
||||
func (t *StdioTransport) Stop(_ context.Context) error {
|
||||
t.mu.Lock()
|
||||
if t.state == StateStopped {
|
||||
t.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
// Set StateStopping and cancel the transport context atomically, in the
|
||||
// same critical section. Splitting these across two lock acquisitions
|
||||
// opens a window where a concurrent Start() could see a state it isn't
|
||||
// guarding against and race a fresh subprocess against this shutdown.
|
||||
t.state = StateStopping
|
||||
if t.stopCh != nil {
|
||||
select {
|
||||
case <-t.stopCh:
|
||||
default:
|
||||
close(t.stopCh)
|
||||
}
|
||||
}
|
||||
cancel := t.handlerCancel
|
||||
t.mu.Unlock()
|
||||
|
||||
if cancel != nil {
|
||||
cancel()
|
||||
}
|
||||
|
||||
// Kill the subprocess.
|
||||
t.stopSubprocess()
|
||||
|
||||
// Wait for the reader goroutine to finish, then for any in-flight
|
||||
// server-request handler it dispatched. Waiting for the reader first
|
||||
// guarantees no further handler goroutines can be added.
|
||||
t.readerWg.Wait()
|
||||
t.serverRequestWg.Wait()
|
||||
|
||||
// Fail all pending requests.
|
||||
t.mu.Lock()
|
||||
for id, ch := range t.pending {
|
||||
close(ch)
|
||||
delete(t.pending, id)
|
||||
}
|
||||
t.state = StateStopped
|
||||
t.mu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Send writes a request and waits for the response with the same id.
|
||||
func (t *StdioTransport) Send(ctx context.Context, body []byte) ([]byte, error) {
|
||||
// Extract the message ID from the body for response correlation.
|
||||
msgID, err := extractMessageID(body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mcp: extract id: %w", err)
|
||||
}
|
||||
|
||||
t.mu.Lock()
|
||||
|
||||
if t.state != StateRunning {
|
||||
t.mu.Unlock()
|
||||
return nil, ErrTransportStopped
|
||||
}
|
||||
|
||||
stdin := t.stdin // capture under lock
|
||||
|
||||
// Register the pending response channel.
|
||||
ch := make(chan []byte, 1)
|
||||
t.pending[msgID] = ch
|
||||
|
||||
t.mu.Unlock()
|
||||
|
||||
// Write the framed message under writeMu to prevent interleaving with
|
||||
// concurrent Send calls on the same pipe.
|
||||
t.writeMu.Lock()
|
||||
err = writeMessageWithTimeout(stdin, body, t.config.SendTimeout)
|
||||
t.writeMu.Unlock()
|
||||
|
||||
if err != nil {
|
||||
// Cleanup the pending entry on write failure.
|
||||
t.mu.Lock()
|
||||
// Check if someone else already consumed the channel (e.g., reader
|
||||
// error handling closed it). Only close if it's still ours.
|
||||
if ch2, ok := t.pending[msgID]; ok && ch2 == ch {
|
||||
close(ch)
|
||||
delete(t.pending, msgID)
|
||||
}
|
||||
t.mu.Unlock()
|
||||
return nil, fmt.Errorf("mcp: write: %w", err)
|
||||
}
|
||||
|
||||
// Wait for the response.
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
// De-register on context cancellation -- no cleanup needed on the
|
||||
// channel since the reader will close it when it tries to deliver.
|
||||
t.mu.Lock()
|
||||
delete(t.pending, msgID)
|
||||
t.mu.Unlock()
|
||||
return nil, ctx.Err()
|
||||
|
||||
case resp, ok := <-ch:
|
||||
if !ok {
|
||||
// Channel closed -- the transport was stopped or the subprocess
|
||||
// crashed before we got a response.
|
||||
return nil, errors.New("mcp: transport closed while waiting for response")
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Notify writes a notification without waiting for a response.
|
||||
func (t *StdioTransport) Notify(ctx context.Context, body []byte) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
t.mu.Lock()
|
||||
if t.state != StateRunning {
|
||||
t.mu.Unlock()
|
||||
return ErrTransportStopped
|
||||
}
|
||||
stdin := t.stdin // capture under lock
|
||||
t.mu.Unlock()
|
||||
|
||||
t.writeMu.Lock()
|
||||
defer t.writeMu.Unlock()
|
||||
if err := writeMessageWithTimeout(stdin, body, t.config.SendTimeout); err != nil {
|
||||
return fmt.Errorf("mcp: notify write: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ── Internal subprocess management ─────────────────────────────────────
|
||||
|
||||
// startSubprocess spawns the MCP server subprocess and starts the reader
|
||||
// goroutine. Must be called without t.mu held.
|
||||
func (t *StdioTransport) startSubprocess(ctx context.Context) error {
|
||||
cmd, stdin, stdout, err := t.spawnProcess(ctx)
|
||||
if err != nil {
|
||||
t.mu.Lock()
|
||||
t.state = StateError
|
||||
t.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
return t.commitSpawnedProcess(ctx, cmd, stdin, stdout, false)
|
||||
}
|
||||
|
||||
// commitSpawnedProcess installs a spawned subprocess and starts its reader,
|
||||
// unless Stop has already run, in which case the process is killed.
|
||||
// resetStartupFailures resets the spawn-failure counter.
|
||||
func (t *StdioTransport) commitSpawnedProcess(ctx context.Context, cmd *exec.Cmd, stdin io.WriteCloser, stdout *bufio.Reader, resetStartupFailures bool) error {
|
||||
t.mu.Lock()
|
||||
if t.isStopped() {
|
||||
t.state = StateStopped
|
||||
t.mu.Unlock()
|
||||
_ = stdin.Close()
|
||||
if cmd.Process != nil {
|
||||
_ = cmd.Process.Kill()
|
||||
_ = cmd.Wait()
|
||||
}
|
||||
return errTransportStopped
|
||||
}
|
||||
t.cmd = cmd
|
||||
t.stdin = stdin
|
||||
t.state = StateRunning
|
||||
if resetStartupFailures {
|
||||
t.startupFailures = 0
|
||||
}
|
||||
t.mu.Unlock()
|
||||
|
||||
// Start the reader goroutine.
|
||||
t.readerWg.Add(1)
|
||||
go t.runReader(ctx, stdout)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// spawnProcess creates and starts the subprocess. Returns the cmd,
|
||||
// stdin writer, and buffered stdout reader.
|
||||
func (t *StdioTransport) spawnProcess(ctx context.Context) (*exec.Cmd, io.WriteCloser, *bufio.Reader, error) {
|
||||
cmd := exec.CommandContext(ctx, t.config.Command, t.config.Args...)
|
||||
cmd.Env = append(os.Environ(), t.config.Env...)
|
||||
cmd.Dir = t.config.Dir
|
||||
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
return nil, nil, nil, fmt.Errorf("stdin pipe: %w", err)
|
||||
}
|
||||
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
_ = stdin.Close()
|
||||
return nil, nil, nil, fmt.Errorf("stdout pipe: %w", err)
|
||||
}
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
_ = stdin.Close()
|
||||
_ = stdout.Close()
|
||||
return nil, nil, nil, fmt.Errorf("start: %w", err)
|
||||
}
|
||||
|
||||
return cmd, stdin, bufio.NewReader(stdout), nil
|
||||
}
|
||||
|
||||
// runReader loops reading newline-delimited JSON messages from the
|
||||
// subprocess's stdout, routing responses to the matching pending
|
||||
// channels. On error (process crash, pipe close), it initiates the
|
||||
// auto-restart sequence.
|
||||
func (t *StdioTransport) runReader(ctx context.Context, reader *bufio.Reader) {
|
||||
defer t.readerWg.Done()
|
||||
|
||||
for {
|
||||
body, err := readMessage(reader)
|
||||
if err != nil {
|
||||
// The subprocess is dead or the pipe is broken. Attempt restart
|
||||
// if we weren't asked to stop.
|
||||
t.mu.Lock()
|
||||
cancelled := t.isStopped()
|
||||
shuttingDown := t.state == StateStopping || t.state == StateStopped
|
||||
t.mu.Unlock()
|
||||
|
||||
if cancelled || shuttingDown {
|
||||
return
|
||||
}
|
||||
|
||||
t.handleProcessDeath(ctx)
|
||||
return
|
||||
}
|
||||
|
||||
t.deliverResponse(ctx, body)
|
||||
}
|
||||
}
|
||||
|
||||
// deliverResponse routes one message read from the subprocess's stdout. A
|
||||
// response goes to the caller waiting on its id; a server-initiated request
|
||||
// goes to the registered handler; a notification has no response to route.
|
||||
func (t *StdioTransport) deliverResponse(ctx context.Context, body []byte) {
|
||||
var msg Message
|
||||
if err := json.Unmarshal(body, &msg); err != nil {
|
||||
return
|
||||
}
|
||||
if msg.IsRequest() {
|
||||
t.dispatchServerRequest(ctx, msg)
|
||||
return
|
||||
}
|
||||
if len(msg.ID) == 0 {
|
||||
// A server notification carries no response to route.
|
||||
return
|
||||
}
|
||||
|
||||
msgID := string(msg.ID)
|
||||
t.mu.Lock()
|
||||
ch, ok := t.pending[msgID]
|
||||
if ok {
|
||||
delete(t.pending, msgID)
|
||||
}
|
||||
t.mu.Unlock()
|
||||
|
||||
if ok {
|
||||
// Non-blocking send: if the caller has already timed out, the
|
||||
// channel might still be in the map but has a full buffer.
|
||||
// Since we use a buffered channel (cap 1), this should succeed.
|
||||
select {
|
||||
case ch <- body:
|
||||
default:
|
||||
// Caller is no longer waiting -- discard.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// dispatchServerRequest runs the registered handler for a server-initiated
|
||||
// request without blocking the reader, and writes its response back. A
|
||||
// missing handler is answered method-not-found, never dropped: the server is
|
||||
// blocked on a reply for its own request id.
|
||||
func (t *StdioTransport) dispatchServerRequest(ctx context.Context, msg Message) {
|
||||
t.mu.Lock()
|
||||
handler := t.serverRequestHandler
|
||||
t.mu.Unlock()
|
||||
|
||||
t.serverRequestWg.Go(func() {
|
||||
var (
|
||||
result json.RawMessage
|
||||
rpcErr *ErrorData
|
||||
)
|
||||
if handler == nil {
|
||||
rpcErr = &ErrorData{Code: ErrCodeMethodNotFound, Message: "method not found: " + msg.Method}
|
||||
} else {
|
||||
result, rpcErr = handler(ctx, msg.Method, msg.Params)
|
||||
}
|
||||
t.respondToServerRequest(msg.ID, result, rpcErr)
|
||||
})
|
||||
}
|
||||
|
||||
// respondToServerRequest writes a JSON-RPC response for a server-initiated
|
||||
// request back to the subprocess's stdin.
|
||||
func (t *StdioTransport) respondToServerRequest(id, result json.RawMessage, rpcErr *ErrorData) {
|
||||
data, err := json.Marshal(Message{JSONRPC: "2.0", ID: id, Result: result, Error: rpcErr})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
t.mu.Lock()
|
||||
stdin := t.stdin
|
||||
running := t.state == StateRunning
|
||||
t.mu.Unlock()
|
||||
if !running || stdin == nil {
|
||||
return
|
||||
}
|
||||
|
||||
t.writeMu.Lock()
|
||||
defer t.writeMu.Unlock()
|
||||
// The error is unreportable here: the transport's only job is to answer
|
||||
// the server's own request, and a failed write is exactly a subprocess
|
||||
// that has already gone away (its reader handles the restart).
|
||||
_ = writeMessageWithTimeout(stdin, data, t.config.SendTimeout)
|
||||
}
|
||||
|
||||
// handleProcessDeath is called when the reader detects the subprocess
|
||||
// has died. It increments crashCount for backoff, transitions to Starting,
|
||||
// closes pending channels, and initiates the auto-restart sequence.
|
||||
func (t *StdioTransport) handleProcessDeath(ctx context.Context) {
|
||||
t.mu.Lock()
|
||||
if t.state != StateRunning {
|
||||
t.mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
t.crashCount++
|
||||
t.state = StateStarting
|
||||
cmd := t.cmd
|
||||
t.cmd = nil
|
||||
t.stdin = nil
|
||||
|
||||
// Fail all pending requests -- the subprocess is gone.
|
||||
t.failAllPendingLocked()
|
||||
t.mu.Unlock()
|
||||
|
||||
if cmd != nil {
|
||||
_ = cmd.Wait()
|
||||
}
|
||||
|
||||
// Attempt restart (outside lock because it waits).
|
||||
t.attemptRestart(ctx)
|
||||
}
|
||||
|
||||
// failAllPendingLocked closes all pending response channels with an error.
|
||||
// Must hold t.mu.
|
||||
func (t *StdioTransport) failAllPendingLocked() {
|
||||
for id, ch := range t.pending {
|
||||
close(ch)
|
||||
delete(t.pending, id)
|
||||
}
|
||||
}
|
||||
|
||||
// attemptRestart restarts a crashed subprocess with exponential backoff until
|
||||
// it starts, the transport stops, or spawn failures reach MaxRetries.
|
||||
func (t *StdioTransport) attemptRestart(ctx context.Context) {
|
||||
for {
|
||||
// Check preconditions under lock.
|
||||
t.mu.Lock()
|
||||
if t.isStopped() {
|
||||
t.state = StateStopped
|
||||
t.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if t.state != StateStarting {
|
||||
t.mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
backoff := t.computeBackoffLocked()
|
||||
|
||||
// Check spawn-failure limit (not crash limit -- crash loops are
|
||||
// bounded by the growing backoff cap).
|
||||
if t.config.MaxRetries > 0 && t.startupFailures >= t.config.MaxRetries {
|
||||
t.state = StateError
|
||||
t.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if t.config.MaxRetries > 0 && t.crashCount >= t.config.MaxRetries {
|
||||
// Crash loops (spawn succeeds, process immediately dies) also
|
||||
// count toward the retry limit so we don't restart forever.
|
||||
t.state = StateError
|
||||
t.mu.Unlock()
|
||||
return
|
||||
}
|
||||
t.mu.Unlock()
|
||||
|
||||
// Wait for the backoff period, but abort if the transport is stopped.
|
||||
timer := time.NewTimer(backoff)
|
||||
select {
|
||||
case <-t.stopCh:
|
||||
timer.Stop()
|
||||
t.mu.Lock()
|
||||
t.state = StateStopped
|
||||
t.mu.Unlock()
|
||||
return
|
||||
case <-timer.C:
|
||||
}
|
||||
|
||||
// Try to start the subprocess.
|
||||
cmd, stdin, stdout, err := t.spawnProcess(ctx)
|
||||
if err != nil {
|
||||
t.mu.Lock()
|
||||
t.startupFailures++
|
||||
t.mu.Unlock()
|
||||
continue
|
||||
}
|
||||
|
||||
// Success -- commit via the same guarded path startSubprocess uses,
|
||||
// so a concurrent Stop() that cancelled the context while
|
||||
// spawnProcess was in flight discards this subprocess instead of
|
||||
// clobbering the Stopped state Stop() already reported.
|
||||
_ = t.commitSpawnedProcess(ctx, cmd, stdin, stdout, true)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// computeBackoffLocked returns the exponential backoff delay based on
|
||||
// the current crashCount. Must hold t.mu.
|
||||
func (t *StdioTransport) computeBackoffLocked() time.Duration {
|
||||
d := t.config.effectiveInitialBackoff()
|
||||
for i := 1; i < t.crashCount; i++ {
|
||||
d *= 2
|
||||
if d > t.config.effectiveMaxBackoff() {
|
||||
return t.config.effectiveMaxBackoff()
|
||||
}
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// writeMessageWithTimeout writes a framed message, giving up after timeout. A
|
||||
// non-positive timeout waits indefinitely.
|
||||
func writeMessageWithTimeout(w io.Writer, data []byte, timeout time.Duration) error {
|
||||
if timeout <= 0 {
|
||||
return writeMessage(w, data)
|
||||
}
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
errCh <- writeMessage(w, data)
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-errCh:
|
||||
return err
|
||||
case <-time.After(timeout):
|
||||
return fmt.Errorf("mcp: write timed out after %s", timeout)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
// isStopped returns true if the transport stop channel has been closed.
|
||||
// Must be called with t.mu held or from a goroutine that doesn't need
|
||||
// the lock for ordering.
|
||||
func (t *StdioTransport) isStopped() bool {
|
||||
select {
|
||||
case <-t.stopCh:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// errTransportStopped is returned by the lifecycle context when the
|
||||
// transport is stopped.
|
||||
var errTransportStopped = errors.New("mcp: transport stopped")
|
||||
|
||||
// extractMessageID extracts the "id" field from a JSON body as a raw JSON
|
||||
// string. This is used as the key for correlating requests with responses.
|
||||
// A missing "id" returns an empty string (for notifications, which don't
|
||||
// expect responses).
|
||||
func extractMessageID(body []byte) (string, error) {
|
||||
var raw struct {
|
||||
ID json.RawMessage `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &raw); err != nil {
|
||||
return "", fmt.Errorf("parse id: %w", err)
|
||||
}
|
||||
return string(raw.ID), nil
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// HTTPTransportConfig configures the HTTP/StreamableHTTP MCP transport.
|
||||
type HTTPTransportConfig struct {
|
||||
// Endpoint is the URL of the MCP server (e.g. "https://mcp.example.com/mcp").
|
||||
// Required.
|
||||
Endpoint string
|
||||
// Headers are additional HTTP headers sent with every request (e.g.
|
||||
// Authorization, custom API keys).
|
||||
Headers map[string]string
|
||||
// Timeout is the per-request timeout. Default: 30s.
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
func (c HTTPTransportConfig) effectiveTimeout() time.Duration {
|
||||
if c.Timeout <= 0 {
|
||||
return 30 * time.Second
|
||||
}
|
||||
return c.Timeout
|
||||
}
|
||||
|
||||
// HTTPTransport is a stateless HTTP Transport: each Send is a POST. It cannot
|
||||
// receive server-initiated requests.
|
||||
type HTTPTransport struct {
|
||||
config HTTPTransportConfig
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
// NewHTTPTransport creates a new HTTP transport with the given config.
|
||||
func NewHTTPTransport(config HTTPTransportConfig) *HTTPTransport {
|
||||
return &HTTPTransport{
|
||||
config: config,
|
||||
client: &http.Client{Timeout: config.effectiveTimeout()},
|
||||
}
|
||||
}
|
||||
|
||||
// Send posts a JSON-RPC request body to the server endpoint and returns the
|
||||
// response body. The response body must be a valid JSON-RPC response.
|
||||
func (t *HTTPTransport) Send(ctx context.Context, body []byte) ([]byte, error) {
|
||||
resp, err := t.do(ctx, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
// Read up to 4 KB of the error body for diagnostics.
|
||||
discard := io.LimitReader(resp.Body, 4096)
|
||||
msg, _ := io.ReadAll(discard)
|
||||
return nil, fmt.Errorf("mcp: HTTP %d: %s", resp.StatusCode, string(msg))
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mcp: read response body: %w", err)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// Notify posts a JSON-RPC notification body to the server and discards the
|
||||
// response. Notifications carry no "id" and never receive a reply.
|
||||
func (t *HTTPTransport) Notify(ctx context.Context, body []byte) error {
|
||||
resp, err := t.do(ctx, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Drain and close the response body to return the connection to the pool.
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
// do sends a POST request with the given body and returns the HTTP response.
|
||||
func (t *HTTPTransport) do(ctx context.Context, body []byte) (*http.Response, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, t.config.Endpoint, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mcp: build request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json, text/event-stream")
|
||||
for k, v := range t.config.Headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
resp, err := t.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mcp: %w", err)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// Start is a no-op: HTTP transport is always ready.
|
||||
func (t *HTTPTransport) Start(_ context.Context) error { return nil }
|
||||
|
||||
// Stop is a no-op: HTTP transport has no persistent resources to release.
|
||||
func (t *HTTPTransport) Stop(_ context.Context) error { return nil }
|
||||
|
||||
// State always returns StateRunning: HTTP is stateless, so the transport is
|
||||
// always considered ready.
|
||||
func (t *HTTPTransport) State() TransportState { return StateRunning }
|
||||
|
||||
// Compile-time interface check.
|
||||
var _ Transport = (*HTTPTransport)(nil)
|
||||
@@ -1,581 +0,0 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SSETransportConfig configures the SSE MCP transport.
|
||||
type SSETransportConfig struct {
|
||||
// SSEEndpoint is the GET URL for the server→client event stream (e.g.
|
||||
// "https://mcp.example.com/sse"). Required.
|
||||
SSEEndpoint string
|
||||
// MessageEndpoint is the POST URL for client messages. Empty discovers it
|
||||
// from the server's "endpoint" event.
|
||||
MessageEndpoint string
|
||||
// Headers are additional HTTP headers sent with every request.
|
||||
Headers map[string]string
|
||||
// ReconnectBackoff is the initial delay before the first reconnect
|
||||
// after the SSE stream drops. Default: 1s.
|
||||
ReconnectBackoff time.Duration
|
||||
// MaxReconnectBackoff caps the exponential backoff delay. Default: 30s.
|
||||
MaxReconnectBackoff time.Duration
|
||||
// POSTTimeout is the timeout for each POST request to the message
|
||||
// endpoint. Default: 30s.
|
||||
POSTTimeout time.Duration
|
||||
}
|
||||
|
||||
func (c SSETransportConfig) effectiveReconnectBackoff() time.Duration {
|
||||
if c.ReconnectBackoff <= 0 {
|
||||
return time.Second
|
||||
}
|
||||
return c.ReconnectBackoff
|
||||
}
|
||||
|
||||
func (c SSETransportConfig) effectiveMaxReconnectBackoff() time.Duration {
|
||||
if c.MaxReconnectBackoff <= 0 {
|
||||
return 30 * time.Second
|
||||
}
|
||||
return c.MaxReconnectBackoff
|
||||
}
|
||||
|
||||
func (c SSETransportConfig) effectivePOSTTimeout() time.Duration {
|
||||
if c.POSTTimeout <= 0 {
|
||||
return 30 * time.Second
|
||||
}
|
||||
return c.POSTTimeout
|
||||
}
|
||||
|
||||
// SSETransport implements [Transport] over MCP SSE. It maintains a
|
||||
// long-lived GET connection for server→client events and sends
|
||||
// client→server messages via HTTP POST. Responses to [Send] are
|
||||
// correlated with the matching SSE "message" event by JSON-RPC ID.
|
||||
type SSETransport struct {
|
||||
config SSETransportConfig
|
||||
|
||||
mu sync.Mutex
|
||||
state TransportState
|
||||
|
||||
// messageEndpoint is the actual POST URL the server told us to use,
|
||||
// discovered from the endpoint event (or the config fallback).
|
||||
messageEndpoint string
|
||||
|
||||
pending map[string]chan []byte
|
||||
|
||||
// stopCh is closed by Stop(). Background goroutines select on this.
|
||||
stopCh chan struct{}
|
||||
|
||||
// lifecycleCancel cancels the lifecycle context handed to the background
|
||||
// reader and reconnect goroutines. Stop calls it so an in-flight reconnect
|
||||
// HTTP request can be interrupted immediately instead of blocking Stop
|
||||
// until the OS-level connect/read gives up.
|
||||
lifecycleCancel context.CancelFunc
|
||||
|
||||
// The SSE reader goroutine.
|
||||
readerWg sync.WaitGroup
|
||||
// Track HTTP response body so Stop can close it.
|
||||
respBody io.Closer
|
||||
|
||||
// serverRequestHandler answers requests the server sends to this client
|
||||
// (sampling/createMessage). Nil until a Client registers itself.
|
||||
serverRequestHandler ServerRequestHandler
|
||||
// serverRequestWg tracks in-flight handler goroutines so Stop waits for
|
||||
// their responses to be posted before the connection is closed. The
|
||||
// handler context is the SSE lifecycle context, carried through the
|
||||
// reader call chain and cancelled by Stop.
|
||||
serverRequestWg sync.WaitGroup
|
||||
}
|
||||
|
||||
// SetServerRequestHandler registers the handler for server-initiated
|
||||
// requests. It implements serverRequestRouter.
|
||||
func (t *SSETransport) SetServerRequestHandler(handler ServerRequestHandler) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.serverRequestHandler = handler
|
||||
}
|
||||
|
||||
// NewSSETransport creates a new SSE transport with the given config.
|
||||
// Callers must call [*SSETransport.Start] before sending messages.
|
||||
func NewSSETransport(config SSETransportConfig) *SSETransport {
|
||||
return &SSETransport{
|
||||
config: config,
|
||||
state: StateStopped,
|
||||
pending: map[string]chan []byte{},
|
||||
}
|
||||
}
|
||||
|
||||
// Start establishes the SSE connection and waits for the server's endpoint
|
||||
// event so the caller knows the transport is ready.
|
||||
func (t *SSETransport) Start(ctx context.Context) error {
|
||||
t.mu.Lock()
|
||||
if t.state == StateRunning {
|
||||
t.mu.Unlock()
|
||||
return fmt.Errorf("mcp sse: already running")
|
||||
}
|
||||
t.state = StateStarting
|
||||
t.stopCh = make(chan struct{})
|
||||
lifecycleCtx, cancel := context.WithCancel(ctx)
|
||||
t.lifecycleCancel = cancel
|
||||
t.messageEndpoint = t.config.MessageEndpoint // fallback; endpoint event overrides
|
||||
t.mu.Unlock()
|
||||
|
||||
return t.connect(lifecycleCtx)
|
||||
}
|
||||
|
||||
// Stop closes the SSE connection, fails pending requests, and transitions
|
||||
// to StateStopped. Calling Stop on a stopped transport is a no-op.
|
||||
func (t *SSETransport) Stop(_ context.Context) error {
|
||||
t.mu.Lock()
|
||||
if t.state == StateStopped {
|
||||
t.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
t.state = StateStopping
|
||||
if t.stopCh != nil {
|
||||
select {
|
||||
case <-t.stopCh:
|
||||
default:
|
||||
close(t.stopCh)
|
||||
}
|
||||
}
|
||||
if t.lifecycleCancel != nil {
|
||||
t.lifecycleCancel()
|
||||
}
|
||||
if t.respBody != nil {
|
||||
_ = t.respBody.Close()
|
||||
t.respBody = nil
|
||||
}
|
||||
t.mu.Unlock()
|
||||
|
||||
t.readerWg.Wait()
|
||||
|
||||
// The reader is done, so no further handler goroutines can be added;
|
||||
// wait for the responses of any already dispatched.
|
||||
t.serverRequestWg.Wait()
|
||||
|
||||
t.mu.Lock()
|
||||
for id, ch := range t.pending {
|
||||
close(ch)
|
||||
delete(t.pending, id)
|
||||
}
|
||||
t.state = StateStopped
|
||||
t.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Send posts a JSON-RPC request to the message endpoint and waits for the
|
||||
// matching response to arrive through the SSE event stream, correlated by
|
||||
// JSON-RPC message ID.
|
||||
func (t *SSETransport) Send(ctx context.Context, body []byte) ([]byte, error) {
|
||||
msgID, err := extractMessageID(body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mcp sse: extract id: %w", err)
|
||||
}
|
||||
|
||||
t.mu.Lock()
|
||||
if t.state != StateRunning {
|
||||
t.mu.Unlock()
|
||||
return nil, fmt.Errorf("mcp sse: transport is not running")
|
||||
}
|
||||
ch := make(chan []byte, 1)
|
||||
t.pending[msgID] = ch
|
||||
t.mu.Unlock()
|
||||
|
||||
defer func() {
|
||||
t.mu.Lock()
|
||||
delete(t.pending, msgID)
|
||||
t.mu.Unlock()
|
||||
}()
|
||||
|
||||
if err := t.postJSON(ctx, body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case resp, ok := <-ch:
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("mcp sse: transport closed while waiting for response")
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Notify posts a JSON-RPC notification to the message endpoint without
|
||||
// waiting for a response (notifications have no "id" by definition).
|
||||
func (t *SSETransport) Notify(ctx context.Context, body []byte) error {
|
||||
t.mu.Lock()
|
||||
if t.state != StateRunning {
|
||||
t.mu.Unlock()
|
||||
return fmt.Errorf("mcp sse: transport is not running")
|
||||
}
|
||||
t.mu.Unlock()
|
||||
return t.postJSON(ctx, body)
|
||||
}
|
||||
|
||||
// ── Internal connection management ───────────────────────────────────────
|
||||
|
||||
// connect establishes the SSE GET connection and blocks until the
|
||||
// endpoint event arrives (or the context is cancelled).
|
||||
func (t *SSETransport) connect(ctx context.Context) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, t.config.SSEEndpoint, nil)
|
||||
if err != nil {
|
||||
_ = t.setError(fmt.Errorf("mcp sse: build GET request: %w", err))
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Accept", "text/event-stream")
|
||||
req.Header.Set("Cache-Control", "no-cache")
|
||||
for k, v := range t.config.Headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
_ = t.setError(fmt.Errorf("mcp sse: connect: %w", err))
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
_ = resp.Body.Close()
|
||||
err := fmt.Errorf("mcp sse: server returned %d", resp.StatusCode)
|
||||
_ = t.setError(err)
|
||||
return err
|
||||
}
|
||||
|
||||
t.mu.Lock()
|
||||
t.respBody = resp.Body
|
||||
t.mu.Unlock()
|
||||
|
||||
// Read the endpoint event (the first event the server sends).
|
||||
reader := bufio.NewReader(resp.Body)
|
||||
msgURL, err := readEndpointEvent(reader)
|
||||
if err != nil {
|
||||
_ = resp.Body.Close()
|
||||
_ = t.setError(fmt.Errorf("mcp sse: read endpoint event: %w", err))
|
||||
return err
|
||||
}
|
||||
if msgURL != "" {
|
||||
t.mu.Lock()
|
||||
t.messageEndpoint = msgURL
|
||||
t.mu.Unlock()
|
||||
}
|
||||
|
||||
t.mu.Lock()
|
||||
t.state = StateRunning
|
||||
t.mu.Unlock()
|
||||
|
||||
// Start the background SSE event reader.
|
||||
t.readerWg.Add(1)
|
||||
go t.runReader(ctx, resp.Body, reader)
|
||||
return nil
|
||||
}
|
||||
|
||||
// runReader loops reading SSE events from the stream, routing
|
||||
// "message" events to the corresponding pending channel.
|
||||
func (t *SSETransport) runReader(ctx context.Context, body io.Closer, reader *bufio.Reader) {
|
||||
defer t.readerWg.Done()
|
||||
defer func() { _ = body.Close() }()
|
||||
|
||||
for {
|
||||
event, data, err := readSSEEvent(reader)
|
||||
if err != nil {
|
||||
// Stream closed or errored. Attempt reconnect.
|
||||
t.mu.Lock()
|
||||
cancelled := t.isStopped()
|
||||
stopping := t.state == StateStopping || t.state == StateStopped
|
||||
t.mu.Unlock()
|
||||
if cancelled || stopping {
|
||||
return
|
||||
}
|
||||
t.reconnect(ctx)
|
||||
return
|
||||
}
|
||||
switch event {
|
||||
case "message":
|
||||
t.deliverMessage(ctx, data)
|
||||
case "endpoint":
|
||||
// Server sent a new endpoint URL (session refresh).
|
||||
// Already handled on connect; accept mid-stream updates too.
|
||||
t.mu.Lock()
|
||||
if data != "" {
|
||||
t.messageEndpoint = data
|
||||
}
|
||||
t.mu.Unlock()
|
||||
default:
|
||||
// ping, heartbeat, etc. — ignore.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// reconnect attempts to re-establish the SSE connection with exponential
|
||||
// backoff. On success, the reader goroutine restarts.
|
||||
func (t *SSETransport) reconnect(ctx context.Context) {
|
||||
backoff := t.config.effectiveReconnectBackoff()
|
||||
for {
|
||||
t.mu.Lock()
|
||||
if t.isStopped() {
|
||||
t.state = StateStopped
|
||||
t.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if t.state != StateRunning {
|
||||
t.mu.Unlock()
|
||||
return
|
||||
}
|
||||
t.mu.Unlock()
|
||||
|
||||
timer := time.NewTimer(backoff)
|
||||
select {
|
||||
case <-t.stopCh:
|
||||
timer.Stop()
|
||||
return
|
||||
case <-timer.C:
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, t.config.SSEEndpoint, nil)
|
||||
if err != nil {
|
||||
backoff = nextBackoff(backoff, t.config.effectiveMaxReconnectBackoff())
|
||||
continue
|
||||
}
|
||||
req.Header.Set("Accept", "text/event-stream")
|
||||
req.Header.Set("Cache-Control", "no-cache")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
backoff = nextBackoff(backoff, t.config.effectiveMaxReconnectBackoff())
|
||||
continue
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
_ = resp.Body.Close()
|
||||
backoff = nextBackoff(backoff, t.config.effectiveMaxReconnectBackoff())
|
||||
continue
|
||||
}
|
||||
|
||||
reader := bufio.NewReader(resp.Body)
|
||||
msgURL, err := readEndpointEvent(reader)
|
||||
if err != nil {
|
||||
_ = resp.Body.Close()
|
||||
backoff = nextBackoff(backoff, t.config.effectiveMaxReconnectBackoff())
|
||||
continue
|
||||
}
|
||||
|
||||
// Guarded commit: Stop may have won while the reconnect GET was in
|
||||
// flight. Do not install a reader (or a response body Stop has already
|
||||
// missed) once Stop has closed stopCh.
|
||||
t.mu.Lock()
|
||||
if t.isStopped() || t.state != StateRunning {
|
||||
t.state = StateStopped
|
||||
t.mu.Unlock()
|
||||
_ = resp.Body.Close()
|
||||
return
|
||||
}
|
||||
if msgURL != "" {
|
||||
t.messageEndpoint = msgURL
|
||||
}
|
||||
t.respBody = resp.Body
|
||||
t.readerWg.Add(1)
|
||||
t.mu.Unlock()
|
||||
|
||||
go t.runReader(ctx, resp.Body, reader)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func nextBackoff(d, ceiling time.Duration) time.Duration {
|
||||
d *= 2
|
||||
if d > ceiling {
|
||||
return ceiling
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// ── Delivery ─────────────────────────────────────────────────────────────
|
||||
|
||||
// deliverMessage routes an incoming SSE message event. A response goes to
|
||||
// the caller waiting on its id; a server-initiated request goes to the
|
||||
// registered handler; a notification has no response to route.
|
||||
func (t *SSETransport) deliverMessage(ctx context.Context, data string) {
|
||||
var msg Message
|
||||
if err := json.Unmarshal([]byte(data), &msg); err != nil {
|
||||
return
|
||||
}
|
||||
if msg.IsRequest() {
|
||||
t.dispatchServerRequest(ctx, msg)
|
||||
return
|
||||
}
|
||||
if len(msg.ID) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
msgID := string(msg.ID)
|
||||
t.mu.Lock()
|
||||
ch, ok := t.pending[msgID]
|
||||
if ok {
|
||||
delete(t.pending, msgID)
|
||||
}
|
||||
t.mu.Unlock()
|
||||
|
||||
if ok {
|
||||
select {
|
||||
case ch <- []byte(data):
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// dispatchServerRequest runs the registered handler for a server-initiated
|
||||
// request without blocking the reader, and posts its response back to the
|
||||
// message endpoint.
|
||||
func (t *SSETransport) dispatchServerRequest(ctx context.Context, msg Message) {
|
||||
t.mu.Lock()
|
||||
handler := t.serverRequestHandler
|
||||
t.mu.Unlock()
|
||||
|
||||
t.serverRequestWg.Go(func() {
|
||||
var (
|
||||
result json.RawMessage
|
||||
rpcErr *ErrorData
|
||||
)
|
||||
if handler == nil {
|
||||
rpcErr = &ErrorData{Code: ErrCodeMethodNotFound, Message: "method not found: " + msg.Method}
|
||||
} else {
|
||||
result, rpcErr = handler(ctx, msg.Method, msg.Params)
|
||||
}
|
||||
body, err := json.Marshal(Message{JSONRPC: "2.0", ID: msg.ID, Result: result, Error: rpcErr})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// Unreportable here: the server's request has no other answer path,
|
||||
// and a failed POST is a connection the reader is already
|
||||
// reconnecting.
|
||||
_ = t.postJSON(ctx, body)
|
||||
})
|
||||
}
|
||||
|
||||
// ── POST ─────────────────────────────────────────────────────────────────
|
||||
|
||||
// postJSON sends a JSON-RPC body to the message endpoint via POST.
|
||||
func (t *SSETransport) postJSON(ctx context.Context, body []byte) error {
|
||||
t.mu.Lock()
|
||||
endpoint := t.messageEndpoint
|
||||
t.mu.Unlock()
|
||||
|
||||
if endpoint == "" {
|
||||
return fmt.Errorf("mcp sse: no message endpoint (awaiting server's endpoint event)")
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return fmt.Errorf("mcp sse: build POST: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
for k, v := range t.config.Headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: t.config.effectivePOSTTimeout()}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mcp sse: post: %w", err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
msg, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
||||
return fmt.Errorf("mcp sse: HTTP %d: %s", resp.StatusCode, string(msg))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ── State helpers ────────────────────────────────────────────────────────
|
||||
|
||||
func (t *SSETransport) setError(err error) error {
|
||||
t.mu.Lock()
|
||||
t.state = StateError
|
||||
t.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
// ── SSE parsing ──────────────────────────────────────────────────────────
|
||||
|
||||
// readEndpointEvent reads the mandatory first event from an SSE stream.
|
||||
// Per the MCP SSE spec, the server MUST send an "endpoint" event as its
|
||||
// first message, whose data payload is the URL the client should POST to.
|
||||
func readEndpointEvent(r *bufio.Reader) (string, error) {
|
||||
event, data, err := readSSEEvent(r)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if event != "endpoint" {
|
||||
return "", fmt.Errorf("expected endpoint event, got %q", event)
|
||||
}
|
||||
return strings.TrimSpace(data), nil
|
||||
}
|
||||
|
||||
// readSSEEvent reads one SSE event and returns its type and data. Comment
|
||||
// lines are skipped; multiple data lines are joined with newlines.
|
||||
func readSSEEvent(r *bufio.Reader) (event, data string, err error) {
|
||||
var dataLines []string
|
||||
for {
|
||||
line, err := r.ReadString('\n')
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
line = strings.TrimRight(line, "\r\n")
|
||||
|
||||
if line == "" {
|
||||
// Empty line terminates the event.
|
||||
if event == "" {
|
||||
event = "message" // default event type per SSE spec
|
||||
}
|
||||
return event, strings.Join(dataLines, "\n"), nil
|
||||
}
|
||||
if strings.HasPrefix(line, ":") {
|
||||
continue // comment
|
||||
}
|
||||
if after, ok := strings.CutPrefix(line, "event: "); ok {
|
||||
event = after
|
||||
continue
|
||||
}
|
||||
if after, ok := strings.CutPrefix(line, "event:"); ok {
|
||||
event = strings.TrimSpace(after)
|
||||
continue
|
||||
}
|
||||
if after, ok := strings.CutPrefix(line, "data: "); ok {
|
||||
dataLines = append(dataLines, after)
|
||||
continue
|
||||
}
|
||||
if after, ok := strings.CutPrefix(line, "data:"); ok {
|
||||
dataLines = append(dataLines, strings.TrimSpace(after))
|
||||
continue
|
||||
}
|
||||
// Other fields (id:, retry:) are ignored.
|
||||
}
|
||||
}
|
||||
|
||||
// isStopped returns true if the transport stop channel has been closed.
|
||||
func (t *SSETransport) isStopped() bool {
|
||||
select {
|
||||
case <-t.stopCh:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// State returns the current transport state.
|
||||
func (t *SSETransport) State() TransportState {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
return t.state
|
||||
}
|
||||
|
||||
// Compile-time interface check.
|
||||
var _ Transport = (*SSETransport)(nil)
|
||||
@@ -1,74 +0,0 @@
|
||||
// Package mcp implements an MCP client over stdio, HTTP and SSE transports.
|
||||
package mcp
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// TransportState represents the lifecycle state of a transport.
|
||||
type TransportState int
|
||||
|
||||
const (
|
||||
// StateStopped is the initial and final state -- no subprocess running.
|
||||
StateStopped TransportState = iota
|
||||
// StateStarting means a subprocess has been spawned and is being
|
||||
// initialised. The transport is not yet usable for requests.
|
||||
StateStarting
|
||||
// StateRunning means the subprocess is healthy and ready to handle requests.
|
||||
StateRunning
|
||||
// StateStopping means the subprocess is being shut down gracefully.
|
||||
StateStopping
|
||||
// StateError means the subprocess has failed and retries have been
|
||||
// exhausted (or the error was unrecoverable). A manual Stop or Start
|
||||
// is required to leave this state.
|
||||
StateError
|
||||
)
|
||||
|
||||
func (s TransportState) String() string {
|
||||
switch s {
|
||||
case StateStopped:
|
||||
return "stopped"
|
||||
case StateStarting:
|
||||
return "starting"
|
||||
case StateRunning:
|
||||
return "running"
|
||||
case StateStopping:
|
||||
return "stopping"
|
||||
case StateError:
|
||||
return "error"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
// Message is a JSON-RPC 2.0 message. Exactly one of Method, Result, or
|
||||
// Error should be set depending on whether this is a request, response,
|
||||
// or notification.
|
||||
type Message struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID json.RawMessage `json:"id,omitempty"`
|
||||
Method string `json:"method,omitempty"`
|
||||
Params json.RawMessage `json:"params,omitempty"`
|
||||
Result json.RawMessage `json:"result,omitempty"`
|
||||
Error *ErrorData `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// ErrorData represents a JSON-RPC 2.0 error object.
|
||||
type ErrorData struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Data any `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
// IsRequest returns true when this is a request message (has an ID and method).
|
||||
func (m Message) IsRequest() bool {
|
||||
return len(m.ID) > 0 && m.Method != ""
|
||||
}
|
||||
|
||||
// IsResponse returns true when this is a response message (has an ID but no method).
|
||||
func (m Message) IsResponse() bool {
|
||||
return len(m.ID) > 0 && m.Method == ""
|
||||
}
|
||||
|
||||
// IsNotification returns true when this is a notification (no ID, has method).
|
||||
func (m Message) IsNotification() bool {
|
||||
return len(m.ID) == 0 && m.Method != ""
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
// Package mcp adapts one MCP transport to the typed tool-provider family.
|
||||
// Package mcp adapts one MCP server, through the official MCP SDK, to the
|
||||
// typed tool-provider family.
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
@@ -12,38 +13,68 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/lifecycle"
|
||||
sdk "github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/plugin"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
protocol "github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
)
|
||||
|
||||
const cleanupTimeout = 10 * time.Second
|
||||
|
||||
// LifecycleTransport is the narrow MCP transport lifecycle used by Provider.
|
||||
type LifecycleTransport interface {
|
||||
protocol.Transport
|
||||
Start(context.Context) error
|
||||
Stop(context.Context) error
|
||||
State() protocol.TransportState
|
||||
// SamplingContent is one content block of a sampling message. Type is carried
|
||||
// so a non-text block is refused explicitly rather than emptied.
|
||||
type SamplingContent struct {
|
||||
Type string
|
||||
Text string
|
||||
}
|
||||
|
||||
// SamplingMessage is one conversation message the server supplied.
|
||||
type SamplingMessage struct {
|
||||
Role string
|
||||
Content SamplingContent
|
||||
}
|
||||
|
||||
// SamplingRequest is a server's request for a completion on its behalf.
|
||||
type SamplingRequest struct {
|
||||
Messages []SamplingMessage
|
||||
SystemPrompt string
|
||||
MaxTokens int
|
||||
// Temperature is nil when the server left it to the client.
|
||||
Temperature *float64
|
||||
}
|
||||
|
||||
// SamplingResult is the completion returned to the server.
|
||||
type SamplingResult struct {
|
||||
Model string
|
||||
Text string
|
||||
StopReason string
|
||||
}
|
||||
|
||||
// SamplingHandler answers a server's sampling request. An error becomes a
|
||||
// JSON-RPC error for that request alone.
|
||||
type SamplingHandler func(context.Context, SamplingRequest) (SamplingResult, error)
|
||||
|
||||
// Connector returns a fresh transport for one session. A command transport
|
||||
// wraps an exec.Cmd, which runs once, so every connect needs a new one.
|
||||
type Connector func(context.Context) (sdk.Transport, error)
|
||||
|
||||
// Provider owns one configured MCP server and its discovered tools.
|
||||
type Provider struct {
|
||||
mu sync.RWMutex
|
||||
name string
|
||||
segment string
|
||||
connect Connector
|
||||
client *sdk.Client
|
||||
|
||||
name string
|
||||
segment string
|
||||
transport LifecycleTransport
|
||||
client *protocol.Client
|
||||
// connectMu serializes connecting, so a slow handshake never holds mu.
|
||||
connectMu sync.Mutex
|
||||
mu sync.Mutex
|
||||
// session is the live connection, or nil before Start, after Stop, and
|
||||
// once the server has gone away; a call then reconnects.
|
||||
session *sdk.ClientSession
|
||||
stopped bool
|
||||
|
||||
// parallelToolCalls is the configured server's opt-in to concurrent
|
||||
// tools/call. It is handed to the client Start builds: the client is
|
||||
// what serializes calls, so the flag has to reach it or the server
|
||||
// stays serialized.
|
||||
parallelToolCalls bool
|
||||
// callMu serializes tools/call unless the server opted into parallel
|
||||
// calls. Nil allows concurrent calls.
|
||||
callMu *sync.Mutex
|
||||
|
||||
// mediaDir is the root directory binary content blocks (images, audio,
|
||||
// resource blobs) are written under, created lazily on the first
|
||||
@@ -52,40 +83,75 @@ type Provider struct {
|
||||
// mediaCallSeq disambiguates concurrent calls to the same tool so
|
||||
// their written media files never share a directory.
|
||||
mediaCallSeq atomic.Int64
|
||||
|
||||
// samplingHandler answers server-initiated sampling/createMessage
|
||||
// requests. Nil leaves the method refused, which is the clean failure
|
||||
// for a server that asks without a sampling handler configured.
|
||||
samplingHandler protocol.SamplingHandler
|
||||
}
|
||||
|
||||
// Option adjusts a Provider at construction.
|
||||
type Option func(*Provider)
|
||||
|
||||
// WithSamplingHandler answers server-initiated sampling/createMessage
|
||||
// requests from the supplied handler. It is the daemon's configured model
|
||||
// path, so an MCP server's sampling request is answered by the same model
|
||||
// a chat turn uses rather than a second provider client.
|
||||
func WithSamplingHandler(handler protocol.SamplingHandler) Option {
|
||||
return func(p *Provider) { p.samplingHandler = handler }
|
||||
}
|
||||
|
||||
// New creates an MCP tool provider. parallelToolCalls mirrors the
|
||||
// configured server's own flag: false (the default) has the provider's
|
||||
// client serialize tools/call, true lets them overlap.
|
||||
func New(name string, transport LifecycleTransport, parallelToolCalls bool, opts ...Option) *Provider {
|
||||
// New creates an MCP tool provider. parallelToolCalls mirrors the configured
|
||||
// server's own flag: false (the default) serializes tools/call. A nil
|
||||
// sampling handler leaves sampling unadvertised, so the SDK refuses it.
|
||||
func New(name string, connect Connector, parallelToolCalls bool, sampling SamplingHandler) *Provider {
|
||||
p := &Provider{
|
||||
name: strings.TrimSpace(name),
|
||||
segment: sanitizeToolSegment(name),
|
||||
transport: transport,
|
||||
parallelToolCalls: parallelToolCalls,
|
||||
name: strings.TrimSpace(name),
|
||||
segment: sanitizeToolSegment(name),
|
||||
connect: connect,
|
||||
client: sdk.NewClient(&sdk.Implementation{Name: "archie-core", Version: "1.0.0"},
|
||||
&sdk.ClientOptions{CreateMessageHandler: sdkSampling(sampling)}), //nolint:staticcheck // SA1019: see sdkSampling.
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(p)
|
||||
if !parallelToolCalls {
|
||||
p.callMu = &sync.Mutex{}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// sdkSampling adapts handler to the SDK. Sampling is deprecated from protocol
|
||||
// 2026-07-28 (SEP-2577) but servers still use it in the deprecation window;
|
||||
// this is the only code that touches the deprecated types.
|
||||
//
|
||||
//nolint:staticcheck // SA1019: MCP sampling is deprecated, still supported.
|
||||
func sdkSampling(handler SamplingHandler) func(context.Context, *sdk.CreateMessageRequest) (*sdk.CreateMessageResult, error) {
|
||||
if handler == nil {
|
||||
return nil
|
||||
}
|
||||
return func(ctx context.Context, request *sdk.CreateMessageRequest) (*sdk.CreateMessageResult, error) {
|
||||
params := request.Params
|
||||
if params == nil {
|
||||
return nil, errors.New("mcp sampling: the request has no params")
|
||||
}
|
||||
req := SamplingRequest{SystemPrompt: params.SystemPrompt, MaxTokens: int(params.MaxTokens)}
|
||||
if params.Temperature != 0 {
|
||||
req.Temperature = ¶ms.Temperature
|
||||
}
|
||||
for _, message := range params.Messages {
|
||||
if message == nil {
|
||||
continue
|
||||
}
|
||||
req.Messages = append(req.Messages, SamplingMessage{Role: string(message.Role), Content: samplingContent(message.Content)})
|
||||
}
|
||||
result, err := handler(ctx, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &sdk.CreateMessageResult{
|
||||
Model: result.Model,
|
||||
Role: "assistant",
|
||||
Content: &sdk.TextContent{Text: result.Text},
|
||||
StopReason: result.StopReason,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func samplingContent(content sdk.Content) SamplingContent {
|
||||
switch block := content.(type) {
|
||||
case *sdk.TextContent:
|
||||
return SamplingContent{Type: "text", Text: block.Text}
|
||||
case *sdk.ImageContent:
|
||||
return SamplingContent{Type: "image"}
|
||||
case *sdk.AudioContent:
|
||||
return SamplingContent{Type: "audio"}
|
||||
default:
|
||||
return SamplingContent{Type: fmt.Sprintf("%T", content)}
|
||||
}
|
||||
}
|
||||
|
||||
// Manifest declares the MCP provider's tool capability.
|
||||
func (p *Provider) Manifest() plugin.Manifest {
|
||||
return plugin.Manifest{
|
||||
@@ -98,7 +164,7 @@ func (p *Provider) Manifest() plugin.Manifest {
|
||||
}
|
||||
}
|
||||
|
||||
// Start starts the transport and performs the MCP handshake.
|
||||
// Start connects to the server and performs the MCP handshake.
|
||||
func (p *Provider) Start(ctx context.Context) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
@@ -106,35 +172,69 @@ func (p *Provider) Start(ctx context.Context) error {
|
||||
if p.name == "" || p.segment == "" {
|
||||
return errors.New("MCP tool provider name is required")
|
||||
}
|
||||
if lifecycle.IsNil(p.transport) {
|
||||
if p.connect == nil {
|
||||
return errors.New("MCP tool provider transport is nil")
|
||||
}
|
||||
if err := p.Manifest().Validate(); err != nil {
|
||||
return fmt.Errorf("MCP tool provider manifest: %w", err)
|
||||
}
|
||||
p.mu.Lock()
|
||||
p.stopped = false
|
||||
p.mu.Unlock()
|
||||
_, err := p.liveSession(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
p.mu.RLock()
|
||||
started := p.client != nil && p.transport.State() == protocol.StateRunning
|
||||
p.mu.RUnlock()
|
||||
if started {
|
||||
return nil
|
||||
// liveSession returns the connected session, connecting first when there is
|
||||
// none: before the first call, or after the server exited or dropped the
|
||||
// connection.
|
||||
func (p *Provider) liveSession(ctx context.Context) (*sdk.ClientSession, error) {
|
||||
p.connectMu.Lock()
|
||||
defer p.connectMu.Unlock()
|
||||
p.mu.Lock()
|
||||
stopped, current := p.stopped, p.session
|
||||
p.mu.Unlock()
|
||||
if stopped {
|
||||
return nil, fmt.Errorf("MCP tool provider %q is stopped", p.name)
|
||||
}
|
||||
|
||||
if err := p.transport.Start(ctx); err != nil {
|
||||
return fmt.Errorf("start MCP server %q: %w", p.name, err)
|
||||
if current != nil {
|
||||
return current, nil
|
||||
}
|
||||
client := protocol.NewClient(p.transport, p.name, p.parallelToolCalls,
|
||||
protocol.WithSamplingHandler(p.samplingHandler))
|
||||
if _, err := client.Initialize(ctx); err != nil {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout)
|
||||
stopErr := p.transport.Stop(cleanupCtx)
|
||||
cancel()
|
||||
return errors.Join(err, stopErr)
|
||||
// The session outlives the request that opened it.
|
||||
sessionCtx := context.WithoutCancel(ctx)
|
||||
transport, err := p.connect(sessionCtx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("start MCP server %q: %w", p.name, err)
|
||||
}
|
||||
session, err := p.client.Connect(sessionCtx, transport, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("start MCP server %q: %w", p.name, err)
|
||||
}
|
||||
p.mu.Lock()
|
||||
p.client = client
|
||||
if p.stopped {
|
||||
p.mu.Unlock()
|
||||
_ = session.Close()
|
||||
return nil, fmt.Errorf("MCP tool provider %q is stopped", p.name)
|
||||
}
|
||||
p.session = session
|
||||
p.mu.Unlock()
|
||||
return nil
|
||||
go p.forgetWhenClosed(session)
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (p *Provider) forgetWhenClosed(session *sdk.ClientSession) {
|
||||
_ = session.Wait()
|
||||
p.mu.Lock()
|
||||
if p.session == session {
|
||||
p.session = nil
|
||||
}
|
||||
p.mu.Unlock()
|
||||
}
|
||||
|
||||
func (p *Provider) connected() bool {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return p.session != nil
|
||||
}
|
||||
|
||||
// Discover lists and adapts executable MCP tools.
|
||||
@@ -142,102 +242,121 @@ func (p *Provider) Discover(ctx context.Context) ([]tools.ToolEntry, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.mu.RLock()
|
||||
client := p.client
|
||||
p.mu.RUnlock()
|
||||
if client == nil {
|
||||
return nil, fmt.Errorf("MCP tool provider %q is not started", p.name)
|
||||
}
|
||||
schemas, err := client.ListTools(ctx)
|
||||
session, err := p.liveSession(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
entries := make([]tools.ToolEntry, 0, len(schemas))
|
||||
names := make(map[string]string, len(schemas))
|
||||
for _, schema := range schemas {
|
||||
segment := sanitizeToolSegment(schema.Name)
|
||||
entries := []tools.ToolEntry{}
|
||||
names := map[string]string{}
|
||||
for tool, err := range session.Tools(ctx, nil) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mcp: tools/list %s: %w", p.name, err)
|
||||
}
|
||||
segment := sanitizeToolSegment(tool.Name)
|
||||
if segment == "" {
|
||||
return nil, fmt.Errorf("MCP server %q advertised invalid empty tool name %q", p.name, schema.Name)
|
||||
return nil, fmt.Errorf("MCP server %q advertised invalid empty tool name %q", p.name, tool.Name)
|
||||
}
|
||||
publicName := "mcp." + p.segment + "." + segment
|
||||
if original, exists := names[publicName]; exists {
|
||||
return nil, fmt.Errorf(
|
||||
"MCP server %q tool names %q and %q both map to %q",
|
||||
p.name,
|
||||
original,
|
||||
schema.Name,
|
||||
publicName,
|
||||
)
|
||||
return nil, fmt.Errorf("MCP server %q tool names %q and %q both map to %q", p.name, original, tool.Name, publicName)
|
||||
}
|
||||
names[publicName] = tool.Name
|
||||
schema, err := inputSchema(tool.InputSchema)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("MCP server %q tool %q: %w", p.name, tool.Name, err)
|
||||
}
|
||||
names[publicName] = schema.Name
|
||||
var class tools.ToolClassification
|
||||
if schema.Annotations.ReadOnlyHint {
|
||||
if tool.Annotations != nil && tool.Annotations.ReadOnlyHint {
|
||||
class = tools.ClassIdempotent
|
||||
}
|
||||
entries = append(entries, tools.ToolEntry{
|
||||
Classification: class,
|
||||
Name: publicName,
|
||||
Toolset: "mcp",
|
||||
Schema: schema.InputSchema,
|
||||
Description: schema.Description,
|
||||
Handler: p.handlerFor(client, schema.Name),
|
||||
CheckFn: func() bool {
|
||||
return p.transport.State() == protocol.StateRunning
|
||||
},
|
||||
Schema: schema,
|
||||
Description: tool.Description,
|
||||
Handler: p.handlerFor(tool.Name),
|
||||
CheckFn: p.connected,
|
||||
})
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
// Stop stops the MCP transport and removes any media files written during
|
||||
// this provider's lifetime.
|
||||
func (p *Provider) Stop(ctx context.Context) error {
|
||||
// inputSchema converts the schema the SDK decoded into the registry's form.
|
||||
func inputSchema(schema any) (tools.JSONSchema, error) {
|
||||
if schema == nil {
|
||||
return tools.JSONSchema{"type": "object"}, nil
|
||||
}
|
||||
raw, err := json.Marshal(schema)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("input schema: %w", err)
|
||||
}
|
||||
var out tools.JSONSchema
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return nil, fmt.Errorf("input schema: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Stop closes the session and removes any media files written during this
|
||||
// provider's lifetime.
|
||||
func (p *Provider) Stop(context.Context) error {
|
||||
p.mu.Lock()
|
||||
p.client = nil
|
||||
p.stopped = true
|
||||
session := p.session
|
||||
p.session = nil
|
||||
mediaDir := p.mediaDir
|
||||
p.mediaDir = ""
|
||||
p.mu.Unlock()
|
||||
if mediaDir != "" {
|
||||
if err := os.RemoveAll(mediaDir); err != nil {
|
||||
return fmt.Errorf("remove MCP media dir %q: %w", mediaDir, err)
|
||||
var errs []error
|
||||
if session != nil {
|
||||
if err := session.Close(); err != nil {
|
||||
errs = append(errs, fmt.Errorf("stop MCP server %q: %w", p.name, err))
|
||||
}
|
||||
}
|
||||
if lifecycle.IsNil(p.transport) {
|
||||
return nil
|
||||
if mediaDir != "" {
|
||||
if err := os.RemoveAll(mediaDir); err != nil {
|
||||
errs = append(errs, fmt.Errorf("remove MCP media dir %q: %w", mediaDir, err))
|
||||
}
|
||||
}
|
||||
if err := p.transport.Stop(ctx); err != nil {
|
||||
return fmt.Errorf("stop MCP server %q: %w", p.name, err)
|
||||
}
|
||||
return nil
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
func (p *Provider) handlerFor(client *protocol.Client, originalName string) tools.Handler {
|
||||
// mediaBlock is one binary content block a tool returned.
|
||||
type mediaBlock struct {
|
||||
data []byte
|
||||
mimeType string
|
||||
}
|
||||
|
||||
func (p *Provider) handlerFor(originalName string) tools.Handler {
|
||||
return func(ctx context.Context, input map[string]any) (any, error) {
|
||||
result, err := client.CallTool(ctx, originalName, input)
|
||||
result, err := p.callTool(ctx, originalName, input)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var text strings.Builder
|
||||
var media []protocol.ContentBlock
|
||||
for _, block := range result.Content {
|
||||
switch {
|
||||
case block.Type == "resource" && block.Resource != nil && block.Resource.Blob != "":
|
||||
// A resource can carry both inline text and a binary blob
|
||||
// at once; keep the text in the summary and still treat
|
||||
// the blob as media.
|
||||
if block.Resource.Text != "" {
|
||||
text.WriteString(block.Resource.Text)
|
||||
}
|
||||
media = append(media, block)
|
||||
case block.Type == "resource" && block.Resource != nil:
|
||||
text.WriteString(block.Resource.Text)
|
||||
case block.Data != "":
|
||||
media = append(media, block)
|
||||
case block.Type == "" || block.Type == "text":
|
||||
var media []mediaBlock
|
||||
for _, content := range result.Content {
|
||||
switch block := content.(type) {
|
||||
case *sdk.TextContent:
|
||||
text.WriteString(block.Text)
|
||||
case *sdk.ImageContent:
|
||||
media = append(media, mediaBlock{block.Data, block.MIMEType})
|
||||
case *sdk.AudioContent:
|
||||
media = append(media, mediaBlock{block.Data, block.MIMEType})
|
||||
case *sdk.EmbeddedResource:
|
||||
if block.Resource == nil {
|
||||
continue
|
||||
}
|
||||
// A resource can carry inline text and a binary blob at once.
|
||||
text.WriteString(block.Resource.Text)
|
||||
if len(block.Resource.Blob) > 0 {
|
||||
media = append(media, mediaBlock{block.Resource.Blob, block.Resource.MIMEType})
|
||||
}
|
||||
case *sdk.ResourceLink:
|
||||
fmt.Fprintf(&text, "[resource %s]", block.URI)
|
||||
default:
|
||||
fmt.Fprintf(&text, "[unhandled content block type %q]", block.Type)
|
||||
fmt.Fprintf(&text, "[unhandled content block %T]", content)
|
||||
}
|
||||
}
|
||||
if result.IsError {
|
||||
@@ -250,13 +369,28 @@ func (p *Provider) handlerFor(client *protocol.Client, originalName string) tool
|
||||
}
|
||||
}
|
||||
|
||||
// maxMediaBlockBase64Bytes caps one media block's base64 size.
|
||||
const maxMediaBlockBase64Bytes = 64 << 20 // 64MiB
|
||||
func (p *Provider) callTool(ctx context.Context, name string, input map[string]any) (*sdk.CallToolResult, error) {
|
||||
if p.callMu != nil {
|
||||
p.callMu.Lock()
|
||||
defer p.callMu.Unlock()
|
||||
}
|
||||
session, err := p.liveSession(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := session.CallTool(ctx, &sdk.CallToolParams{Name: name, Arguments: input})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mcp: tools/call %s.%s: %w", p.name, name, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// maxMediaBlockBytes caps one media block's decoded size.
|
||||
const maxMediaBlockBytes = 48 << 20 // 48MiB
|
||||
|
||||
// writeMultimodalResult writes each media block under
|
||||
// mediaDir/<tool>/<call>/ and returns a result naming the files. Bad base64
|
||||
// is an error.
|
||||
func (p *Provider) writeMultimodalResult(toolName, summaryText string, media []protocol.ContentBlock) (tools.MultimodalResult, error) {
|
||||
// mediaDir/<tool>/<call>/ and returns a result naming the files.
|
||||
func (p *Provider) writeMultimodalResult(toolName, summaryText string, media []mediaBlock) (tools.MultimodalResult, error) {
|
||||
result := tools.MultimodalResult{IsMultimodal: true, Summary: summaryText}
|
||||
root, err := p.mediaRoot()
|
||||
if err != nil {
|
||||
@@ -269,8 +403,7 @@ func (p *Provider) writeMultimodalResult(toolName, summaryText string, media []p
|
||||
}
|
||||
|
||||
// Each call gets its own subdirectory so concurrent calls to the same
|
||||
// tool never write to the same index-based filename and clobber or
|
||||
// interleave each other's output.
|
||||
// tool never write to the same index-based filename.
|
||||
callSeq := p.mediaCallSeq.Add(1)
|
||||
subdir := filepath.Join(root, toolName, strconv.FormatInt(callSeq, 10))
|
||||
if err := os.MkdirAll(subdir, 0o755); err != nil {
|
||||
@@ -280,29 +413,18 @@ func (p *Provider) writeMultimodalResult(toolName, summaryText string, media []p
|
||||
files := make([]string, 0, len(media))
|
||||
refs := make([]tools.MediaRef, 0, len(media))
|
||||
for i, block := range media {
|
||||
data := block.Data
|
||||
mimeType := block.MimeType
|
||||
if block.Resource != nil {
|
||||
data = block.Resource.Blob
|
||||
mimeType = block.Resource.MimeType
|
||||
if len(block.data) > maxMediaBlockBytes {
|
||||
return tools.MultimodalResult{}, fmt.Errorf("MCP tool %s: media block %d (%d bytes) exceeds the %d byte limit",
|
||||
toolName, i, len(block.data), maxMediaBlockBytes)
|
||||
}
|
||||
if len(data) > maxMediaBlockBase64Bytes {
|
||||
return tools.MultimodalResult{}, fmt.Errorf("MCP tool %s: media block %d (%d bytes base64) exceeds the %d byte limit",
|
||||
toolName, i, len(data), maxMediaBlockBase64Bytes)
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(data)
|
||||
if err != nil {
|
||||
return tools.MultimodalResult{}, fmt.Errorf("MCP tool %s: decode media block %d: %w", toolName, i, err)
|
||||
}
|
||||
ext := extensionForMimeType(mimeType)
|
||||
name := fmt.Sprintf("%d%s", i, ext)
|
||||
name := fmt.Sprintf("%d%s", i, extensionForMimeType(block.mimeType))
|
||||
path := filepath.Join(subdir, name)
|
||||
if err := os.WriteFile(path, raw, 0o644); err != nil { //nolint:gosec // G306: the agent reads tool media as another user.
|
||||
if err := os.WriteFile(path, block.data, 0o644); err != nil { //nolint:gosec // G306: the agent reads tool media as another user.
|
||||
return tools.MultimodalResult{}, fmt.Errorf("MCP tool %s: write media block %d: %w", toolName, i, err)
|
||||
}
|
||||
files = append(files, path)
|
||||
refs = append(refs, tools.MediaRef{
|
||||
Type: mediaTypeForMimeType(mimeType),
|
||||
Type: mediaTypeForMimeType(block.mimeType),
|
||||
Path: path,
|
||||
FileName: name,
|
||||
})
|
||||
|
||||
@@ -24,7 +24,6 @@ export interface McpServer {
|
||||
work_dir?: string;
|
||||
url?: string;
|
||||
sse_endpoint?: string;
|
||||
message_endpoint?: string;
|
||||
parallel_tool_calls: boolean;
|
||||
headers_configured: boolean;
|
||||
}
|
||||
@@ -100,16 +99,10 @@ const args = computed({
|
||||
<Input :model-value="server.url"
|
||||
@update:model-value="(value: string | number) => patch({ url: String(value) })" class="font-mono" placeholder="https://host/mcp" />
|
||||
</Label>
|
||||
<template v-else>
|
||||
<Label class="grid gap-1 text-caption text-fg-subtle">SSE endpoint
|
||||
<Input :model-value="server.sse_endpoint"
|
||||
<Label v-else class="grid gap-1 text-caption text-fg-subtle">SSE endpoint
|
||||
<Input :model-value="server.sse_endpoint"
|
||||
@update:model-value="(value: string | number) => patch({ sse_endpoint: String(value) })" class="font-mono" />
|
||||
</Label>
|
||||
<Label class="grid gap-1 text-caption text-fg-subtle">Message endpoint
|
||||
<Input :model-value="server.message_endpoint"
|
||||
@update:model-value="(value: string | number) => patch({ message_endpoint: String(value) })" class="font-mono" />
|
||||
</Label>
|
||||
</template>
|
||||
</Label>
|
||||
|
||||
<Label class="flex items-center gap-2 text-label">
|
||||
<Switch :model-value="server.parallel_tool_calls" @update:model-value="(value: boolean) => patch({ parallel_tool_calls: value })" />
|
||||
|
||||
Reference in new issue
Block a user