Add hooks and MCP as first-class components; expand docs
Promotes the two remaining "deliberately not in scope" components from the harness model to first-class subsystems, and overhauls the docs. Hooks (runtime/types.go, runtime/runtime.go, runtime/hooks_test.go): - New runtime.LifecycleHooks struct on LoopConfig.Hooks with five Go callbacks: OnUserPromptSubmit (may rewrite prompt), OnSessionStart, BeforeToolUse (gating with same shape as PermissionChecker), AfterToolUse (observe), OnStop (with reason: completed/max_turns/error/aborted). - Wired into Run, dispatchTool, executeToolKickoff at all 8 exit points + both tool-execution paths. - 8 tests covering each hook firing. MCP (tools/mcp/, runtime/builder.go, runtime/types.go): - New tools/mcp package using the official github.com/modelcontextprotocol/go-sdk v1.5.0. Stdio and Streamable HTTP transports. - ServerConfig now exposes Headers + HTTPClient for HTTP auth (static bearer, OAuth via oauth2.NewClient, mTLS, custom RoundTripper). Header injection clones requests so SDK retries see clean params. - First-class AgentSpec.MCPServers — BuildRuntime connects each server, registers adapter tools (mcp__<server>__<tool>), stashes clients on Runtime. - New Runtime.Close() releases sessions; idempotent. - 14 tests including end-to-end header propagation through the SDK via httptest.Server. Examples: - support-agent now demonstrates Skills + Permission + LifecycleHooks together. Audit log via AfterToolUse + OnStop, JSONL output. - defer rt.Close() added to all four examples (no-op without MCP, idiomatic). Docs: - README expanded: Why harness, Requirements, Install, Examples table, Configuration (env vars), Non-goals, Testing, expanded Status. Quick Start fixed to use real BuildRuntime API. - developer.md mental-model diagram replaced with two correct ones: composition (how a Runtime is wired) and per-Run sequence (what rt.Run actually does, including hook fan-out and the tool batch loop). - developer.md gains Lifecycle hooks + MCP servers subsections with full snippets, including Streamable HTTP auth and OAuth recipes (clientcredentials + authcode flows via golang.org/x/oauth2). - LICENSE file added (MIT). All 18 packages build and test green.
This commit is contained in:
1 parent
4b2f645f16
commit
76c03019c8
19 files changed
+1926
-59
No files matched your search
@@ -0,0 +1,114 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
sdk "github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
// mcpToolAdapter implements tool.Tool by delegating Execute to an MCP
|
||||
// session's CallTool. Constructed by Client.Connect via discoverTools.
|
||||
type mcpToolAdapter struct {
|
||||
serverName string
|
||||
sdkTool *sdk.Tool
|
||||
session *sdk.ClientSession
|
||||
}
|
||||
|
||||
// Name returns "mcp__<server>__<tool>". The double-underscore
|
||||
// namespacing matches Claude Code so the LLM treats these tools the
|
||||
// same way it would in CC and so they can't collide with built-in
|
||||
// harness tools.
|
||||
func (a *mcpToolAdapter) Name() string {
|
||||
return "mcp__" + a.serverName + "__" + a.sdkTool.Name
|
||||
}
|
||||
|
||||
func (a *mcpToolAdapter) Description() string { return a.sdkTool.Description }
|
||||
|
||||
// Parameters returns the server-supplied JSON Schema. SDK leaves
|
||||
// InputSchema as `any`; we marshal it. If the schema fails to marshal
|
||||
// (vanishingly unlikely — server-supplied JSON), we return an empty
|
||||
// object schema so the LLM still sees the tool as callable.
|
||||
func (a *mcpToolAdapter) Parameters() json.RawMessage {
|
||||
if a.sdkTool.InputSchema == nil {
|
||||
return json.RawMessage(`{"type":"object"}`)
|
||||
}
|
||||
b, err := json.Marshal(a.sdkTool.InputSchema)
|
||||
if err != nil {
|
||||
return json.RawMessage(`{"type":"object"}`)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// IsConcurrencySafe reports false — MCP doesn't expose a safety hint
|
||||
// per tool, and the only safe default for arbitrary external code is
|
||||
// "no". Callers who know a specific MCP tool is read-only can wrap the
|
||||
// adapter to override this.
|
||||
func (a *mcpToolAdapter) IsConcurrencySafe(_ json.RawMessage) bool { return false }
|
||||
|
||||
// Execute marshals input into the MCP CallTool payload, invokes the
|
||||
// server, and translates the response back into a tool.ToolResult.
|
||||
//
|
||||
// MCP's tool-error model differs from harness's:
|
||||
// - Protocol errors (transport, schema validation) → returned as Go
|
||||
// error, surfaced to the runtime as a tool result with Error set.
|
||||
// - Tool errors (CallToolResult.IsError=true) → also surfaced as
|
||||
// ToolResult.Error so the agent sees them the same way it sees a
|
||||
// harness-native tool error.
|
||||
func (a *mcpToolAdapter) Execute(ctx context.Context, input json.RawMessage) (tool.ToolResult, error) {
|
||||
var args any
|
||||
if len(input) > 0 {
|
||||
if err := json.Unmarshal(input, &args); err != nil {
|
||||
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
|
||||
}
|
||||
}
|
||||
res, err := a.session.CallTool(ctx, &sdk.CallToolParams{
|
||||
Name: a.sdkTool.Name,
|
||||
Arguments: args,
|
||||
})
|
||||
if err != nil {
|
||||
return tool.ToolResult{Error: err.Error()}, nil
|
||||
}
|
||||
return mcpResultToToolResult(res), nil
|
||||
}
|
||||
|
||||
// mcpResultToToolResult flattens MCP content blocks into a harness
|
||||
// ToolResult: TextContent concatenated into Output (or Error if
|
||||
// IsError), ImageContent collected into Images. Other content types
|
||||
// (audio, embedded resources) are described in Output as a placeholder.
|
||||
func mcpResultToToolResult(res *sdk.CallToolResult) tool.ToolResult {
|
||||
var text strings.Builder
|
||||
var images []llm.ImageContent
|
||||
for _, c := range res.Content {
|
||||
switch v := c.(type) {
|
||||
case *sdk.TextContent:
|
||||
if text.Len() > 0 {
|
||||
text.WriteByte('\n')
|
||||
}
|
||||
text.WriteString(v.Text)
|
||||
case *sdk.ImageContent:
|
||||
images = append(images, llm.ImageContent{
|
||||
MimeType: v.MIMEType,
|
||||
Data: v.Data,
|
||||
})
|
||||
default:
|
||||
// Unknown content type — note it so the agent isn't silently
|
||||
// missing data.
|
||||
if text.Len() > 0 {
|
||||
text.WriteByte('\n')
|
||||
}
|
||||
fmt.Fprintf(&text, "[unsupported MCP content: %T]", c)
|
||||
}
|
||||
}
|
||||
out := tool.ToolResult{Images: images}
|
||||
if res.IsError {
|
||||
out.Error = text.String()
|
||||
} else {
|
||||
out.Output = text.String()
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
// Package mcp adapts an external Model Context Protocol (MCP) server's
|
||||
// tools into harness tool.Tool implementations.
|
||||
//
|
||||
// Typical usage:
|
||||
//
|
||||
// cli, err := mcp.Connect(ctx, mcp.ServerConfig{
|
||||
// Name: "fs",
|
||||
// Command: "npx",
|
||||
// Args: []string{"-y", "@modelcontextprotocol/server-filesystem", "/tmp"},
|
||||
// })
|
||||
// if err != nil { ... }
|
||||
// defer cli.Close()
|
||||
// for _, t := range cli.Tools() {
|
||||
// reg.Register(t)
|
||||
// }
|
||||
//
|
||||
// For declarative wiring, set runtime.AgentSpec.MCPServers — the runtime
|
||||
// builder will Connect each server, register its tools into the agent's
|
||||
// registry, and tear them down via Runtime.Close.
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
|
||||
sdk "github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
// ServerConfig describes one MCP server to connect to. Exactly one
|
||||
// transport must be specified: Command (stdio, the most common) or URL
|
||||
// (Streamable HTTP via the SDK's StreamableClientTransport).
|
||||
type ServerConfig struct {
|
||||
// Name namespaces the server's tools. Adapter tool names become
|
||||
// "mcp__<Name>__<tool>", matching Claude Code's convention so the
|
||||
// LLM treats them the same way.
|
||||
Name string
|
||||
|
||||
// Command + Args + Env wire the stdio transport. Env is merged into
|
||||
// the spawned process's environment (replacing duplicates from
|
||||
// os.Environ()).
|
||||
Command string
|
||||
Args []string
|
||||
Env map[string]string
|
||||
|
||||
// URL wires the Streamable HTTP transport (StreamableClientTransport).
|
||||
// Mutually exclusive with Command — set exactly one.
|
||||
URL string
|
||||
|
||||
// Headers attaches static HTTP headers to every request the
|
||||
// Streamable HTTP transport makes. Typical use: auth tokens
|
||||
// ("Authorization": "Bearer …", "X-API-Key": …). Ignored for
|
||||
// stdio. Wrapped around HTTPClient.Transport — your custom
|
||||
// RoundTripper still runs.
|
||||
Headers map[string]string
|
||||
|
||||
// HTTPClient overrides the default *http.Client used by the
|
||||
// Streamable HTTP transport. Use this for mTLS, custom timeouts,
|
||||
// or full RoundTripper control. Ignored for stdio. nil ⇒ a fresh
|
||||
// http.Client{} with default transport.
|
||||
HTTPClient *http.Client
|
||||
|
||||
// ClientImplementation is sent to the server during the initialize
|
||||
// handshake. Optional — defaults to {Name: "harness", Version: "v1"}.
|
||||
ClientImplementation *sdk.Implementation
|
||||
}
|
||||
|
||||
// Client is a connected MCP server with its discovered tools adapted as
|
||||
// harness tool.Tool implementations.
|
||||
type Client struct {
|
||||
name string
|
||||
session *sdk.ClientSession
|
||||
tools []tool.Tool
|
||||
closed bool
|
||||
}
|
||||
|
||||
// Connect opens a session to the MCP server in cfg, lists its tools,
|
||||
// and adapts each into a tool.Tool. Returned Client owns the session;
|
||||
// call Close to release it.
|
||||
func Connect(ctx context.Context, cfg ServerConfig) (*Client, error) {
|
||||
if cfg.Name == "" {
|
||||
return nil, fmt.Errorf("mcp: ServerConfig.Name is required")
|
||||
}
|
||||
if cfg.Command == "" && cfg.URL == "" {
|
||||
return nil, fmt.Errorf("mcp: one of Command or URL must be set")
|
||||
}
|
||||
if cfg.Command != "" && cfg.URL != "" {
|
||||
return nil, fmt.Errorf("mcp: Command and URL are mutually exclusive")
|
||||
}
|
||||
|
||||
transport, err := buildTransport(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return connectWithTransport(ctx, cfg.Name, transport, cfg.ClientImplementation)
|
||||
}
|
||||
|
||||
// connectWithTransport is the lower-level entrypoint shared by Connect
|
||||
// and the test helpers. Exposed via mcp_test_helpers.go so tests can
|
||||
// pair the client with an InMemoryTransport.
|
||||
func connectWithTransport(ctx context.Context, name string, transport sdk.Transport, impl *sdk.Implementation) (*Client, error) {
|
||||
if impl == nil {
|
||||
impl = &sdk.Implementation{Name: "harness", Version: "v1"}
|
||||
}
|
||||
client := sdk.NewClient(impl, nil)
|
||||
session, err := client.Connect(ctx, transport, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mcp: connect %q: %w", name, err)
|
||||
}
|
||||
tools, err := discoverTools(ctx, name, session)
|
||||
if err != nil {
|
||||
_ = session.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &Client{name: name, session: session, tools: tools}, nil
|
||||
}
|
||||
|
||||
// Tools returns the adapter tool.Tool slice. Safe to call multiple
|
||||
// times; the slice header is shared (callers should not mutate it).
|
||||
func (c *Client) Tools() []tool.Tool { return c.tools }
|
||||
|
||||
// Name returns the configured server name.
|
||||
func (c *Client) Name() string { return c.name }
|
||||
|
||||
// Close releases the underlying MCP session. Safe to call multiple
|
||||
// times — subsequent calls are no-ops.
|
||||
func (c *Client) Close() error {
|
||||
if c.closed {
|
||||
return nil
|
||||
}
|
||||
c.closed = true
|
||||
return c.session.Close()
|
||||
}
|
||||
|
||||
// buildTransport selects a transport based on cfg. stdio uses
|
||||
// CommandTransport with a process whose env is os.Environ() merged
|
||||
// with cfg.Env (cfg.Env wins on conflict). Streamable HTTP uses
|
||||
// StreamableClientTransport, with optional Headers + HTTPClient
|
||||
// applied via wrapHTTPClient.
|
||||
func buildTransport(cfg ServerConfig) (sdk.Transport, error) {
|
||||
if cfg.Command != "" {
|
||||
cmd := exec.Command(cfg.Command, cfg.Args...)
|
||||
cmd.Env = mergeEnv(os.Environ(), cfg.Env)
|
||||
return &sdk.CommandTransport{Command: cmd}, nil
|
||||
}
|
||||
return &sdk.StreamableClientTransport{
|
||||
Endpoint: cfg.URL,
|
||||
HTTPClient: wrapHTTPClient(cfg.HTTPClient, cfg.Headers),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// wrapHTTPClient returns the *http.Client the Streamable HTTP transport
|
||||
// should use. If headers is non-empty, the client's Transport is
|
||||
// wrapped in a header-injecting RoundTripper so every outgoing request
|
||||
// carries them. The caller's *http.Client is NOT mutated — a shallow
|
||||
// copy is returned when wrapping is needed.
|
||||
func wrapHTTPClient(client *http.Client, headers map[string]string) *http.Client {
|
||||
if client == nil {
|
||||
client = &http.Client{}
|
||||
}
|
||||
if len(headers) == 0 {
|
||||
return client
|
||||
}
|
||||
base := client.Transport
|
||||
if base == nil {
|
||||
base = http.DefaultTransport
|
||||
}
|
||||
out := *client // shallow copy — leave caller's struct alone
|
||||
out.Transport = &headerInjector{base: base, headers: headers}
|
||||
return &out
|
||||
}
|
||||
|
||||
// headerInjector is an http.RoundTripper that adds static headers to
|
||||
// every request before delegating. Request is cloned so the caller's
|
||||
// *http.Request is never mutated (matters for retries inside the SDK).
|
||||
type headerInjector struct {
|
||||
base http.RoundTripper
|
||||
headers map[string]string
|
||||
}
|
||||
|
||||
func (h *headerInjector) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
req2 := req.Clone(req.Context())
|
||||
for k, v := range h.headers {
|
||||
req2.Header.Set(k, v)
|
||||
}
|
||||
return h.base.RoundTrip(req2)
|
||||
}
|
||||
|
||||
// mergeEnv returns base with overrides applied. Order is preserved for
|
||||
// base; overrides are appended at the end after pruning duplicates so
|
||||
// the spawned process sees override values win.
|
||||
func mergeEnv(base []string, overrides map[string]string) []string {
|
||||
if len(overrides) == 0 {
|
||||
return base
|
||||
}
|
||||
out := make([]string, 0, len(base)+len(overrides))
|
||||
for _, kv := range base {
|
||||
// "K=V" — keep only entries whose key is NOT being overridden.
|
||||
key := envKey(kv)
|
||||
if _, ok := overrides[key]; ok {
|
||||
continue
|
||||
}
|
||||
out = append(out, kv)
|
||||
}
|
||||
for k, v := range overrides {
|
||||
out = append(out, k+"="+v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func envKey(kv string) string {
|
||||
for i := 0; i < len(kv); i++ {
|
||||
if kv[i] == '=' {
|
||||
return kv[:i]
|
||||
}
|
||||
}
|
||||
return kv
|
||||
}
|
||||
|
||||
// discoverTools lists tools from the server (paginating if necessary)
|
||||
// and wraps each in an adapter.
|
||||
func discoverTools(ctx context.Context, serverName string, session *sdk.ClientSession) ([]tool.Tool, error) {
|
||||
var out []tool.Tool
|
||||
cursor := ""
|
||||
for {
|
||||
params := &sdk.ListToolsParams{Cursor: cursor}
|
||||
res, err := session.ListTools(ctx, params)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mcp: list tools for %q: %w", serverName, err)
|
||||
}
|
||||
for _, t := range res.Tools {
|
||||
out = append(out, &mcpToolAdapter{
|
||||
serverName: serverName,
|
||||
sdkTool: t,
|
||||
session: session,
|
||||
})
|
||||
}
|
||||
if res.NextCursor == "" {
|
||||
break
|
||||
}
|
||||
cursor = res.NextCursor
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
sdk "github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// startInProcessServer spins up an in-process MCP server with the
|
||||
// supplied tool configurations and returns a connected harness *Client
|
||||
// pointing at it. The server is shut down via t.Cleanup.
|
||||
//
|
||||
// toolFns lets each test customise per-tool handler behaviour (return
|
||||
// text, image, error, etc.).
|
||||
func startInProcessServer(t *testing.T, name string, tools []sdkToolFixture) *Client {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
|
||||
server := sdk.NewServer(&sdk.Implementation{Name: "test-server", Version: "v0"}, nil)
|
||||
for _, tf := range tools {
|
||||
t := tf // capture
|
||||
server.AddTool(t.Tool, t.Handler)
|
||||
}
|
||||
clientTransport, serverTransport := sdk.NewInMemoryTransports()
|
||||
serverSession, err := server.Connect(ctx, serverTransport, nil)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = serverSession.Close() })
|
||||
|
||||
cli, err := connectWithTransport(ctx, name, clientTransport, nil)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = cli.Close() })
|
||||
return cli
|
||||
}
|
||||
|
||||
type sdkToolFixture struct {
|
||||
Tool *sdk.Tool
|
||||
Handler sdk.ToolHandler
|
||||
}
|
||||
|
||||
// helper: build a JSON-schema RawMessage tool with a single string arg.
|
||||
func stringArgTool(name, desc string, handler sdk.ToolHandler) sdkToolFixture {
|
||||
return sdkToolFixture{
|
||||
Tool: &sdk.Tool{
|
||||
Name: name,
|
||||
Description: desc,
|
||||
InputSchema: json.RawMessage(`{"type":"object","properties":{"q":{"type":"string"}}}`),
|
||||
},
|
||||
Handler: handler,
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPAdapter_NameNamespacing(t *testing.T) {
|
||||
cli := startInProcessServer(t, "fs", []sdkToolFixture{
|
||||
stringArgTool("read", "read it", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: "ok"}}}, nil
|
||||
}),
|
||||
})
|
||||
tools := cli.Tools()
|
||||
require.Len(t, tools, 1)
|
||||
assert.Equal(t, "mcp__fs__read", tools[0].Name())
|
||||
}
|
||||
|
||||
func TestMCPAdapter_ParametersPassthrough(t *testing.T) {
|
||||
cli := startInProcessServer(t, "srv", []sdkToolFixture{
|
||||
stringArgTool("echo", "echo back", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: "x"}}}, nil
|
||||
}),
|
||||
})
|
||||
require.Len(t, cli.Tools(), 1)
|
||||
params := cli.Tools()[0].Parameters()
|
||||
var schema map[string]any
|
||||
require.NoError(t, json.Unmarshal(params, &schema))
|
||||
assert.Equal(t, "object", schema["type"])
|
||||
props, _ := schema["properties"].(map[string]any)
|
||||
require.NotNil(t, props["q"], "server-supplied schema property must round-trip")
|
||||
}
|
||||
|
||||
func TestMCPAdapter_ExecuteCallsTool(t *testing.T) {
|
||||
var sawArgs json.RawMessage
|
||||
cli := startInProcessServer(t, "srv", []sdkToolFixture{
|
||||
stringArgTool("echo", "echo", func(_ context.Context, req *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
sawArgs = req.Params.Arguments
|
||||
return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: "got: " + string(req.Params.Arguments)}}}, nil
|
||||
}),
|
||||
})
|
||||
require.Len(t, cli.Tools(), 1)
|
||||
res, err := cli.Tools()[0].Execute(context.Background(), json.RawMessage(`{"q":"hello"}`))
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, res.Error)
|
||||
assert.Contains(t, res.Output, "hello")
|
||||
assert.JSONEq(t, `{"q":"hello"}`, string(sawArgs))
|
||||
}
|
||||
|
||||
func TestMCPAdapter_ExecuteErrorPath(t *testing.T) {
|
||||
cli := startInProcessServer(t, "srv", []sdkToolFixture{
|
||||
stringArgTool("boom", "fails", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
return nil, errors.New("kaboom")
|
||||
}),
|
||||
})
|
||||
require.Len(t, cli.Tools(), 1)
|
||||
res, err := cli.Tools()[0].Execute(context.Background(), json.RawMessage(`{}`))
|
||||
require.NoError(t, err, "Execute itself returns nil; the tool error surfaces in result.Error")
|
||||
assert.NotEmpty(t, res.Error, "MCP tool error must surface as ToolResult.Error")
|
||||
}
|
||||
|
||||
func TestMCPAdapter_ImageContentMapping(t *testing.T) {
|
||||
pngBytes := []byte{0x89, 'P', 'N', 'G', 0x0d}
|
||||
cli := startInProcessServer(t, "srv", []sdkToolFixture{
|
||||
stringArgTool("snap", "take a snapshot", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
return &sdk.CallToolResult{
|
||||
Content: []sdk.Content{
|
||||
&sdk.ImageContent{Data: pngBytes, MIMEType: "image/png"},
|
||||
&sdk.TextContent{Text: "caption"},
|
||||
},
|
||||
}, nil
|
||||
}),
|
||||
})
|
||||
require.Len(t, cli.Tools(), 1)
|
||||
res, err := cli.Tools()[0].Execute(context.Background(), json.RawMessage(`{}`))
|
||||
require.NoError(t, err)
|
||||
require.Len(t, res.Images, 1)
|
||||
assert.Equal(t, "image/png", res.Images[0].MimeType)
|
||||
assert.Equal(t, pngBytes, []byte(res.Images[0].Data))
|
||||
assert.Equal(t, "caption", res.Output)
|
||||
// Sanity: the harness ImageContent type is what tools expect.
|
||||
var _ llm.ImageContent = res.Images[0]
|
||||
}
|
||||
|
||||
func TestMCPClient_ConnectDiscovers(t *testing.T) {
|
||||
cli := startInProcessServer(t, "srv", []sdkToolFixture{
|
||||
stringArgTool("a", "first", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: ""}}}, nil
|
||||
}),
|
||||
stringArgTool("b", "second", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: ""}}}, nil
|
||||
}),
|
||||
})
|
||||
tools := cli.Tools()
|
||||
require.Len(t, tools, 2)
|
||||
got := []string{tools[0].Name(), tools[1].Name()}
|
||||
assert.ElementsMatch(t, []string{"mcp__srv__a", "mcp__srv__b"}, got)
|
||||
}
|
||||
|
||||
func TestMCPClient_CloseIsIdempotent(t *testing.T) {
|
||||
cli := startInProcessServer(t, "srv", []sdkToolFixture{
|
||||
stringArgTool("noop", "no-op", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: ""}}}, nil
|
||||
}),
|
||||
})
|
||||
require.NoError(t, cli.Close())
|
||||
require.NoError(t, cli.Close(), "second Close must be a no-op (no panic, no error)")
|
||||
}
|
||||
|
||||
func TestConnect_ValidatesConfig(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
_, err := Connect(ctx, ServerConfig{})
|
||||
require.Error(t, err, "empty config must fail")
|
||||
|
||||
_, err = Connect(ctx, ServerConfig{Name: "x"})
|
||||
require.Error(t, err, "no transport set must fail")
|
||||
|
||||
_, err = Connect(ctx, ServerConfig{Name: "x", Command: "true", URL: "http://x"})
|
||||
require.Error(t, err, "both transports set must fail")
|
||||
}
|
||||
|
||||
func TestMergeEnv_OverrideWins(t *testing.T) {
|
||||
base := []string{"PATH=/usr/bin", "FOO=bar"}
|
||||
out := mergeEnv(base, map[string]string{"FOO": "baz", "NEW": "v"})
|
||||
// The PATH entry must be preserved verbatim; FOO must be replaced;
|
||||
// NEW must be appended.
|
||||
assert.Contains(t, out, "PATH=/usr/bin")
|
||||
assert.NotContains(t, out, "FOO=bar")
|
||||
assert.Contains(t, out, "FOO=baz")
|
||||
assert.Contains(t, out, "NEW=v")
|
||||
}
|
||||
|
||||
// recordingRT captures every Request that hits its RoundTrip, then
|
||||
// returns a canned 200 response. Used to verify the headerInjector
|
||||
// passes headers through and doesn't mutate the caller's request.
|
||||
type recordingRT struct {
|
||||
mu sync.Mutex
|
||||
headers []http.Header
|
||||
}
|
||||
|
||||
func (r *recordingRT) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
r.mu.Lock()
|
||||
r.headers = append(r.headers, req.Header.Clone())
|
||||
r.mu.Unlock()
|
||||
return &http.Response{
|
||||
StatusCode: 200,
|
||||
Header: make(http.Header),
|
||||
Body: http.NoBody,
|
||||
Request: req,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func TestHeaderInjector_AddsHeadersAndDelegates(t *testing.T) {
|
||||
base := &recordingRT{}
|
||||
rt := &headerInjector{
|
||||
base: base,
|
||||
headers: map[string]string{"Authorization": "Bearer t1", "X-Trace": "abc"},
|
||||
}
|
||||
req, err := http.NewRequest("POST", "https://example.com/mcp", nil)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("X-Existing", "kept")
|
||||
|
||||
_, err = rt.RoundTrip(req)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Len(t, base.headers, 1)
|
||||
got := base.headers[0]
|
||||
assert.Equal(t, "Bearer t1", got.Get("Authorization"))
|
||||
assert.Equal(t, "abc", got.Get("X-Trace"))
|
||||
assert.Equal(t, "kept", got.Get("X-Existing"), "pre-existing headers must survive")
|
||||
|
||||
// The caller's req must NOT have been mutated.
|
||||
assert.Empty(t, req.Header.Get("Authorization"),
|
||||
"original request must remain unchanged so SDK retries see a clean req")
|
||||
}
|
||||
|
||||
func TestWrapHTTPClient_NoHeadersReturnsSameClient(t *testing.T) {
|
||||
in := &http.Client{}
|
||||
out := wrapHTTPClient(in, nil)
|
||||
assert.Same(t, in, out, "no headers ⇒ no copy, no wrap")
|
||||
}
|
||||
|
||||
func TestWrapHTTPClient_NilClientGetsDefaulted(t *testing.T) {
|
||||
out := wrapHTTPClient(nil, map[string]string{"X": "y"})
|
||||
require.NotNil(t, out)
|
||||
require.NotNil(t, out.Transport)
|
||||
_, ok := out.Transport.(*headerInjector)
|
||||
assert.True(t, ok, "headers ⇒ transport must be wrapped")
|
||||
}
|
||||
|
||||
func TestWrapHTTPClient_DoesNotMutateCallerClient(t *testing.T) {
|
||||
original := &http.Client{Transport: http.DefaultTransport}
|
||||
out := wrapHTTPClient(original, map[string]string{"X": "y"})
|
||||
assert.NotSame(t, original, out, "wrapping must clone the client")
|
||||
assert.Equal(t, http.DefaultTransport, original.Transport,
|
||||
"caller's Transport must be untouched")
|
||||
}
|
||||
|
||||
func TestBuildTransport_HTTPWithHeaders(t *testing.T) {
|
||||
tr, err := buildTransport(ServerConfig{
|
||||
Name: "x", URL: "https://example.com/mcp",
|
||||
Headers: map[string]string{"Authorization": "Bearer t1"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
st, ok := tr.(*sdk.StreamableClientTransport)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "https://example.com/mcp", st.Endpoint)
|
||||
require.NotNil(t, st.HTTPClient)
|
||||
_, ok = st.HTTPClient.Transport.(*headerInjector)
|
||||
assert.True(t, ok, "HTTPClient.Transport must be a headerInjector when Headers set")
|
||||
}
|
||||
|
||||
// TestStreamableHTTP_HeadersReachServer drives the whole transport via
|
||||
// httptest.Server to confirm headers actually arrive. The handshake
|
||||
// will fail (we don't speak MCP back), but the server captures the
|
||||
// inbound request before that — proving header propagation end-to-end
|
||||
// through the SDK.
|
||||
func TestStreamableHTTP_HeadersReachServer(t *testing.T) {
|
||||
var (
|
||||
mu sync.Mutex
|
||||
got http.Header
|
||||
)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
if got == nil {
|
||||
got = r.Header.Clone()
|
||||
}
|
||||
mu.Unlock()
|
||||
// Reply with something that won't satisfy the MCP handshake —
|
||||
// the transport will error, but only AFTER the server has seen
|
||||
// the request, which is what we're asserting.
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
ctx := context.Background()
|
||||
_, _ = Connect(ctx, ServerConfig{
|
||||
Name: "remote", URL: srv.URL,
|
||||
Headers: map[string]string{"Authorization": "Bearer real-token", "X-Tenant": "acme"},
|
||||
})
|
||||
// We don't assert err: depending on SDK retry behavior the call may
|
||||
// or may not return immediately. The header check is the contract.
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
require.NotNil(t, got, "server must have seen at least one request")
|
||||
assert.Equal(t, "Bearer real-token", got.Get("Authorization"),
|
||||
"Streamable HTTP transport must carry caller's Headers to the server")
|
||||
assert.Equal(t, "acme", got.Get("X-Tenant"))
|
||||
}
|
||||
Reference in new issue
Block a user