MCPcopy Create free account
hub / github.com/modelcontextprotocol/go-sdk / ServeHTTP

Method ServeHTTP

mcp/streamable_client_test.go:69–135  ·  view source on GitHub ↗
(w http.ResponseWriter, req *http.Request)

Source from the content-addressed store, hash-verified

67}
68
69func (s *fakeStreamableServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
70 key := streamableRequestKey{
71 httpMethod: req.Method,
72 sessionID: req.Header.Get(sessionIDHeader),
73 lastEventID: req.Header.Get(lastEventIDHeader),
74 }
75 var jsonrpcReq *jsonrpc.Request
76 if req.Method == http.MethodPost {
77 body, err := io.ReadAll(req.Body)
78 if err != nil {
79 s.t.Errorf("failed to read body: %v", err)
80 http.Error(w, "failed to read body", http.StatusInternalServerError)
81 return
82 }
83 msg, err := jsonrpc.DecodeMessage(body)
84 if err != nil {
85 s.t.Errorf("invalid body: %v", err)
86 http.Error(w, "invalid body", http.StatusInternalServerError)
87 return
88 }
89 if r, ok := msg.(*jsonrpc.Request); ok {
90 key.jsonrpcMethod = r.Method
91 jsonrpcReq = r
92 }
93 }
94
95 s.calledMu.Lock()
96 if s.called == nil {
97 s.called = make(map[streamableRequestKey]bool)
98 }
99 s.called[key] = true
100 s.calledMu.Unlock()
101
102 resp, ok := s.responses[key]
103 if !ok {
104 s.t.Errorf("missing response for %v", key)
105 http.Error(w, "no response", http.StatusInternalServerError)
106 return
107 }
108
109 // Determine body and status, potentially using responseFunc for dynamic responses.
110 body := resp.body
111 status := resp.status
112 if resp.responseFunc != nil {
113 body, status = resp.responseFunc(jsonrpcReq)
114 }
115 if status == 0 {
116 status = http.StatusOK
117 }
118
119 for k, v := range resp.header {
120 w.Header().Set(k, v)
121 }
122 rc := http.NewResponseController(w)
123 w.WriteHeader(status)
124 rc.Flush() // flush response headers
125
126 if v := req.Header.Get(protocolVersionHeader); v != resp.wantProtocolVersion && resp.wantProtocolVersion != "" {

Callers

nothing calls this directly

Calls 3

DecodeMessageFunction · 0.92
WriteMethod · 0.65
ErrorMethod · 0.45

Tested by

no test coverage detected