// Package mcptest is an MCP server for tests: a few tools, a session it // gives at initialize and can forget, its tool list in pages, and answers // as JSON or, when asked, as a stream with progress before the answer. package mcptest import ( "encoding/json" "fmt" "net/http" "net/http/httptest" "strings" "sync" ) // Server is the fake server and what it saw. type Server struct { *httptest.Server // Stream answers tools/call as server-sent events, with a progress // notification first. Stream bool // PageSize splits the tool list into pages; zero sends it whole. PageSize int mu sync.Mutex session string sessions int // Calls are the tools called, and Headers the headers of each call. Calls []string Args []json.RawMessage Headers []http.Header } // Tools are what it offers: echo returns its text, fail answers with a // tool error, big returns more than most limits allow. var Tools = []map[string]any{ {"name": "echo", "description": "Says the text back.", "inputSchema": map[string]any{ "type": "object", "properties": map[string]any{"text": map[string]any{"type": "string"}}}}, {"name": "fail", "description": "Always fails.", "inputSchema": map[string]any{"type": "object"}}, {"name": "big", "description": "Answers with a megabyte.", "inputSchema": map[string]any{"type": "object"}}, } // New starts one. func New() *Server { s := &Server{} s.Server = httptest.NewServer(http.HandlerFunc(s.serve)) return s } // Forget drops the session, as a restarted server would. func (s *Server) Forget() { s.mu.Lock() s.session = "" s.mu.Unlock() } // Sessions is how many times it was initialized. func (s *Server) Sessions() int { s.mu.Lock() defer s.mu.Unlock() return s.sessions } func (s *Server) serve(w http.ResponseWriter, r *http.Request) { var msg struct { ID json.RawMessage `json:"id"` Method string `json:"method"` Params json.RawMessage `json:"params"` } if json.NewDecoder(r.Body).Decode(&msg) != nil { http.Error(w, "bad", http.StatusBadRequest) return } s.mu.Lock() if msg.Method == "initialize" { s.sessions++ s.session = fmt.Sprintf("s%d", s.sessions) w.Header().Set("Mcp-Session-Id", s.session) } else if r.Header.Get("Mcp-Session-Id") != s.session || s.session == "" { s.mu.Unlock() http.Error(w, "no such session", http.StatusNotFound) return } s.mu.Unlock() if len(msg.ID) == 0 { w.WriteHeader(http.StatusAccepted) return } answer := func(result any) { w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": msg.ID, "result": result}) } switch msg.Method { case "initialize": answer(map[string]any{"protocolVersion": "2025-06-18", "capabilities": map[string]any{"tools": map[string]any{}}, "serverInfo": map[string]any{"name": "test", "version": "1"}}) case "tools/list": var p struct { Cursor string `json:"cursor"` } _ = json.Unmarshal(msg.Params, &p) start := 0 _, _ = fmt.Sscan(p.Cursor, &start) end := len(Tools) if s.PageSize > 0 && start+s.PageSize < end { end = start + s.PageSize } res := map[string]any{"tools": Tools[start:end]} if end < len(Tools) { res["nextCursor"] = fmt.Sprint(end) } answer(res) case "tools/call": var p struct { Name string `json:"name"` Arguments json.RawMessage `json:"arguments"` } _ = json.Unmarshal(msg.Params, &p) s.mu.Lock() s.Calls, s.Args, s.Headers = append(s.Calls, p.Name), append(s.Args, p.Arguments), append(s.Headers, r.Header.Clone()) s.mu.Unlock() var result map[string]any switch p.Name { case "echo": var a struct { Text string `json:"text"` } _ = json.Unmarshal(p.Arguments, &a) result = map[string]any{"content": []any{map[string]any{"type": "text", "text": a.Text}}} case "fail": result = map[string]any{"content": []any{map[string]any{"type": "text", "text": "it failed"}}, "isError": true} case "big": result = map[string]any{"content": []any{map[string]any{"type": "text", "text": strings.Repeat("x", 1<<20)}}} default: w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": msg.ID, "error": map[string]any{"code": -32602, "message": "unknown tool " + p.Name}}) return } if s.Stream { w.Header().Set("Content-Type", "text/event-stream") fmt.Fprintf(w, "data: %s\n\n", mustJSON(map[string]any{"jsonrpc": "2.0", "method": "notifications/progress", "params": map[string]any{"progress": 1, "total": 2, "message": "halfway"}})) fmt.Fprintf(w, "event: message\ndata: %s\n\n", mustJSON(map[string]any{"jsonrpc": "2.0", "id": msg.ID, "result": result})) return } answer(result) default: w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": msg.ID, "error": map[string]any{"code": -32601, "message": "method not found"}}) } } func mustJSON(v any) string { b, _ := json.Marshal(v) return string(b) }