|
| 1 | +package testutil |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "net/http" |
| 8 | + "net/http/httptest" |
| 9 | + "sync" |
| 10 | + "testing" |
| 11 | + "time" |
| 12 | + |
| 13 | + "cdr.dev/slog/v3" |
| 14 | + "cdr.dev/slog/v3/sloggers/slogtest" |
| 15 | + "github.com/coder/aibridge/mcp" |
| 16 | + "github.com/mark3labs/mcp-go/client/transport" |
| 17 | + mcplib "github.com/mark3labs/mcp-go/mcp" |
| 18 | + "github.com/mark3labs/mcp-go/server" |
| 19 | + "github.com/stretchr/testify/require" |
| 20 | + "go.opentelemetry.io/otel/trace" |
| 21 | + "go.opentelemetry.io/otel/trace/noop" |
| 22 | +) |
| 23 | + |
| 24 | +// MockToolName is the primary mock tool name used in MCP tests. |
| 25 | +const MockToolName = "coder_list_workspaces" |
| 26 | + |
| 27 | +// MockMCP wraps a real mcp.ServerProxier with test assertion helpers. |
| 28 | +// Implements mcp.ServerProxier so it can be passed directly to NewRequestBridge. |
| 29 | +type MockMCP struct { |
| 30 | + mcp.ServerProxier |
| 31 | + calls *callAccumulator |
| 32 | +} |
| 33 | + |
| 34 | +// GetCallsByTool returns recorded arguments for a given tool name. |
| 35 | +func (m *MockMCP) GetCallsByTool(name string) []any { |
| 36 | + return m.calls.getCallsByTool(name) |
| 37 | +} |
| 38 | + |
| 39 | +// SetToolError configures a tool to return an error when invoked. |
| 40 | +func (m *MockMCP) SetToolError(tool, errMsg string) { |
| 41 | + m.calls.setToolError(tool, errMsg) |
| 42 | +} |
| 43 | + |
| 44 | +// SetupMCPForTest creates a ready-to-use MCP server with proxy named "coder". |
| 45 | +func SetupMCPForTest(t *testing.T, tracer trace.Tracer) *MockMCP { |
| 46 | + t.Helper() |
| 47 | + return SetupMCPForTestWithName(t, "coder", tracer) |
| 48 | +} |
| 49 | + |
| 50 | +func SetupMCPForTestWithName(t *testing.T, name string, tracer trace.Tracer) *MockMCP { |
| 51 | + t.Helper() |
| 52 | + |
| 53 | + srv, acc := createMockMCPSrv(t) |
| 54 | + mcpSrv := httptest.NewServer(srv) |
| 55 | + t.Cleanup(mcpSrv.Close) // FIRST registered → runs LAST (LIFO) |
| 56 | + |
| 57 | + logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: false}).Leveled(slog.LevelDebug) |
| 58 | + // Use a dedicated HTTP client so MCP mocks don't use http.DefaultTransport, |
| 59 | + // which can break when httptest.Server calls CloseIdleConnections in parallel |
| 60 | + // resulting in error `init MCP client: failed to send initialized notification: failed to send request: failed to send request: Post "http://127.0.0.1:43843": net/http: HTTP/1.x transport connection broken: http: CloseIdleConnections called` |
| 61 | + // https://github.com/golang/go/blob/44ec057a3e89482cf775f5eaaf03b0b5fcab1fa4/src/net/http/httptest/server.go#L268 |
| 62 | + httpClient := &http.Client{Transport: &http.Transport{}} |
| 63 | + proxy, err := mcp.NewStreamableHTTPServerProxy(name, mcpSrv.URL, nil, nil, nil, logger, tracer, transport.WithHTTPBasicClient(httpClient)) |
| 64 | + require.NoError(t, err) |
| 65 | + |
| 66 | + mgr := mcp.NewServerProxyManager(map[string]mcp.ServerProxier{proxy.Name(): proxy}, tracer) |
| 67 | + t.Cleanup(func() { |
| 68 | + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 69 | + defer cancel() |
| 70 | + require.NoError(t, mgr.Shutdown(ctx)) |
| 71 | + }) |
| 72 | + |
| 73 | + ctx, cancel := context.WithTimeout(t.Context(), time.Second*30) |
| 74 | + t.Cleanup(cancel) |
| 75 | + require.NoError(t, mgr.Init(ctx)) |
| 76 | + require.NotEmpty(t, mgr.ListTools(), "mock MCP server should expose tools after init") |
| 77 | + |
| 78 | + return &MockMCP{ServerProxier: mgr, calls: acc} |
| 79 | +} |
| 80 | + |
| 81 | +func NilMCPManager() mcp.ServerProxier { |
| 82 | + return mcp.NewServerProxyManager(nil, noop.NewTracerProvider().Tracer("")) |
| 83 | +} |
| 84 | + |
| 85 | +// callAccumulator tracks all tool invocations by name and each instance's arguments. |
| 86 | +type callAccumulator struct { |
| 87 | + calls map[string][]any |
| 88 | + callsMu sync.Mutex |
| 89 | + toolErrors map[string]string |
| 90 | +} |
| 91 | + |
| 92 | +func newCallAccumulator() *callAccumulator { |
| 93 | + return &callAccumulator{ |
| 94 | + calls: make(map[string][]any), |
| 95 | + toolErrors: make(map[string]string), |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +func (a *callAccumulator) setToolError(tool string, errMsg string) { |
| 100 | + a.callsMu.Lock() |
| 101 | + defer a.callsMu.Unlock() |
| 102 | + a.toolErrors[tool] = errMsg |
| 103 | +} |
| 104 | + |
| 105 | +func (a *callAccumulator) getToolError(tool string) (string, bool) { |
| 106 | + a.callsMu.Lock() |
| 107 | + defer a.callsMu.Unlock() |
| 108 | + errMsg, ok := a.toolErrors[tool] |
| 109 | + return errMsg, ok |
| 110 | +} |
| 111 | + |
| 112 | +func (a *callAccumulator) addCall(tool string, args any) { |
| 113 | + a.callsMu.Lock() |
| 114 | + defer a.callsMu.Unlock() |
| 115 | + a.calls[tool] = append(a.calls[tool], args) |
| 116 | +} |
| 117 | + |
| 118 | +func (a *callAccumulator) getCallsByTool(name string) []any { |
| 119 | + a.callsMu.Lock() |
| 120 | + defer a.callsMu.Unlock() |
| 121 | + result := make([]any, len(a.calls[name])) |
| 122 | + copy(result, a.calls[name]) |
| 123 | + return result |
| 124 | +} |
| 125 | + |
| 126 | +func createMockMCPSrv(t *testing.T) (http.Handler, *callAccumulator) { |
| 127 | + t.Helper() |
| 128 | + |
| 129 | + s := server.NewMCPServer( |
| 130 | + "Mock coder MCP server", |
| 131 | + "1.0.0", |
| 132 | + server.WithToolCapabilities(true), |
| 133 | + ) |
| 134 | + |
| 135 | + acc := newCallAccumulator() |
| 136 | + |
| 137 | + for _, name := range []string{MockToolName, "coder_list_templates", "coder_template_version_parameters", "coder_get_authenticated_user", "coder_create_workspace_build", "coder_delete_template"} { |
| 138 | + tool := mcplib.NewTool(name, |
| 139 | + mcplib.WithDescription(fmt.Sprintf("Mock of the %s tool", name)), |
| 140 | + ) |
| 141 | + s.AddTool(tool, func(ctx context.Context, request mcplib.CallToolRequest) (*mcplib.CallToolResult, error) { |
| 142 | + acc.addCall(request.Params.Name, request.Params.Arguments) |
| 143 | + if errMsg, ok := acc.getToolError(request.Params.Name); ok { |
| 144 | + return nil, errors.New(errMsg) |
| 145 | + } |
| 146 | + return mcplib.NewToolResultText("mock"), nil |
| 147 | + }) |
| 148 | + } |
| 149 | + |
| 150 | + return server.NewStreamableHTTPServer(s), acc |
| 151 | +} |
0 commit comments