Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

refactor(mcp): extract shared HTTP helpers for tool reuse (#19617)

Vincent Huang97405134cca0
diff --git a/backend/api/mcp/tool_call.go b/backend/api/mcp/tool_call.go
index d2b0451ab7..b3e7580631 100644
--- a/backend/api/mcp/tool_call.go
+++ b/backend/api/mcp/tool_call.go
@@ -1,14 +1,10 @@
package mcp
import (
- "bytes"
"context"
"encoding/json"
"fmt"
- "io"
- "net/http"
"strings"
- "time"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/pkg/errors"
@@ -72,72 +68,36 @@ func (s *Server) handleCallAPI(ctx context.Context, _ *mcp.CallToolRequest, inpu
if body == nil {
body = make(map[string]any)
}
- bodyBytes, err := json.Marshal(body)
- if err != nil {
- return nil, nil, errors.Wrap(err, "failed to marshal request body")
- }
-
- // Build HTTP request
- url := fmt.Sprintf("http://localhost:%d%s", s.profile.Port, endpoint.Path)
- httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(bodyBytes))
- if err != nil {
- return nil, nil, errors.Wrap(err, "failed to create HTTP request")
- }
-
- // Set headers for Connect RPC
- httpReq.Header.Set("Content-Type", "application/json")
- httpReq.Header.Set("Connect-Protocol-Version", "1")
- // Forward the auth token from the MCP context
- if token := getAccessToken(ctx); token != "" {
- httpReq.Header.Set("Authorization", "Bearer "+token)
- }
-
- // Execute request with timeout
- client := &http.Client{Timeout: 30 * time.Second}
- resp, err := client.Do(httpReq)
- if err != nil {
- return nil, nil, errors.Wrap(err, "failed to execute API request")
- }
- defer resp.Body.Close()
-
- // Read response body
- respBody, err := io.ReadAll(resp.Body)
+ // Execute API request
+ resp, err := s.apiRequest(ctx, endpoint.Path, body)
if err != nil {
- return nil, nil, errors.Wrap(err, "failed to read response body")
+ return nil, nil, err
}
// Check for binary response - not supported
- contentType := resp.Header.Get("Content-Type")
+ contentType := resp.Headers.Get("Content-Type")
if isBinaryContentType(contentType) {
return nil, nil, errors.Errorf("binary response not supported (content-type: %s)", contentType)
}
// Parse JSON response
- var respJSON any
- if len(respBody) > 0 {
- if err := json.Unmarshal(respBody, &respJSON); err != nil {
- // If not valid JSON, return as string
- respJSON = string(respBody)
- }
- }
-
output := CallOutput{
- Status: resp.StatusCode,
- Response: respJSON,
+ Status: resp.Status,
+ }
+ if len(resp.Body) > 0 {
+ var respJSON any
+ if json.Unmarshal(resp.Body, &respJSON) != nil {
+ respJSON = string(resp.Body)
+ }
+ output.Response = respJSON
}
// Check for error response
- if resp.StatusCode >= 400 {
- if errMap, ok := respJSON.(map[string]any); ok {
- if msg, ok := errMap["message"].(string); ok {
- output.Error = msg
- } else if code, ok := errMap["code"].(string); ok {
- output.Error = code
- }
- }
+ if resp.Status >= 400 {
+ output.Error = parseError(resp.Body)
if output.Error == "" {
- output.Error = fmt.Sprintf("HTTP %d", resp.StatusCode)
+ output.Error = fmt.Sprintf("HTTP %d", resp.Status)
}
}
@@ -186,19 +146,3 @@ func isBinaryContentType(ct string) bool {
}
return false
}
-
-// Context key for storing the access token.
-type accessTokenKey struct{}
-
-// withAccessToken adds the access token to the context.
-func withAccessToken(ctx context.Context, token string) context.Context {
- return context.WithValue(ctx, accessTokenKey{}, token)
-}
-
-// getAccessToken retrieves the access token from the context.
-func getAccessToken(ctx context.Context) string {
- if token, ok := ctx.Value(accessTokenKey{}).(string); ok {
- return token
- }
- return ""
-}
diff --git a/backend/api/mcp/tool_http.go b/backend/api/mcp/tool_http.go
new file mode 100644
index 0000000000..657013ac45
--- /dev/null
+++ b/backend/api/mcp/tool_http.go
@@ -0,0 +1,97 @@
+package mcp
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "time"
+
+ "github.com/pkg/errors"
+)
+
+// apiResponse holds the HTTP response from an internal API call.
+type apiResponse struct {
+ Status int
+ Body json.RawMessage
+ Headers http.Header
+}
+
+// apiRequest executes an HTTP POST to an internal Bytebase API endpoint.
+// It handles URL building, auth forwarding, Connect-RPC headers, and JSON marshaling.
+func (s *Server) apiRequest(ctx context.Context, path string, body any) (*apiResponse, error) {
+ var bodyBytes []byte
+ var err error
+ if body != nil {
+ bodyBytes, err = json.Marshal(body)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to marshal request body")
+ }
+ } else {
+ bodyBytes = []byte("{}")
+ }
+
+ url := fmt.Sprintf("http://localhost:%d%s", s.profile.Port, path)
+ httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(bodyBytes))
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to create HTTP request")
+ }
+
+ httpReq.Header.Set("Content-Type", "application/json")
+ httpReq.Header.Set("Connect-Protocol-Version", "1")
+
+ if token := getAccessToken(ctx); token != "" {
+ httpReq.Header.Set("Authorization", "Bearer "+token)
+ }
+
+ client := &http.Client{Timeout: 30 * time.Second}
+ resp, err := client.Do(httpReq)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to execute API request")
+ }
+ defer resp.Body.Close()
+
+ respBody, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to read response body")
+ }
+
+ return &apiResponse{
+ Status: resp.StatusCode,
+ Body: json.RawMessage(respBody),
+ Headers: resp.Header,
+ }, nil
+}
+
+// parseError extracts the error message from an API error response body.
+func parseError(body json.RawMessage) string {
+ var errMap map[string]any
+ if json.Unmarshal(body, &errMap) != nil {
+ return ""
+ }
+ if msg, ok := errMap["message"].(string); ok {
+ return msg
+ }
+ if code, ok := errMap["code"].(string); ok {
+ return code
+ }
+ return ""
+}
+
+// Context key for storing the access token.
+type accessTokenKey struct{}
+
+// withAccessToken adds the access token to the context.
+func withAccessToken(ctx context.Context, token string) context.Context {
+ return context.WithValue(ctx, accessTokenKey{}, token)
+}
+
+// getAccessToken retrieves the access token from the context.
+func getAccessToken(ctx context.Context) string {
+ if token, ok := ctx.Value(accessTokenKey{}).(string); ok {
+ return token
+ }
+ return ""
+}
diff --git a/backend/api/mcp/tool_http_test.go b/backend/api/mcp/tool_http_test.go
new file mode 100644
index 0000000000..d90356ad26
--- /dev/null
+++ b/backend/api/mcp/tool_http_test.go
@@ -0,0 +1,87 @@
+package mcp
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/component/config"
+)
+
+// newTestServerWithMock creates a *Server backed by a mock HTTP server.
+// The mock server is automatically closed when the test completes.
+func newTestServerWithMock(t *testing.T, handler http.Handler) *Server {
+ t.Helper()
+ mock := httptest.NewServer(handler)
+ t.Cleanup(mock.Close)
+ // Parse port from URL like "http://127.0.0.1:PORT".
+ parts := strings.Split(mock.URL, ":")
+ port, _ := strconv.Atoi(parts[len(parts)-1])
+ return &Server{
+ profile: &config.Profile{Port: port},
+ }
+}
+
+func TestApiRequest_AuthForwarding(t *testing.T) {
+ var capturedAuth string
+ s := newTestServerWithMock(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ capturedAuth = r.Header.Get("Authorization")
+ w.WriteHeader(http.StatusOK)
+ fmt.Fprint(w, `{}`)
+ }))
+
+ ctx := withAccessToken(context.Background(), "test-token-123")
+ resp, err := s.apiRequest(ctx, "/api/test", nil)
+ require.NoError(t, err)
+ require.Equal(t, http.StatusOK, resp.Status)
+ require.Equal(t, "Bearer test-token-123", capturedAuth)
+}
+
+func TestApiRequest_ErrorParsing(t *testing.T) {
+ s := newTestServerWithMock(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusForbidden)
+ fmt.Fprint(w, `{"message": "permission denied", "code": "PERMISSION_DENIED"}`)
+ }))
+
+ ctx := context.Background()
+ resp, err := s.apiRequest(ctx, "/api/test", nil)
+ require.NoError(t, err)
+ require.Equal(t, http.StatusForbidden, resp.Status)
+
+ errMsg := parseError(resp.Body)
+ require.Equal(t, "permission denied", errMsg)
+}
+
+func TestApiRequest_RawMessage(t *testing.T) {
+ const payload = `{"id":12345,"count":9999999999}`
+ s := newTestServerWithMock(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ fmt.Fprint(w, payload)
+ }))
+
+ ctx := context.Background()
+ resp, err := s.apiRequest(ctx, "/api/test", nil)
+ require.NoError(t, err)
+ require.Equal(t, http.StatusOK, resp.Status)
+
+ // Verify raw JSON is preserved.
+ require.JSONEq(t, payload, string(resp.Body))
+
+ // Decode into typed struct with int64 fields to verify integers are preserved.
+ type result struct {
+ ID int64 `json:"id"`
+ Count int64 `json:"count"`
+ }
+ var r result
+ err = json.Unmarshal(resp.Body, &r)
+ require.NoError(t, err)
+ require.Equal(t, int64(12345), r.ID)
+ require.Equal(t, int64(9999999999), r.Count)
+}