Run Vale over every tracked Go, Markdown and template file and fix the remaining findings: long sentences, repetition, UI verbs, identifiers that should be backticked, and migration narration in comments. AGENTS.md and CLAUDE.md keep their absolute rules; the prompt heuristic against repeated absolutes is disabled for rule files.
558 lines
17 KiB
Go
558 lines
17 KiB
Go
// Package mcp adapts one MCP server, through the official MCP SDK, to the
|
|
// typed tool-provider family.
|
|
package mcp
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
|
|
sdk "github.com/modelcontextprotocol/go-sdk/mcp"
|
|
|
|
"github.com/samcharles93/archie-core/internal/plugin"
|
|
"github.com/samcharles93/archie-core/internal/tools"
|
|
)
|
|
|
|
// 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 {
|
|
name string
|
|
segment string
|
|
connect Connector
|
|
client *sdk.Client
|
|
|
|
// connectMu serialises 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
|
|
|
|
// callMu serialises 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
|
|
// multimodal tool result. It is removed by Stop.
|
|
mediaDir string
|
|
// mediaCallSeq disambiguates concurrent calls to the same tool so
|
|
// their written media files never share a directory.
|
|
mediaCallSeq atomic.Int64
|
|
}
|
|
|
|
// New creates an MCP tool provider. parallelToolCalls mirrors the configured
|
|
// server's own flag: false (the default) serialises 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),
|
|
connect: connect,
|
|
client: sdk.NewClient(&sdk.Implementation{Name: "archie-core", Version: "1.0.0"},
|
|
&sdk.ClientOptions{CreateMessageHandler: sdkSampling(sampling)}), //nolint:staticcheck // SA1019: see sdkSampling.
|
|
}
|
|
if !parallelToolCalls {
|
|
p.callMu = &sync.Mutex{}
|
|
}
|
|
return p
|
|
}
|
|
|
|
// sdkSampling adapts handler to the SDK. Protocol 2026-07-28 (SEP-2577)
|
|
// deprecates sampling, 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{
|
|
ID: "mcp." + sanitizeManifestSegment(p.name),
|
|
Name: "MCP tools: " + p.name,
|
|
Version: "1.0.0",
|
|
APIVersion: plugin.HostAPIVersion,
|
|
Capabilities: []plugin.CapabilityKind{"tools"},
|
|
Permissions: []plugin.Permission{"process"},
|
|
}
|
|
}
|
|
|
|
// 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
|
|
}
|
|
if p.name == "" || p.segment == "" {
|
|
return errors.New("MCP tool provider name is required")
|
|
}
|
|
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
|
|
}
|
|
|
|
// 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 current != nil {
|
|
return current, nil
|
|
}
|
|
// 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()
|
|
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()
|
|
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.
|
|
func (p *Provider) Discover(ctx context.Context) ([]tools.ToolEntry, error) {
|
|
if err := ctx.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
session, err := p.liveSession(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
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, 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, 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)
|
|
}
|
|
var class tools.ToolClassification
|
|
if tool.Annotations != nil && tool.Annotations.ReadOnlyHint {
|
|
class = tools.ClassIdempotent
|
|
}
|
|
entries = append(entries, tools.ToolEntry{
|
|
Classification: class,
|
|
Name: publicName,
|
|
Toolset: "mcp",
|
|
Schema: schema,
|
|
Description: tool.Description,
|
|
Handler: p.handlerFor(tool.Name),
|
|
CheckFn: p.connected,
|
|
})
|
|
}
|
|
return entries, nil
|
|
}
|
|
|
|
// 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.stopped = true
|
|
session := p.session
|
|
p.session = nil
|
|
mediaDir := p.mediaDir
|
|
p.mediaDir = ""
|
|
p.mu.Unlock()
|
|
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 mediaDir != "" {
|
|
if err := os.RemoveAll(mediaDir); err != nil {
|
|
errs = append(errs, fmt.Errorf("remove MCP media dir %q: %w", mediaDir, err))
|
|
}
|
|
}
|
|
return errors.Join(errs...)
|
|
}
|
|
|
|
// 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 := p.callTool(ctx, originalName, input)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var text strings.Builder
|
|
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 %T]", content)
|
|
}
|
|
}
|
|
if result.IsError {
|
|
return nil, fmt.Errorf("MCP tool %q reported an error: %s", originalName, text.String())
|
|
}
|
|
if len(media) == 0 {
|
|
return text.String(), nil
|
|
}
|
|
return p.writeMultimodalResult(originalName, text.String(), media)
|
|
}
|
|
}
|
|
|
|
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.
|
|
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 {
|
|
return tools.MultimodalResult{}, err
|
|
}
|
|
|
|
// The tool name comes from the server; refuse path traversal.
|
|
if err := rejectPathTraversal(toolName); err != nil {
|
|
return tools.MultimodalResult{}, fmt.Errorf("MCP tool name %q is not safe as a path component: %w", toolName, err)
|
|
}
|
|
|
|
// Each call gets its own subdirectory so concurrent calls to the same
|
|
// 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 {
|
|
return tools.MultimodalResult{}, fmt.Errorf("MCP tool %s: create media dir: %w", toolName, err)
|
|
}
|
|
|
|
files := make([]string, 0, len(media))
|
|
refs := make([]tools.MediaRef, 0, len(media))
|
|
for i, block := range media {
|
|
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)
|
|
}
|
|
name := fmt.Sprintf("%d%s", i, extensionForMimeType(block.mimeType))
|
|
path := filepath.Join(subdir, name)
|
|
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(block.mimeType),
|
|
Path: path,
|
|
FileName: name,
|
|
})
|
|
}
|
|
|
|
result.SubdirHint = subdir
|
|
result.Files = files
|
|
result.URLs = refs
|
|
return result, nil
|
|
}
|
|
|
|
// mediaRoot returns the media directory, creating it on first use.
|
|
func (p *Provider) mediaRoot() (string, error) {
|
|
p.mu.Lock()
|
|
defer p.mu.Unlock()
|
|
if p.mediaDir != "" {
|
|
return p.mediaDir, nil
|
|
}
|
|
dir, err := os.MkdirTemp("", "archie-mcp-media-")
|
|
if err != nil {
|
|
return "", fmt.Errorf("MCP provider %q: create media root: %w", p.name, err)
|
|
}
|
|
p.mediaDir = dir
|
|
return dir, nil
|
|
}
|
|
|
|
// rejectPathTraversal returns an error if name contains a path separator or
|
|
// a "." component (covers both ".." and a bare "."), i.e. anything that
|
|
// would let it escape or alter the directory it's joined into. Tool names
|
|
// have no legitimate reason to contain path structure.
|
|
func rejectPathTraversal(name string) error {
|
|
if name == "" {
|
|
return errors.New("empty name")
|
|
}
|
|
if strings.ContainsAny(name, `/\`) {
|
|
return errors.New("contains a path separator")
|
|
}
|
|
// No separators at this point, so name is a single path component --
|
|
// only "." and ".." are themselves traversal-meaningful.
|
|
if name == "." || name == ".." {
|
|
return errors.New("is a \".\" or \"..\" path component")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// extensionForMimeType maps common MCP media MIME types to a file
|
|
// extension. Unrecognized types get no extension -- the file is still
|
|
// written and its path returned; a missing extension doesn't stop the
|
|
// content from being usable, it's just not identifiable by filename alone.
|
|
func extensionForMimeType(mimeType string) string {
|
|
switch mimeType {
|
|
case "image/png":
|
|
return ".png"
|
|
case "image/jpeg":
|
|
return ".jpg"
|
|
case "image/gif":
|
|
return ".gif"
|
|
case "image/webp":
|
|
return ".webp"
|
|
case "audio/wav", "audio/wave", "audio/x-wav":
|
|
return ".wav"
|
|
case "audio/mpeg":
|
|
return ".mp3"
|
|
case "audio/ogg":
|
|
return ".ogg"
|
|
case "video/mp4":
|
|
return ".mp4"
|
|
case "application/pdf":
|
|
return ".pdf"
|
|
default:
|
|
return ""
|
|
}
|
|
}
|
|
|
|
// mediaTypeForMimeType maps a MIME type to image, video, audio or document.
|
|
// Only photo formats count as image.
|
|
func mediaTypeForMimeType(mimeType string) string {
|
|
switch mimeType {
|
|
case "image/png", "image/jpeg", "image/gif", "image/webp":
|
|
return "image"
|
|
}
|
|
switch {
|
|
case strings.HasPrefix(mimeType, "video/"):
|
|
return "video"
|
|
case strings.HasPrefix(mimeType, "audio/"):
|
|
return "audio"
|
|
default:
|
|
return "document"
|
|
}
|
|
}
|
|
|
|
func sanitizeManifestSegment(value string) string {
|
|
return sanitizeSegment(value, '-')
|
|
}
|
|
|
|
func sanitizeToolSegment(value string) string {
|
|
return sanitizeSegment(value, '_')
|
|
}
|
|
|
|
func sanitizeSegment(value string, separator rune) string {
|
|
var out strings.Builder
|
|
pendingSeparator := false
|
|
for _, char := range strings.ToLower(strings.TrimSpace(value)) {
|
|
if isASCIILetter(char) || isASCIIDigit(char) {
|
|
if pendingSeparator && out.Len() > 0 {
|
|
out.WriteRune(separator)
|
|
}
|
|
out.WriteRune(char)
|
|
pendingSeparator = false
|
|
continue
|
|
}
|
|
pendingSeparator = true
|
|
}
|
|
sanitized := out.String()
|
|
if sanitized == "" {
|
|
return ""
|
|
}
|
|
if !isASCIILetter(rune(sanitized[0])) {
|
|
return "x" + string(separator) + sanitized
|
|
}
|
|
return sanitized
|
|
}
|
|
|
|
func isASCIILetter(char rune) bool {
|
|
return char >= 'a' && char <= 'z'
|
|
}
|
|
|
|
func isASCIIDigit(char rune) bool {
|
|
return char >= '0' && char <= '9'
|
|
}
|