Files
Enterprise-Knowledge-Base/client/mcp_service.go
T
wizardchen 7643dd457e refactor(credentials): introduce /credentials subresource pattern
Replace the legacy "redacted placeholder + Clear* boolean" pattern with
dedicated per-resource credential subresources across MCP services,
Models, Web search providers, and Data sources.

Why
---
The previous design had three problems:

1. Main PUT body carried secret fields. The frontend echoed back a
   redacted "***" placeholder, and a fragile MergeUpdate / IsRedactedOrEmpty
   defense in the service layer tried to detect "user did not change this"
   vs "user wants to clear this". A regression in that defense (or a new
   frontend forgetting it) silently overwrites the stored secret with the
   placeholder.

2. The "remove this credential" UX was a red checkbox under a pre-filled
   password input. Three intents (preserve / replace / clear) collapsed
   onto one field, and credential changes were bundled with unrelated
   config edits in the same submit. Users wiped working keys by mistake.

3. Secret presence was inferred from "did the response come back with a
   '***' placeholder", which couples the contract to a magic string.

Design
------
Each of the four resources now exposes:

  PUT    /{resource}/{id}/credentials          # write one or more fields
  DELETE /{resource}/{id}/credentials/{field}  # clear a single field

"Is this configured?" metadata travels on the main resource response as
a typed map (dto.MCPServiceResponse.Credentials etc.) — no separate GET
endpoint. The frontend reads the configured boolean from the main GET
and never sees secret values at all.

Main PUT endpoints now ignore any secret fields in the request body and
log a deprecation warning if they appear, so legacy clients fail loudly
rather than overwriting silently.

Frontend
--------
- New reusable <CredentialResource> component renders a three-state card
  (unconfigured / configured / editing) and drives the dedicated
  endpoints. Used by MCP, Model, Web search; DataSource has a bespoke
  card with the same behaviour because its credentials are a single
  atomic per-connector map.
- Cancel from edit mode now restores state synchronously from the meta
  prop. The previous async refresh() was a no-op while state was still
  'editing', leaving the input frozen open.
- Remove is single-click + toast. The danger-themed button is the
  deterrent; a modal confirm adds friction without adding safety (the
  plaintext is irrecoverable client-side either way — recovery means
  re-typing).

DTOs (internal/handler/dto/) are deliberately separate from the GORM
models so "no secret in response" is a compile-time invariant: a future
contributor cannot leak a secret without explicitly adding the field to
the DTO, which is review-able in a single diff.

Storage is unchanged — credentials still live in the existing jsonb /
parameters columns. No schema migration.

Cleanup
-------
- types.MCPService / types.Model / types.WebSearchProviderEntity /
  types.DataSourceConfig: drop ClearAPIKey / ClearToken / ClearAppSecret
  / ClearCredentials boolean fields, MergeUpdate(), RedactSensitiveData().
- utils/types/secret.go: drop PreserveIfRedacted / IsRedactedOrEmpty.
  RedactedSecretPlaceholder constant is retained because VectorStore
  still uses the old pattern and is out of scope here.
- Frontend hasExistingApiKey / clearApiKey / convertToLegacyFormat
  redaction handling removed; i18n keys renamed secret -> credential.
2026-05-17 15:27:52 +08:00

214 lines
6.7 KiB
Go

package client
import (
"context"
"encoding/json"
"fmt"
"net/http"
)
// MCPTransportType represents the transport type for MCP service
type MCPTransportType string
const (
MCPTransportSSE MCPTransportType = "sse"
MCPTransportHTTPStreamable MCPTransportType = "http-streamable"
MCPTransportStdio MCPTransportType = "stdio"
)
// MCPService represents an MCP service configuration
type MCPService struct {
ID string `json:"id"`
TenantID uint64 `json:"tenant_id"`
Name string `json:"name"`
Description string `json:"description"`
Enabled bool `json:"enabled"`
TransportType MCPTransportType `json:"transport_type"`
URL *string `json:"url,omitempty"`
Headers map[string]string `json:"headers"`
AuthConfig *MCPAuthConfig `json:"auth_config"`
AdvancedConfig *MCPAdvancedConfig `json:"advanced_config"`
StdioConfig *MCPStdioConfig `json:"stdio_config,omitempty"`
EnvVars map[string]string `json:"env_vars,omitempty"`
IsBuiltin bool `json:"is_builtin"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
// MCPAuthConfig represents authentication configuration for MCP service.
//
// Secret fields (APIKey, Token) are accepted on create but are never returned
// by the server. To mutate credentials on an existing service, use the
// dedicated /credentials subresource — see the MCP credentials API for the
// PUT / DELETE shape. Sending secret fields in a main PUT body is silently
// ignored server-side.
type MCPAuthConfig struct {
APIKey string `json:"api_key,omitempty"`
Token string `json:"token,omitempty"`
CustomHeaders map[string]string `json:"custom_headers,omitempty"`
}
// MCPAdvancedConfig represents advanced configuration for MCP service
type MCPAdvancedConfig struct {
Timeout int `json:"timeout"`
RetryCount int `json:"retry_count"`
RetryDelay int `json:"retry_delay"`
}
// MCPStdioConfig represents stdio transport configuration
type MCPStdioConfig struct {
Command string `json:"command"`
Args []string `json:"args"`
}
// MCPTool represents a tool exposed by an MCP service
type MCPTool struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema json.RawMessage `json:"inputSchema"`
}
// MCPResource represents a resource exposed by an MCP service
type MCPResource struct {
URI string `json:"uri"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
MimeType string `json:"mimeType,omitempty"`
}
// MCPTestResult represents the result of testing an MCP service connection
type MCPTestResult struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
Tools []*MCPTool `json:"tools,omitempty"`
Resources []*MCPResource `json:"resources,omitempty"`
}
// CreateMCPService creates a new MCP service
func (c *Client) CreateMCPService(ctx context.Context, service *MCPService) (*MCPService, error) {
resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/mcp-services", service, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *MCPService `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// ListMCPServices lists all MCP services for the current tenant
func (c *Client) ListMCPServices(ctx context.Context) ([]*MCPService, error) {
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/mcp-services", nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data []*MCPService `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// GetMCPService gets an MCP service by ID
func (c *Client) GetMCPService(ctx context.Context, serviceID string) (*MCPService, error) {
resp, err := c.doRequest(ctx, http.MethodGet, fmt.Sprintf("/api/v1/mcp-services/%s", serviceID), nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *MCPService `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// UpdateMCPService updates an MCP service
func (c *Client) UpdateMCPService(ctx context.Context, serviceID string, updates map[string]interface{}) (*MCPService, error) {
resp, err := c.doRequest(ctx, http.MethodPut, fmt.Sprintf("/api/v1/mcp-services/%s", serviceID), updates, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *MCPService `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// DeleteMCPService deletes an MCP service
func (c *Client) DeleteMCPService(ctx context.Context, serviceID string) error {
resp, err := c.doRequest(ctx, http.MethodDelete, fmt.Sprintf("/api/v1/mcp-services/%s", serviceID), nil, nil)
if err != nil {
return err
}
return parseResponse(resp, nil)
}
// TestMCPService tests an MCP service connection
func (c *Client) TestMCPService(ctx context.Context, serviceID string) (*MCPTestResult, error) {
resp, err := c.doRequest(ctx, http.MethodPost, fmt.Sprintf("/api/v1/mcp-services/%s/test", serviceID), nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *MCPTestResult `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// GetMCPServiceTools gets the tools provided by an MCP service
func (c *Client) GetMCPServiceTools(ctx context.Context, serviceID string) ([]*MCPTool, error) {
resp, err := c.doRequest(ctx, http.MethodGet, fmt.Sprintf("/api/v1/mcp-services/%s/tools", serviceID), nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data []*MCPTool `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// GetMCPServiceResources gets the resources provided by an MCP service
func (c *Client) GetMCPServiceResources(ctx context.Context, serviceID string) ([]*MCPResource, error) {
resp, err := c.doRequest(ctx, http.MethodGet, fmt.Sprintf("/api/v1/mcp-services/%s/resources", serviceID), nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data []*MCPResource `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}