tools

package
v1.0.16 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 22, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package tools provides shared utilities and types for MCP tool implementations.

Package tools provides shared utilities and types for MCP tool implementations.

Package tools provides shared utilities and types for MCP tool implementations.

Package tools provides shared utilities for MCP tool handlers.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddClusterContextParams added in v0.0.61

func AddClusterContextParams(sc *server.ServerContext) []mcp.ToolOption

AddClusterContextParams returns tool options for cluster and kubeContext parameters based on the server's operating mode. This ensures backwards compatibility:

  • cluster parameter is only added when federation is enabled
  • kubeContext parameter is only added when NOT in in-cluster mode

Usage in tool registration:

opts := []mcp.ToolOption{
    mcp.WithDescription("..."),
}
opts = append(opts, tools.AddClusterContextParams(sc)...)
opts = append(opts, /* tool-specific params */...)
tool := mcp.NewTool("tool_name", opts...)

func CheckMutatingOperation added in v0.0.77

func CheckMutatingOperation(sc *server.ServerContext, operation string) *mcp.CallToolResult

CheckMutatingOperation verifies if a mutating operation is allowed given the current server configuration. Returns an error result if blocked, nil if allowed.

This centralizes the non-destructive mode check to avoid code duplication across all tool handlers that perform mutating operations.

Operations are allowed if:

  • NonDestructiveMode is disabled, OR
  • DryRun mode is enabled (operations will be validated but not applied), OR
  • The operation is explicitly listed in AllowedOperations

Protected operations include: create, apply, delete, patch, scale, exec, port-forward

func ExtractClusterParam added in v0.0.61

func ExtractClusterParam(args map[string]interface{}) string

ExtractClusterParam extracts the cluster parameter from request arguments. Returns an empty string if not provided.

func FormatAuthenticationError added in v0.0.73

func FormatAuthenticationError(err error) string

FormatAuthenticationError returns a user-friendly error message for authentication errors. If the error is not an authentication error, returns a generic message.

func FormatClusterError added in v0.0.61

func FormatClusterError(err error, clusterName string) string

FormatClusterError formats a federation error into a user-friendly message. This function handles the various error types from the federation package and returns appropriate messages for MCP tool responses.

Security

This function uses UserFacingError() methods from federation error types to ensure no internal details (cluster names, network topology) are leaked.

func FormatK8sError added in v0.0.167

func FormatK8sError(prefix string, err error, user *federation.UserInfo) string

FormatK8sError formats a Kubernetes operation error with optional impersonation context. When user info is available (federation mode), the impersonated user and groups are appended to help diagnose RBAC permission issues.

Example output without impersonation:

"Failed to list resources: pods is forbidden: ..."

Example output with impersonation:

"Failed to list resources: pods is forbidden: ... (impersonating user=fernando@example.com, groups=[giantswarm-connector:giantswarm, customer-connector:group-customer])"

func GetK8sClient added in v0.0.43

func GetK8sClient(ctx context.Context, sc *server.ServerContext) (k8s.Client, error)

GetK8sClient returns the appropriate Kubernetes client for the given context. If downstream OAuth is enabled and an access token is present in the context, it returns a per-user client. Otherwise, it returns the shared service account client.

When downstream OAuth strict mode is enabled and authentication fails, returns (nil, error) with an authentication error.

Tool handlers should use this function instead of directly calling sc.K8sClient() to ensure proper OAuth passthrough when enabled.

Error Handling

Returns (nil, error) when downstream OAuth strict mode is enabled and:

  • No OAuth token is present in the context (server.ErrOAuthTokenMissing)
  • The OAuth token cannot be used to create a client (server.ErrOAuthClientFailed)

Returns (client, nil) on success.

func HideDeprecatedAliasesFilter added in v0.1.95

func HideDeprecatedAliasesFilter(_ context.Context, tools []mcp.Tool) []mcp.Tool

HideDeprecatedAliasesFilter is a mcpserver.ToolFilterFunc that strips deprecated aliases out of the tools/list response. The aliases remain fully invokable via tools/call (the mcp-go filter chain only runs on list), so existing clients calling kubernetes_<name> keep working, but new clients can't discover the deprecated names. Pair this with MaybeAddDeprecatedAlias on the registration side.

func IsAuthenticationError added in v0.0.73

func IsAuthenticationError(err error) bool

IsAuthenticationError returns true if the error is an OAuth authentication error. This can be used to distinguish between authentication failures and other errors.

func IsDeprecatedAlias added in v0.1.95

func IsDeprecatedAlias(name string) bool

IsDeprecatedAlias reports whether name is a deprecated backward-compat alias registered by MaybeAddDeprecatedAlias.

func IsMutatingOperationAllowed added in v0.1.75

func IsMutatingOperationAllowed(sc *server.ServerContext, operation string) bool

IsMutatingOperationAllowed reports whether the given operation verb would be permitted under the current server configuration. The rules are:

  • NonDestructiveMode is disabled, OR
  • DryRun mode is enabled, OR
  • The operation is listed in AllowedOperations.

In particular, AllowedOperations is honored even when NonDestructiveMode=true and DryRun=false: the whitelist is the explicit escape hatch for selectively enabling specific verbs without flipping the global mode.

This predicate is used at two sites and a change to either rule affects both:

  • At tool-registration time, to skip exposing destructive tools that cannot be invoked under the current configuration.
  • At handler invocation time, via CheckMutatingOperation, to enforce the same rule at the call site as a defence-in-depth check.

func MaybeAddDeprecatedAlias added in v0.1.95

func MaybeAddDeprecatedAlias(
	s *mcpserver.MCPServer,
	sc *server.ServerContext,
	primaryName string,
	handler ToolHandler,
	opts ...mcp.ToolOption,
)

MaybeAddDeprecatedAlias registers a deprecated alias for primaryName if one is mapped in deprecatedAliasFor. The alias shares the same input schema and handler; only the name and description differ. Its description is replaced with a [DEPRECATED] banner pointing to primaryName. Audit logs record the alias name actually invoked, so operators can track residual usage.

func ValidateClusterParam added in v0.0.61

func ValidateClusterParam(sc *server.ServerContext, clusterName string) string

ValidateClusterParam validates that the cluster parameter can be used. Returns an error message if the cluster parameter is specified but federation is not enabled.

This is a convenience function for handlers that don't yet support multi-cluster operations but want to provide clear error messages.

func WrapWithAuditLogging added in v0.0.166

func WrapWithAuditLogging(
	toolName string,
	handler ToolHandler,
	sc *server.ServerContext,
) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

WrapWithAuditLogging wraps a tool handler with audit logging. This function creates a wrapper that automatically captures:

  • Tool invocation timing
  • User identity from OAuth context (if available)
  • Cluster and resource information from request arguments
  • Success/error status from the handler result
  • OpenTelemetry trace context for correlation

The wrapper logs tool invocations using the AuditLogger from the instrumentation provider. If no instrumentation provider is available, the handler is called without audit logging.

Types

type ClusterClient added in v0.0.61

type ClusterClient struct {
	// contains filtered or unexported fields
}

ClusterClient provides access to Kubernetes operations with multi-cluster support. It wraps either the local k8s.Client or federation-based clients.

Usage Pattern

Tool handlers should use GetClusterClient to get the appropriate client:

client, errMsg := tools.GetClusterClient(ctx, sc, clusterName)
if errMsg != "" {
    return mcp.NewToolResultError(errMsg), nil
}
// Use client.K8s() for standard operations, or client.User() for user info

func GetClusterClient added in v0.0.61

func GetClusterClient(ctx context.Context, sc *server.ServerContext, clusterName string) (*ClusterClient, string)

GetClusterClient returns a ClusterClient for the specified cluster. If clusterName is empty, returns a client for the local cluster.

Federation Behavior

When federation is enabled AND a cluster name is specified:

  • Creates a FederatedClient using the federation manager
  • The client is configured with user impersonation for security
  • All operations are performed under the authenticated user's identity

When federation is NOT enabled or cluster is empty:

  • Returns the standard k8s client from ServerContext
  • Does not require OAuth authentication

Return Values

Returns (ClusterClient, "") on success or (nil, errorMessage) on failure. The error message is suitable for direct use in MCP tool responses.

func (*ClusterClient) ClusterName added in v0.0.61

func (cc *ClusterClient) ClusterName() string

ClusterName returns the target cluster name (empty for local cluster).

func (*ClusterClient) IsFederated added in v0.0.61

func (cc *ClusterClient) IsFederated() bool

IsFederated returns true if this client uses federation.

func (*ClusterClient) K8s added in v0.0.61

func (cc *ClusterClient) K8s() k8s.Client

K8s returns the underlying Kubernetes client. This client is configured for the target cluster.

func (*ClusterClient) User added in v0.0.61

func (cc *ClusterClient) User() *federation.UserInfo

User returns the authenticated user info. Returns nil if federation is not enabled or if using local fallback.

type ToolHandler added in v0.0.166

type ToolHandler func(ctx context.Context, request mcp.CallToolRequest, sc *server.ServerContext) (*mcp.CallToolResult, error)

ToolHandler is the signature for MCP tool handler functions that take ServerContext.

Directories

Path Synopsis
Package access provides tools for checking user permissions on Kubernetes clusters.
Package access provides tools for checking user permissions on Kubernetes clusters.
Package capi provides MCP tools for CAPI (Cluster API) cluster discovery and navigation in multi-cluster environments.
Package capi provides MCP tools for CAPI (Cluster API) cluster discovery and navigation in multi-cluster environments.
Package mcptest provides shared helpers for tests that exercise MCP tool handlers via the in-process JSON-RPC entry point on github.com/mark3labs/mcp-go/server.MCPServer.
Package mcptest provides shared helpers for tests that exercise MCP tool handlers via the in-process JSON-RPC entry point on github.com/mark3labs/mcp-go/server.MCPServer.
Package output provides fleet-scale output filtering and truncation for MCP tool responses.
Package output provides fleet-scale output filtering and truncation for MCP tool responses.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL