-
Notifications
You must be signed in to change notification settings - Fork 117
Add secrets management support to ToolHive MCP server #2006
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
JAORMX
wants to merge
2
commits into
main
Choose a base branch
from
feat/mcp-server-secrets-management
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
package server | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
|
||
"github.com/mark3labs/mcp-go/mcp" | ||
|
||
"github.com/stacklok/toolhive/pkg/secrets" | ||
) | ||
|
||
// SecretInfo represents secret information returned by list | ||
type SecretInfo struct { | ||
Key string `json:"key"` | ||
Description string `json:"description,omitempty"` | ||
} | ||
|
||
// ListSecretsResponse represents the response from listing secrets | ||
type ListSecretsResponse struct { | ||
Secrets []SecretInfo `json:"secrets"` | ||
} | ||
|
||
// ListSecrets lists all available secrets | ||
func (h *Handler) ListSecrets(ctx context.Context, _ mcp.CallToolRequest) (*mcp.CallToolResult, error) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why you pass mcp.CallToolRequest if that's not used anywhere? |
||
// Get the configuration to determine the secrets provider | ||
cfg := h.configProvider.GetConfig() | ||
|
||
// Check if secrets setup has been completed | ||
if !cfg.Secrets.SetupCompleted { | ||
return mcp.NewToolResultError( | ||
"Secrets provider not configured. Please run 'thv secret setup' to configure a secrets provider first"), nil | ||
} | ||
|
||
// Get the provider type | ||
providerType, err := cfg.Secrets.GetProviderType() | ||
if err != nil { | ||
return mcp.NewToolResultError(fmt.Sprintf("Failed to get secrets provider type: %v", err)), nil | ||
} | ||
|
||
// Create the secrets provider | ||
secretsProvider, err := secrets.CreateSecretProvider(providerType) | ||
if err != nil { | ||
return mcp.NewToolResultError(fmt.Sprintf("Failed to create secrets provider: %v", err)), nil | ||
} | ||
|
||
// List all secrets | ||
secretDescriptions, err := secretsProvider.ListSecrets(ctx) | ||
if err != nil { | ||
return mcp.NewToolResultError(fmt.Sprintf("Failed to list secrets: %v", err)), nil | ||
} | ||
|
||
// Format results with structured data | ||
var results []SecretInfo | ||
for _, desc := range secretDescriptions { | ||
info := SecretInfo{ | ||
Key: desc.Key, | ||
Description: desc.Description, | ||
} | ||
results = append(results, info) | ||
} | ||
|
||
// Create structured response | ||
response := ListSecretsResponse{ | ||
Secrets: results, | ||
} | ||
|
||
return mcp.NewToolResultStructuredOnly(response), nil | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
package server | ||
|
||
import ( | ||
"context" | ||
"testing" | ||
|
||
"github.com/mark3labs/mcp-go/mcp" | ||
"github.com/stretchr/testify/assert" | ||
"go.uber.org/mock/gomock" | ||
|
||
"github.com/stacklok/toolhive/pkg/config" | ||
configmocks "github.com/stacklok/toolhive/pkg/config/mocks" | ||
registrymocks "github.com/stacklok/toolhive/pkg/registry/mocks" | ||
workloadsmocks "github.com/stacklok/toolhive/pkg/workloads/mocks" | ||
) | ||
|
||
func TestHandler_ListSecrets(t *testing.T) { | ||
t.Parallel() | ||
ctrl := gomock.NewController(t) | ||
t.Cleanup(func() { ctrl.Finish() }) | ||
|
||
tests := []struct { | ||
name string | ||
setupMocks func(*configmocks.MockProvider) | ||
wantErr bool | ||
checkResult func(*testing.T, *mcp.CallToolResult) | ||
}{ | ||
{ | ||
name: "secrets not setup", | ||
setupMocks: func(configProvider *configmocks.MockProvider) { | ||
// Mock config setup - not completed | ||
cfg := &config.Config{ | ||
Secrets: config.Secrets{ | ||
SetupCompleted: false, | ||
}, | ||
} | ||
configProvider.EXPECT().GetConfig().Return(cfg).AnyTimes() | ||
}, | ||
wantErr: false, | ||
checkResult: func(t *testing.T, result *mcp.CallToolResult) { | ||
t.Helper() | ||
assert.NotNil(t, result) | ||
assert.True(t, result.IsError) | ||
}, | ||
}, | ||
} | ||
|
||
for _, tt := range tests { | ||
t.Run(tt.name, func(t *testing.T) { | ||
t.Parallel() | ||
|
||
// Create mocks | ||
mockRegistry := registrymocks.NewMockProvider(ctrl) | ||
mockWorkloadManager := workloadsmocks.NewMockManager(ctrl) | ||
mockConfigProvider := configmocks.NewMockProvider(ctrl) | ||
|
||
// Setup mocks | ||
if tt.setupMocks != nil { | ||
tt.setupMocks(mockConfigProvider) | ||
} | ||
|
||
handler := &Handler{ | ||
ctx: context.Background(), | ||
workloadManager: mockWorkloadManager, | ||
registryProvider: mockRegistry, | ||
configProvider: mockConfigProvider, | ||
} | ||
|
||
request := mcp.CallToolRequest{ | ||
Params: mcp.CallToolParams{ | ||
Name: "list_secrets", | ||
Arguments: map[string]interface{}{}, | ||
}, | ||
} | ||
|
||
result, err := handler.ListSecrets(context.Background(), request) | ||
|
||
if tt.wantErr { | ||
assert.Error(t, err) | ||
} else { | ||
assert.NoError(t, err) | ||
if tt.checkResult != nil { | ||
tt.checkResult(t, result) | ||
} | ||
} | ||
}) | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -14,12 +14,19 @@ import ( | |
transporttypes "github.com/stacklok/toolhive/pkg/transport/types" | ||
) | ||
|
||
// SecretMapping represents a secret name and its target environment variable | ||
type SecretMapping struct { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we do not accept a description here? |
||
Name string `json:"name"` | ||
Target string `json:"target"` | ||
} | ||
|
||
// runServerArgs holds the arguments for running a server | ||
type runServerArgs struct { | ||
Server string `json:"server"` | ||
Name string `json:"name,omitempty"` | ||
Host string `json:"host,omitempty"` | ||
Env map[string]string `json:"env,omitempty"` | ||
Server string `json:"server"` | ||
Name string `json:"name,omitempty"` | ||
Host string `json:"host,omitempty"` | ||
Env map[string]string `json:"env,omitempty"` | ||
Secrets []SecretMapping `json:"secrets,omitempty"` | ||
} | ||
|
||
// RunServer runs an MCP server | ||
|
@@ -119,6 +126,12 @@ func buildServerConfig( | |
// Prepare environment variables | ||
envVars := prepareEnvironmentVariables(imageMetadata, args.Env) | ||
|
||
// Prepare secrets | ||
secrets := prepareSecrets(args.Secrets) | ||
if len(secrets) > 0 { | ||
opts = append(opts, runner.WithSecrets(secrets)) | ||
} | ||
|
||
// Build the configuration | ||
envVarValidator := &runner.DetachedEnvVarValidator{} | ||
return runner.NewRunConfigBuilder(ctx, imageMetadata, envVars, envVarValidator, opts...) | ||
|
@@ -159,6 +172,21 @@ func prepareEnvironmentVariables(imageMetadata *registry.ImageMetadata, userEnv | |
return envVarsMap | ||
} | ||
|
||
// prepareSecrets converts SecretMapping array to the string format expected by the runner | ||
func prepareSecrets(secretMappings []SecretMapping) []string { | ||
if len(secretMappings) == 0 { | ||
return nil | ||
} | ||
|
||
secrets := make([]string, len(secretMappings)) | ||
for i, mapping := range secretMappings { | ||
// Convert to the format expected by runner: "secret_name,target=ENV_VAR_NAME" | ||
secrets[i] = fmt.Sprintf("%s,target=%s", mapping.Name, mapping.Target) | ||
} | ||
|
||
return secrets | ||
} | ||
|
||
// saveAndRunServer saves the configuration and runs the server | ||
func (h *Handler) saveAndRunServer(ctx context.Context, runConfig *runner.RunConfig, name string) error { | ||
// Save the run configuration state before starting | ||
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
how is description passed to the secret? i do not see any example of setting up that description