mirror of
https://github.com/coder/coder.git
synced 2026-10-31 19:36:41 +08:00
## Stack Context PR 4 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 workspace agent MCP manager now stores `*mcp.ClientSession` per configured server. - stdio servers use `mcp.CommandTransport` with an `exec.Cmd` built from Coder's `agentexec.Execer`, preserving environment enrichment; the command uses the manager's parent context so a stdio subprocess outlives the connect handshake and stops when the session closes. - HTTP and SSE servers use header-injecting HTTP clients. - Binary tool content is re-encoded to base64 for the agent API because the official SDK decodes it into raw bytes. - The reload test now triggers config diffs via an environment variable because the official SDK drops connections on non-protocol stdout output (flags like `-test.v` made the fake server chatty). > Mux created this PR on Mike's behalf.
53 lines
1.4 KiB
Go
53 lines
1.4 KiB
Go
package agentmcp
|
|
|
|
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,
|
|
}}
|
|
}
|