mirror of
https://github.com/coder/coder.git
synced 2026-11-01 04:47:17 +08:00
## Stack Context PR 3 of 6 in a stack that migrates every Coder MCP surface from the archived `github.com/mark3labs/mcp-go` library to the official `github.com/modelcontextprotocol/go-sdk` v1.7.0. Stack: #28056 -> #28057 -> #28058 -> #28059 -> #28060 -> #28061 ## Why The chatd external MCP client (admin-configured MCP servers used by Agent chat) now holds `*mcp.ClientSession` connections created via `mcp.NewClient` and `Client.Connect`, with `StreamableClientTransport` or `SSEClientTransport` per server config. - Auth and identity headers are injected through a custom `http.RoundTripper` because the official SDK has no per-header transport options. - Tool input schemas are extracted from the SDK's `map[string]any` decoding. - Content conversion handles the official pointer content types; the SDK decodes blob resources into raw bytes, so binary content is handled without an extra base64 round trip. - Test fixtures are official stateless Streamable HTTP servers. > Mux created this PR on Mike's behalf.
53 lines
1.4 KiB
Go
53 lines
1.4 KiB
Go
package mcpclient
|
|
|
|
import (
|
|
"flag"
|
|
"net/http"
|
|
)
|
|
|
|
func httpClientWithHeaders(headers map[string]string) *http.Client {
|
|
base := http.DefaultTransport
|
|
if isolated := mcpHTTPClient(); isolated != nil {
|
|
base = isolated.Transport
|
|
}
|
|
if len(headers) == 0 {
|
|
return &http.Client{Transport: base}
|
|
}
|
|
return &http.Client{Transport: &headerRoundTripper{
|
|
base: base,
|
|
headers: headers,
|
|
}}
|
|
}
|
|
|
|
type headerRoundTripper struct {
|
|
base http.RoundTripper
|
|
headers map[string]string
|
|
}
|
|
|
|
func (h *headerRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
|
|
clone := req.Clone(req.Context())
|
|
for k, v := range h.headers {
|
|
clone.Header.Set(k, v)
|
|
}
|
|
return h.base.RoundTrip(clone)
|
|
}
|
|
|
|
// mcpHTTPClient returns an isolated *http.Client when running
|
|
// inside tests, or nil for production. During tests,
|
|
// httptest.Server.Close() calls
|
|
// http.DefaultTransport.CloseIdleConnections(), which disrupts
|
|
// any MCP client sharing that transport. When DefaultTransport
|
|
// is a *http.Transport it is cloned; otherwise a minimal
|
|
// transport with ProxyFromEnvironment is created as a fallback.
|
|
func mcpHTTPClient() *http.Client {
|
|
if flag.Lookup("test.v") == nil {
|
|
return nil
|
|
}
|
|
if dt, ok := http.DefaultTransport.(*http.Transport); ok {
|
|
return &http.Client{Transport: dt.Clone()}
|
|
}
|
|
return &http.Client{Transport: &http.Transport{
|
|
Proxy: http.ProxyFromEnvironment,
|
|
}}
|
|
}
|