Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
208 changes: 208 additions & 0 deletions mcpcompat/server/instructions_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc.
// SPDX-License-Identifier: Apache-2.0

package server_test

import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/stacklok/toolhive-core/mcpcompat/server"
)

// callerFromHeader is a WithHTTPContextFunc that copies the X-Caller header
// into the request context under callerKey, the key skills_test.go declares.
// It stands in for ToolHive's identity middleware.
func callerFromHeader(ctx context.Context, r *http.Request) context.Context {
return context.WithValue(ctx, callerKey{}, r.Header.Get("X-Caller"))
}

// instructionsForCaller is a WithInstructionsFunc that greets the caller the
// context carries, proving the func sees the per-request context.
func instructionsForCaller(ctx context.Context) string {
caller, _ := ctx.Value(callerKey{}).(string)
if caller == "" {
return ""
}
return "instructions for " + caller
}

// legacyInitializeBody is a 2025-11-25 initialize request.
const legacyInitializeBody = `{"jsonrpc":"2.0","id":1,"method":"initialize","params":` +
`{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}`

// modernDiscoverBody is a SEP-2575 (2026-07-28) server/discover request: the
// handshake fields travel in _meta, and go-sdk serves the method only when
// the request declares the Modern revision (header + _meta).
const modernDiscoverBody = `{"jsonrpc":"2.0","id":1,"method":"server/discover","params":{"_meta":{` +
`"io.modelcontextprotocol/protocolVersion":"2026-07-28",` +
`"io.modelcontextprotocol/clientInfo":{"name":"test","version":"1.0"},` +
`"io.modelcontextprotocol/clientCapabilities":{}}}}`

// instructionsHTTPClient is the transport the tests in this file post with.
// httptest.Server.Close closes http.DefaultTransport's idle connections, so a
// parallel test's in-flight request on http.DefaultClient can fail with
// "CloseIdleConnections called". A transport of our own, with keep-alives
// off, keeps these tests out of that race (as reaping_internal_test.go does).
var instructionsHTTPClient = &http.Client{Transport: &http.Transport{DisableKeepAlives: true}}

// postRaw sends one JSON-RPC request with an optional X-Caller header and
// returns the result object, with the raw bytes for absence checks.
func postRaw(t *testing.T, url, method, caller string) (map[string]json.RawMessage, string) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
body, version := legacyInitializeBody, "2025-11-25"
if method == "server/discover" {
body, version = modernDiscoverBody, "2026-07-28"
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader(body))
require.NoError(t, err)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json, text/event-stream")
req.Header.Set("MCP-Protocol-Version", version)
if method == "server/discover" {
// SEP-2575 routing header, required on every Modern request.
req.Header.Set("Mcp-Method", method)
}
if caller != "" {
req.Header.Set("X-Caller", caller)
}
resp, err := instructionsHTTPClient.Do(req)
require.NoError(t, err)
r := readFirstResult(t, resp)
require.Nil(t, r.Error, "%s must not error", method)
var result map[string]json.RawMessage
require.NoError(t, json.Unmarshal(r.Result, &result))
return result, string(r.Result)
}

func instructionsOf(t *testing.T, result map[string]json.RawMessage) string {
t.Helper()
raw, ok := result["instructions"]
if !ok {
return ""
}
var s string
require.NoError(t, json.Unmarshal(raw, &s))
return s
}

func TestInstructions_AbsentByDefault(t *testing.T) {
t.Parallel()
ts := httptest.NewServer(server.NewStreamableHTTPServer(server.NewMCPServer("plain", "1.0.0")))
defer ts.Close()

_, raw := postRaw(t, ts.URL, "initialize", "")
assert.NotContains(t, raw, `"instructions"`, "no option set: the key must be absent, as before")
}

func TestInstructions_Static(t *testing.T) {
t.Parallel()
srv := server.NewMCPServer("static", "1.0.0", server.WithInstructions("Start with hello."))
ts := httptest.NewServer(server.NewStreamableHTTPServer(srv))
defer ts.Close()

result, _ := postRaw(t, ts.URL, "initialize", "")
assert.Equal(t, "Start with hello.", instructionsOf(t, result))
}

func TestInstructions_FuncSeesRequestContext(t *testing.T) {
t.Parallel()
srv := server.NewMCPServer("dynamic", "1.0.0",
server.WithInstructions("static text, must lose"),
server.WithInstructionsFunc(instructionsForCaller))
ts := httptest.NewServer(server.NewStreamableHTTPServer(srv, server.WithHTTPContextFunc(callerFromHeader)))
defer ts.Close()

alice, _ := postRaw(t, ts.URL, "initialize", "alice")
assert.Equal(t, "instructions for alice", instructionsOf(t, alice))

bob, _ := postRaw(t, ts.URL, "initialize", "bob")
assert.Equal(t, "instructions for bob", instructionsOf(t, bob), "each initialize is answered for its own caller")

_, raw := postRaw(t, ts.URL, "initialize", "")
assert.NotContains(t, raw, `"instructions"`, "an empty func result omits the key")
}

func TestInstructions_FuncOnStatelessServer(t *testing.T) {
t.Parallel()
srv := server.NewMCPServer("stateless", "1.0.0", server.WithInstructionsFunc(instructionsForCaller))
ts := httptest.NewServer(server.NewStreamableHTTPServer(srv,
server.WithStateless(true), server.WithHTTPContextFunc(callerFromHeader)))
defer ts.Close()

result, _ := postRaw(t, ts.URL, "initialize", "carol")
assert.Equal(t, "instructions for carol", instructionsOf(t, result))
}

func TestInstructions_Discover(t *testing.T) {
t.Parallel()
t.Run("static", func(t *testing.T) {
t.Parallel()
srv := server.NewMCPServer("discover-static", "1.0.0", server.WithInstructions("Static for discover."))
ts := httptest.NewServer(server.NewStreamableHTTPServer(srv))
defer ts.Close()

result, _ := postRaw(t, ts.URL, "server/discover", "")
assert.Equal(t, "Static for discover.", instructionsOf(t, result))
})
t.Run("func", func(t *testing.T) {
t.Parallel()
srv := server.NewMCPServer("discover-func", "1.0.0", server.WithInstructionsFunc(instructionsForCaller))
ts := httptest.NewServer(server.NewStreamableHTTPServer(srv, server.WithHTTPContextFunc(callerFromHeader)))
defer ts.Close()

result, _ := postRaw(t, ts.URL, "server/discover", "dave")
assert.Equal(t, "instructions for dave", instructionsOf(t, result))
})
}

func TestInstructions_HandleMessage(t *testing.T) {
t.Parallel()
const initialize = `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}`

t.Run("static", func(t *testing.T) {
t.Parallel()
srv := server.NewMCPServer("hm-static", "1.0.0", server.WithInstructions("Static via HandleMessage."))
resp := handleMessageResult(context.Background(), t, srv, initialize)
assert.Equal(t, "Static via HandleMessage.", resp["instructions"])
})
t.Run("func", func(t *testing.T) {
t.Parallel()
srv := server.NewMCPServer("hm-func", "1.0.0", server.WithInstructionsFunc(instructionsForCaller))
ctx := context.WithValue(context.Background(), callerKey{}, "erin")
resp := handleMessageResult(ctx, t, srv, initialize)
assert.Equal(t, "instructions for erin", resp["instructions"])
})
t.Run("absent", func(t *testing.T) {
t.Parallel()
srv := server.NewMCPServer("hm-plain", "1.0.0")
resp := handleMessageResult(context.Background(), t, srv, initialize)
_, present := resp["instructions"]
assert.False(t, present)
})
}

// handleMessageResult runs one message through the shim's own dispatcher and
// returns the decoded result object.
func handleMessageResult(ctx context.Context, t *testing.T, srv *server.MCPServer, message string) map[string]any {
t.Helper()
msg := srv.HandleMessage(ctx, json.RawMessage(message))
require.NotNil(t, msg)
data, err := json.Marshal(msg)
require.NoError(t, err)
var resp map[string]any
require.NoError(t, json.Unmarshal(data, &resp))
result, ok := resp["result"].(map[string]any)
require.True(t, ok, "response must carry a result: %s", data)
return result
}
5 changes: 3 additions & 2 deletions mcpcompat/server/request_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ func (s *MCPServer) HandleMessage(ctx context.Context, message json.RawMessage)
func (s *MCPServer) dispatch(ctx context.Context, method string, id any, message json.RawMessage) mcp.JSONRPCMessage {
switch method {
case string(mcp.MethodInitialize):
return successResponse(id, s.handleInitialize())
return successResponse(id, s.handleInitialize(ctx))
case string(mcp.MethodPing):
return successResponse(id, mcp.EmptyResult{})
case string(mcp.MethodToolsList):
Expand All @@ -88,11 +88,12 @@ func (s *MCPServer) dispatch(ctx context.Context, method string, id any, message
}
}

func (s *MCPServer) handleInitialize() mcp.InitializeResult {
func (s *MCPServer) handleInitialize(ctx context.Context) mcp.InitializeResult {
return mcp.InitializeResult{
ProtocolVersion: mcp.LATEST_PROTOCOL_VERSION,
ServerInfo: mcp.Implementation{Name: s.name, Version: s.version},
Capabilities: s.buildCapabilities(),
Instructions: s.instructionsFor(ctx),
}
}

Expand Down
71 changes: 71 additions & 0 deletions mcpcompat/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,14 @@ type MCPServer struct {
directoryReadDeclared bool
readDirectory ReadDirectoryHandlerFunc

// instructions, set via WithInstructions, is the text advertised to every
// client in the initialize and server/discover results (mirrors mcp-go's
// WithInstructions). instructionsFunc, set via WithInstructionsFunc,
// computes that text per request from the request context instead, and
// wins over instructions when both are set.
instructions string
instructionsFunc InstructionsFunc

mu sync.RWMutex
tools map[string]ServerTool
resources map[string]ServerResource
Expand Down Expand Up @@ -439,6 +447,40 @@ func WithPageSize(n int) ServerOption {
}
}

// InstructionsFunc computes the server instructions to advertise for one
// request. ctx is the request context: on the Streamable HTTP transport it
// carries whatever WithHTTPContextFunc stored (ToolHive stores the caller's
// identity there), so the text can differ per caller. An empty result omits
// the field, exactly as an unset WithInstructions does.
type InstructionsFunc func(ctx context.Context) string

// WithInstructions sets the server instructions advertised to every client in
// the initialize and server/discover results (mirrors mcp-go's
// WithInstructions). The default, an empty string, omits the field.
func WithInstructions(instructions string) ServerOption {
return func(s *MCPServer) { s.instructions = instructions }
}

// WithInstructionsFunc computes the server instructions per request instead of
// once at construction. go-sdk copies ServerOptions.Instructions verbatim into
// every initialize and server/discover result and offers no per-session hook,
// so the shim overwrites the field on the result after go-sdk built it (see
// applyInstructionsFunc). An aggregator uses this to advertise only the
// instructions of the backends the calling identity may reach. When both
// options are set the func wins; a nil fn leaves WithInstructions in force.
func WithInstructionsFunc(fn InstructionsFunc) ServerOption {
return func(s *MCPServer) { s.instructionsFunc = fn }
}

// instructionsFor returns the instructions to advertise for ctx: the
// per-request func when one is set, else the static text.
func (s *MCPServer) instructionsFor(ctx context.Context) string {
if s.instructionsFunc != nil {
return s.instructionsFunc(ctx)
}
return s.instructions
}

// AddTool registers a tool and its handler.
func (s *MCPServer) AddTool(tool mcp.Tool, handler ToolHandlerFunc) {
s.mu.Lock()
Expand Down Expand Up @@ -602,6 +644,9 @@ func (s *MCPServer) buildServer(genSessionID func() string, stateless bool) (*go
var srv *gosdk.Server
opts := &gosdk.ServerOptions{
Logger: s.logger,
// The static text; applyInstructionsFunc overrides it per request when
// WithInstructionsFunc is set.
Instructions: s.instructions,
// PageSize configures list pagination. A zero value leaves go-sdk's
// DefaultPageSize (1000) in place, preserving the pre-existing behavior
// for callers that do not set WithPageSize.
Expand Down Expand Up @@ -874,6 +919,7 @@ func (s *MCPServer) sessionDispatchMiddleware(srv *gosdk.Server, stateless bool)
// an HTTP Cache-Control header.
if err == nil {
s.stripPublicCacheScope(res)
s.applyInstructionsFunc(ctx, method, res)
}
if err != nil && method == string(mcp.MethodToolsCall) {
err = translateUnknownToolError(err, req)
Expand All @@ -894,6 +940,31 @@ func (s *MCPServer) sessionDispatchMiddleware(srv *gosdk.Server, stateless bool)
}
}

// methodServerDiscover is the SEP-2575 server/discover method. go-sdk keeps
// its own constant unexported, so name it here.
const methodServerDiscover = "server/discover"

// applyInstructionsFunc replaces the instructions go-sdk copied from
// ServerOptions.Instructions on an initialize or server/discover result with
// the per-request text of WithInstructionsFunc. It is a result rewrite like
// stripPublicCacheScope, for the same reason: go-sdk exposes no per-session
// hook for the field. Without a func the static text stays as go-sdk set it.
func (s *MCPServer) applyInstructionsFunc(ctx context.Context, method string, res gosdk.Result) {
if s.instructionsFunc == nil {
return
}
switch r := res.(type) {
case *gosdk.InitializeResult:
if method == string(mcp.MethodInitialize) && r != nil {
r.Instructions = s.instructionsFunc(ctx)
}
case *gosdk.DiscoverResult:
if method == methodServerDiscover && r != nil {
r.Instructions = s.instructionsFunc(ctx)
}
}
}

// The two members of the MCP cacheScope union. go-sdk models CacheScope as a
// bare string and exports no constants for it, so name them here.
const (
Expand Down
6 changes: 3 additions & 3 deletions mcpcompat/server/transports.go
Original file line number Diff line number Diff line change
Expand Up @@ -481,9 +481,9 @@ func (s *StreamableHTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request)
// middleware reads it back via req.GetExtra().Header to bridge the values.
// Keying by nonce (not session ID) avoids the race where concurrent POSTs
// on the same session clobber each other's context (issue #156, item U3).
// The initialize POST (no session yet) carries no per-request values the
// handler needs; only non-initialize POSTs need bridging, but bridging
// initialize is harmless.
// The initialize POST (no session yet) is bridged too, and must stay so:
// WithInstructionsFunc reads the caller's identity from the bridged
// context when it computes the initialize (and server/discover) result.
nonce := crand.Text()
s.mcp.setPendingRequestContext(r.Context(), nonce)
r.Header.Set(reqNonceHeader, nonce)
Expand Down