azdext

package
v1.34.1 Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2026 License: MIT Imports: 62 Imported by: 8

Documentation

Index

Constants

View Source
const (
	AiErrorReasonMissingSubscription  = "AI_MISSING_SUBSCRIPTION"
	AiErrorReasonLocationRequired     = "AI_LOCATION_REQUIRED"
	AiErrorReasonQuotaLocation        = "AI_QUOTA_LOCATION_REQUIRED"
	AiErrorReasonModelNotFound        = "AI_MODEL_NOT_FOUND"
	AiErrorReasonNoModelsMatch        = "AI_NO_MODELS_MATCH"
	AiErrorReasonNoDeploymentMatch    = "AI_NO_DEPLOYMENT_MATCH"
	AiErrorReasonNoValidSkus          = "AI_NO_VALID_SKUS"
	AiErrorReasonNoLocationsWithQuota = "AI_NO_LOCATIONS_WITH_QUOTA"
	AiErrorReasonInvalidCapacity      = "AI_INVALID_CAPACITY"
	AiErrorReasonInteractiveRequired  = "AI_INTERACTIVE_REQUIRED"
)

AI error reason codes used in gRPC ErrorInfo.Reason.

View Source
const (
	AuthErrorReasonNotLoggedIn   = "AUTH_NOT_LOGGED_IN"
	AuthErrorReasonLoginRequired = "AUTH_LOGIN_REQUIRED"
)

Auth error reason codes used in gRPC ErrorInfo.Reason.

For AAD-originated failures, the Reason is the originating Entra error code formatted as "AADSTS<code>" (e.g. "AADSTS530084") so extensions can match on the AAD code directly without azd having to define a synthetic taxonomy. The constants below cover azd-local conditions that have no corresponding Entra code.

View Source
const (
	TraceparentKey = "traceparent"
	TracestateKey  = "tracestate"

	TraceparentEnv = "TRACEPARENT"
	TracestateEnv  = "TRACESTATE"
)
View Source
const (
	AccountService_ListSubscriptions_FullMethodName                        = v1.AccountService_ListSubscriptions_FullMethodName
	AccountService_LookupTenant_FullMethodName                             = v1.AccountService_LookupTenant_FullMethodName
	AiModelService_ListLocationsWithQuota_FullMethodName                   = v1.AiModelService_ListLocationsWithQuota_FullMethodName
	AiModelService_ListModelLocationsWithQuota_FullMethodName              = v1.AiModelService_ListModelLocationsWithQuota_FullMethodName
	AiModelService_ListModels_FullMethodName                               = v1.AiModelService_ListModels_FullMethodName
	AiModelService_ListUsages_FullMethodName                               = v1.AiModelService_ListUsages_FullMethodName
	AiModelService_ResolveModelDeployments_FullMethodName                  = v1.AiModelService_ResolveModelDeployments_FullMethodName
	ArtifactKind_ARTIFACT_KIND_ARCHIVE                                     = v1.ArtifactKind_ARTIFACT_KIND_ARCHIVE
	ArtifactKind_ARTIFACT_KIND_CONFIG                                      = v1.ArtifactKind_ARTIFACT_KIND_CONFIG
	ArtifactKind_ARTIFACT_KIND_CONTAINER                                   = v1.ArtifactKind_ARTIFACT_KIND_CONTAINER
	ArtifactKind_ARTIFACT_KIND_DEPLOYMENT                                  = v1.ArtifactKind_ARTIFACT_KIND_DEPLOYMENT
	ArtifactKind_ARTIFACT_KIND_DIRECTORY                                   = v1.ArtifactKind_ARTIFACT_KIND_DIRECTORY
	ArtifactKind_ARTIFACT_KIND_ENDPOINT                                    = v1.ArtifactKind_ARTIFACT_KIND_ENDPOINT
	ArtifactKind_ARTIFACT_KIND_RESOURCE                                    = v1.ArtifactKind_ARTIFACT_KIND_RESOURCE
	ArtifactKind_ARTIFACT_KIND_UNSPECIFIED                                 = v1.ArtifactKind_ARTIFACT_KIND_UNSPECIFIED
	ContainerService_Build_FullMethodName                                  = v1.ContainerService_Build_FullMethodName
	ContainerService_Package_FullMethodName                                = v1.ContainerService_Package_FullMethodName
	ContainerService_Publish_FullMethodName                                = v1.ContainerService_Publish_FullMethodName
	DeploymentService_GetDeploymentContext_FullMethodName                  = v1.DeploymentService_GetDeploymentContext_FullMethodName
	DeploymentService_GetDeployment_FullMethodName                         = v1.DeploymentService_GetDeployment_FullMethodName
	EnvironmentService_GetConfigSection_FullMethodName                     = v1.EnvironmentService_GetConfigSection_FullMethodName
	EnvironmentService_GetConfigString_FullMethodName                      = v1.EnvironmentService_GetConfigString_FullMethodName
	EnvironmentService_GetConfig_FullMethodName                            = v1.EnvironmentService_GetConfig_FullMethodName
	EnvironmentService_GetCurrent_FullMethodName                           = v1.EnvironmentService_GetCurrent_FullMethodName
	EnvironmentService_GetValue_FullMethodName                             = v1.EnvironmentService_GetValue_FullMethodName
	EnvironmentService_GetValues_FullMethodName                            = v1.EnvironmentService_GetValues_FullMethodName
	EnvironmentService_Get_FullMethodName                                  = v1.EnvironmentService_Get_FullMethodName
	EnvironmentService_List_FullMethodName                                 = v1.EnvironmentService_List_FullMethodName
	EnvironmentService_Select_FullMethodName                               = v1.EnvironmentService_Select_FullMethodName
	EnvironmentService_SetConfig_FullMethodName                            = v1.EnvironmentService_SetConfig_FullMethodName
	EnvironmentService_SetValue_FullMethodName                             = v1.EnvironmentService_SetValue_FullMethodName
	EnvironmentService_UnsetConfig_FullMethodName                          = v1.EnvironmentService_UnsetConfig_FullMethodName
	ErrorOrigin_ERROR_ORIGIN_LOCAL                                         = v1.ErrorOrigin_ERROR_ORIGIN_LOCAL
	ErrorOrigin_ERROR_ORIGIN_SERVICE                                       = v1.ErrorOrigin_ERROR_ORIGIN_SERVICE
	ErrorOrigin_ERROR_ORIGIN_TOOL                                          = v1.ErrorOrigin_ERROR_ORIGIN_TOOL
	ErrorOrigin_ERROR_ORIGIN_UNSPECIFIED                                   = v1.ErrorOrigin_ERROR_ORIGIN_UNSPECIFIED
	EventService_EventStream_FullMethodName                                = v1.EventService_EventStream_FullMethodName
	ExtensionService_Ready_FullMethodName                                  = v1.ExtensionService_Ready_FullMethodName
	ExtensionService_ReportError_FullMethodName                            = v1.ExtensionService_ReportError_FullMethodName
	FrameworkService_Stream_FullMethodName                                 = v1.FrameworkService_Stream_FullMethodName
	LocationKind_LOCATION_KIND_LOCAL                                       = v1.LocationKind_LOCATION_KIND_LOCAL
	LocationKind_LOCATION_KIND_REMOTE                                      = v1.LocationKind_LOCATION_KIND_REMOTE
	LocationKind_LOCATION_KIND_UNSPECIFIED                                 = v1.LocationKind_LOCATION_KIND_UNSPECIFIED
	ProjectService_AddService_FullMethodName                               = v1.ProjectService_AddService_FullMethodName
	ProjectService_GetConfigSection_FullMethodName                         = v1.ProjectService_GetConfigSection_FullMethodName
	ProjectService_GetConfigValue_FullMethodName                           = v1.ProjectService_GetConfigValue_FullMethodName
	ProjectService_GetResolvedServices_FullMethodName                      = v1.ProjectService_GetResolvedServices_FullMethodName
	ProjectService_GetServiceConfigSection_FullMethodName                  = v1.ProjectService_GetServiceConfigSection_FullMethodName
	ProjectService_GetServiceConfigValue_FullMethodName                    = v1.ProjectService_GetServiceConfigValue_FullMethodName
	ProjectService_GetServiceTargetResource_FullMethodName                 = v1.ProjectService_GetServiceTargetResource_FullMethodName
	ProjectService_Get_FullMethodName                                      = v1.ProjectService_Get_FullMethodName
	ProjectService_ParseGitHubUrl_FullMethodName                           = v1.ProjectService_ParseGitHubUrl_FullMethodName
	ProjectService_SetConfigSection_FullMethodName                         = v1.ProjectService_SetConfigSection_FullMethodName
	ProjectService_SetConfigValue_FullMethodName                           = v1.ProjectService_SetConfigValue_FullMethodName
	ProjectService_SetServiceConfigSection_FullMethodName                  = v1.ProjectService_SetServiceConfigSection_FullMethodName
	ProjectService_SetServiceConfigValue_FullMethodName                    = v1.ProjectService_SetServiceConfigValue_FullMethodName
	ProjectService_UnsetConfig_FullMethodName                              = v1.ProjectService_UnsetConfig_FullMethodName
	ProjectService_UnsetServiceConfig_FullMethodName                       = v1.ProjectService_UnsetServiceConfig_FullMethodName
	PromptService_Confirm_FullMethodName                                   = v1.PromptService_Confirm_FullMethodName
	PromptService_MultiSelect_FullMethodName                               = v1.PromptService_MultiSelect_FullMethodName
	PromptService_PromptAiDeployment_FullMethodName                        = v1.PromptService_PromptAiDeployment_FullMethodName
	PromptService_PromptAiLocationWithQuota_FullMethodName                 = v1.PromptService_PromptAiLocationWithQuota_FullMethodName
	PromptService_PromptAiModelLocationWithQuota_FullMethodName            = v1.PromptService_PromptAiModelLocationWithQuota_FullMethodName
	PromptService_PromptAiModel_FullMethodName                             = v1.PromptService_PromptAiModel_FullMethodName
	PromptService_PromptLocation_FullMethodName                            = v1.PromptService_PromptLocation_FullMethodName
	PromptService_PromptResourceGroupResource_FullMethodName               = v1.PromptService_PromptResourceGroupResource_FullMethodName
	PromptService_PromptResourceGroup_FullMethodName                       = v1.PromptService_PromptResourceGroup_FullMethodName
	PromptService_PromptSubscriptionResource_FullMethodName                = v1.PromptService_PromptSubscriptionResource_FullMethodName
	PromptService_PromptSubscription_FullMethodName                        = v1.PromptService_PromptSubscription_FullMethodName
	PromptService_Prompt_FullMethodName                                    = v1.PromptService_Prompt_FullMethodName
	PromptService_Select_FullMethodName                                    = v1.PromptService_Select_FullMethodName
	ProvisioningService_Stream_FullMethodName                              = v1.ProvisioningService_Stream_FullMethodName
	ProvisioningSkippedReason_PROVISIONING_SKIPPED_REASON_DEPLOYMENT_STATE = v1.ProvisioningSkippedReason_PROVISIONING_SKIPPED_REASON_DEPLOYMENT_STATE
	ProvisioningSkippedReason_PROVISIONING_SKIPPED_REASON_UNSPECIFIED      = v1.ProvisioningSkippedReason_PROVISIONING_SKIPPED_REASON_UNSPECIFIED
	ServiceTargetService_Stream_FullMethodName                             = v1.ServiceTargetService_Stream_FullMethodName
	UserConfigService_GetSection_FullMethodName                            = v1.UserConfigService_GetSection_FullMethodName
	UserConfigService_GetString_FullMethodName                             = v1.UserConfigService_GetString_FullMethodName
	UserConfigService_Get_FullMethodName                                   = v1.UserConfigService_Get_FullMethodName
	UserConfigService_Set_FullMethodName                                   = v1.UserConfigService_Set_FullMethodName
	UserConfigService_Unset_FullMethodName                                 = v1.UserConfigService_Unset_FullMethodName
	ValidationCheckSeverity_VALIDATION_CHECK_SEVERITY_ERROR                = v1.ValidationCheckSeverity_VALIDATION_CHECK_SEVERITY_ERROR
	ValidationCheckSeverity_VALIDATION_CHECK_SEVERITY_WARNING              = v1.ValidationCheckSeverity_VALIDATION_CHECK_SEVERITY_WARNING
	ValidationService_Stream_FullMethodName                                = v1.ValidationService_Stream_FullMethodName
	WorkflowService_Run_FullMethodName                                     = v1.WorkflowService_Run_FullMethodName
)
View Source
const (
	// ValidationCheckTypeArmProvision is the check type dispatched by the
	// Bicep provider during ARM-template provision validation. Its context
	// carries ARM-specific data (template, parameters, resource snapshot) and
	// therefore only runs for Bicep-provisioned deployments.
	ValidationCheckTypeArmProvision = "arm-provision"

	// ValidationCheckTypeProvision is the provider-agnostic check type
	// dispatched immediately before provisioning runs, regardless of the
	// provisioning provider (Bicep, Terraform, or extension-provided providers
	// such as microsoft.foundry and demo). Its context is "lean" because it
	// deliberately omits all of the ARM-derived data that "arm-provision"
	// carries — there is no ARM template, no resolved parameters, no resources
	// snapshot, and no predicted resources — since non-ARM providers do not
	// produce them. It carries only ambient environment values: the
	// environment name, subscription, location, resource group, and target
	// scope.
	//
	// These values are best-effort ambient values read from the azd
	// environment at dispatch time. The dispatch happens before the provider
	// resolves and prompts for subscription/location/resource group, so on a
	// cold first-time run (no flags, no persisted env values) subscription_id,
	// env_location, and resource_group may be empty, and target_scope is
	// inferred only from the presence of AZURE_RESOURCE_GROUP. Checks that
	// depend on these values must treat them as best-effort and tolerate empty
	// or not-yet-authoritative values (e.g. skip rather than fail when unset).
	ValidationCheckTypeProvision = "provision"
)
View Source
const (
	// ValidationContextResourcesSnapshot is the key for the raw Bicep
	// snapshot JSON in an "arm-provision" check context.
	ValidationContextResourcesSnapshot = "resources_snapshot"
	// ValidationContextPredictedResources is the key for the JSON array of
	// predicted resources extracted from the Bicep snapshot. Each element is
	// a resource object with type, name, location, properties, etc.
	ValidationContextPredictedResources = "predicted_resources"
	// ValidationContextARMTemplate is the key for the compiled ARM
	// template JSON in an "arm-provision" check context.
	ValidationContextARMTemplate = "arm_template"
	// ValidationContextARMParameters is the key for the resolved ARM
	// parameters JSON in an "arm-provision" check context.
	ValidationContextARMParameters = "arm_parameters"
	// ValidationContextEnvLocation is the key for the Azure deployment
	// location string. It is present in both "arm-provision" and
	// "provision" check contexts.
	ValidationContextEnvLocation = "env_location"
)
View Source
const (
	// ValidationContextEnvName is the key for the azd environment name in a
	// "provision" check context.
	ValidationContextEnvName = "env_name"
	// ValidationContextSubscriptionID is the key for the Azure subscription id
	// in a "provision" check context.
	ValidationContextSubscriptionID = "subscription_id"
	// ValidationContextResourceGroup is the key for the target resource group
	// name in a "provision" check context. It is empty for subscription-scoped
	// deployments.
	ValidationContextResourceGroup = "resource_group"
	// ValidationContextTargetScope is the key for the deployment target scope
	// ("subscription" or "resourceGroup") in a "provision" check context.
	ValidationContextTargetScope = "target_scope"
)
View Source
const (
	AiErrorDomain = "azd.ai"
)

AI error metadata constants used in gRPC ErrorInfo for AI model/prompt APIs.

View Source
const (
	AuthErrorDomain = "azd.auth"
)

Auth error metadata constants used in gRPC ErrorInfo for auth-related host APIs.

View Source
const Version = "1.34.1"

Version is the semantic version of the azdext SDK package. This value mirrors the CLI version in cli/version.txt and is automatically updated by eng/scripts/Update-CliVersion.ps1.

Variables

View Source
var (
	AccountService_ServiceDesc       = v1.AccountService_ServiceDesc
	AiModelService_ServiceDesc       = v1.AiModelService_ServiceDesc
	ArtifactKind_name                = v1.ArtifactKind_name
	ArtifactKind_value               = v1.ArtifactKind_value
	ContainerService_ServiceDesc     = v1.ContainerService_ServiceDesc
	DeploymentService_ServiceDesc    = v1.DeploymentService_ServiceDesc
	EnvironmentService_ServiceDesc   = v1.EnvironmentService_ServiceDesc
	ErrorOrigin_name                 = v1.ErrorOrigin_name
	ErrorOrigin_value                = v1.ErrorOrigin_value
	EventService_ServiceDesc         = v1.EventService_ServiceDesc
	ExtensionService_ServiceDesc     = v1.ExtensionService_ServiceDesc
	File_account_proto               = v1.File_azd_extensions_v1_account_proto
	File_ai_model_proto              = v1.File_azd_extensions_v1_ai_model_proto
	File_container_proto             = v1.File_azd_extensions_v1_container_proto
	File_deployment_proto            = v1.File_azd_extensions_v1_deployment_proto
	File_environment_proto           = v1.File_azd_extensions_v1_environment_proto
	File_errors_proto                = v1.File_azd_extensions_v1_errors_proto
	File_event_proto                 = v1.File_azd_extensions_v1_event_proto
	File_extension_proto             = v1.File_azd_extensions_v1_extension_proto
	File_framework_service_proto     = v1.File_azd_extensions_v1_framework_service_proto
	File_models_proto                = v1.File_azd_extensions_v1_models_proto
	File_project_proto               = v1.File_azd_extensions_v1_project_proto
	File_prompt_proto                = v1.File_azd_extensions_v1_prompt_proto
	File_provisioning_proto          = v1.File_azd_extensions_v1_provisioning_proto
	File_service_target_proto        = v1.File_azd_extensions_v1_service_target_proto
	File_user_config_proto           = v1.File_azd_extensions_v1_user_config_proto
	File_validation_proto            = v1.File_azd_extensions_v1_validation_proto
	File_workflow_proto              = v1.File_azd_extensions_v1_workflow_proto
	FrameworkService_ServiceDesc     = v1.FrameworkService_ServiceDesc
	LocationKind_name                = v1.LocationKind_name
	LocationKind_value               = v1.LocationKind_value
	ProjectService_ServiceDesc       = v1.ProjectService_ServiceDesc
	PromptService_ServiceDesc        = v1.PromptService_ServiceDesc
	ProvisioningService_ServiceDesc  = v1.ProvisioningService_ServiceDesc
	ProvisioningSkippedReason_name   = v1.ProvisioningSkippedReason_name
	ProvisioningSkippedReason_value  = v1.ProvisioningSkippedReason_value
	ServiceTargetService_ServiceDesc = v1.ServiceTargetService_ServiceDesc
	UserConfigService_ServiceDesc    = v1.UserConfigService_ServiceDesc
	ValidationCheckSeverity_name     = v1.ValidationCheckSeverity_name
	ValidationCheckSeverity_value    = v1.ValidationCheckSeverity_value
	ValidationService_ServiceDesc    = v1.ValidationService_ServiceDesc
	WorkflowService_ServiceDesc      = v1.WorkflowService_ServiceDesc
)
View Source
var ErrDebuggerAborted = errors.New("debugger attach aborted")

ErrDebuggerAborted is returned when the user declines to attach a debugger.

View Source
var ErrProjectNotFound = errors.New("azure.yaml not found")

ErrProjectNotFound is returned when azure.yaml cannot be located.

View Source
var (
	FrameworkServiceFactoryKey = func(config *ServiceConfig) string {
		return string(config.Language)
	}
)
View Source
var (
	ServiceTargetFactoryKey = func(config *ServiceConfig) string {
		return string(config.Host)
	}
)

Functions

func AppendPATH added in v1.23.14

func AppendPATH(dirs ...string) error

AppendPATH adds dirs to the end of the PATH environment variable. Duplicate entries already in PATH are not added again.

Platform behavior: see PrependPATH.

func AuthErrorReason added in v1.24.2

func AuthErrorReason(st *status.Status) string

AuthErrorReason extracts the ErrorInfo.Reason from a gRPC status when the domain matches AuthErrorDomain.

func BackupFile added in v1.23.14

func BackupFile(path, suffix string) (string, error)

BackupFile creates a backup copy of path at path+suffix using atomic copy. If the source file does not exist, it returns nil (no backup needed).

The default suffix is ".bak" if suffix is empty.

Returns the backup path on success, or an error if the copy fails.

func CaptureOutput added in v1.23.14

func CaptureOutput(fn func()) (string, string, error)

CaptureOutput captures stdout and stderr output from a function. Useful for testing CLI output.

The function fn is called synchronously. Any writes to os.Stdout and os.Stderr during fn's execution are captured and returned as strings. The original file descriptors are restored after fn returns, even if fn panics.

func ContainerRuntime added in v1.23.14

func ContainerRuntime() string

ContainerRuntime returns the detected container runtime name, or an empty string if no container environment is detected. When multiple container environment variables are set, the first match in containerEnvVars order wins, ensuring deterministic results.

Possible return values: "codespaces", "kubernetes", "devcontainer", "docker", "".

func CopyFileAtomic added in v1.23.14

func CopyFileAtomic(src, dst string, perm os.FileMode) error

CopyFileAtomic copies src to dst atomically using the write-temp-rename pattern. The destination file is never in a partially-written state.

Platform behavior: see WriteFileAtomic.

If perm is zero, the source file's permissions are used.

func DeepMergeJSON added in v1.23.14

func DeepMergeJSON(base, override map[string]any) map[string]any

DeepMergeJSON performs a recursive merge of override into base. When both base and override have a map value for the same key, those maps are merged recursively. Otherwise the override value replaces the base value.

Recursion is bounded to [deepMergeMaxDepth] levels to prevent stack overflow from deeply nested or adversarial inputs. Beyond the limit, the override value replaces the base value (merge degrades to shallow at that level).

func EnsureDir added in v1.23.14

func EnsureDir(dir string, perm os.FileMode) error

EnsureDir creates directory dir and any necessary parents with the given permissions. If the directory already exists, EnsureDir is a no-op and returns nil.

This is a convenience wrapper around os.MkdirAll with an explicit error prefix for diagnostics.

func ErrorLinks(err error) []errorhandler.ErrorLink

ErrorLinks extracts the Links field from structured extension or host gRPC errors. Returns nil if the error has no links.

func ErrorMessage

func ErrorMessage(err error) string

ErrorMessage extracts the user-friendly message from a structured error or a host gRPC error carrying an ActionableErrorDetail. Returns "" otherwise.

func ErrorSuggestion

func ErrorSuggestion(err error) string

ErrorSuggestion extracts the Suggestion field from structured extension or host gRPC errors. Returns an empty string if the error has no suggestion.

func ExecCommand added in v1.23.14

func ExecCommand(ctx context.Context, name string, args ...string) *exec.Cmd

ExecCommand creates an exec.Cmd that runs a program directly without a shell, preventing shell injection. Arguments are passed as a list, not interpolated through a shell parser.

This is the recommended API for executing external programs when the program path and arguments are known. Use ShellCommand only when shell features (pipes, globbing, variable expansion) are genuinely required.

The name is resolved via exec.LookPath-style lookup (PATH search).

func FindFileUpward added in v1.23.14

func FindFileUpward(startDir string, fileName string) (string, error)

FindFileUpward searches for a file by name starting from startDir, walking up parent directories until found or root is reached. Returns the directory containing the file, not the full file path.

func GRPCStatusFromError added in v1.24.3

func GRPCStatusFromError(err error) (*status.Status, bool)

GRPCStatusFromError extracts a *status.Status from err's chain when one is present. Returns (nil, false) if err does not carry a gRPC status.

func GenerateExtensionMetadata

func GenerateExtensionMetadata(schemaVersion, id string, root *cobra.Command) *extensions.ExtensionCommandMetadata

GenerateExtensionMetadata generates ExtensionCommandMetadata from a Cobra root command This function is typically called by extensions to generate their metadata

func GetProjectDir added in v1.23.14

func GetProjectDir() (string, error)

GetProjectDir returns the azd project directory. It checks AZD_EXEC_PROJECT_DIR env var first, then walks up from cwd looking for azure.yaml.

func IsContainerEnvironment added in v1.23.14

func IsContainerEnvironment() bool

IsContainerEnvironment reports whether the current process is running inside a container environment. It checks for:

  • GitHub Codespaces (CODESPACES env var)
  • Kubernetes (KUBERNETES_SERVICE_HOST env var)
  • VS Code Dev Containers (REMOTE_CONTAINERS / REMOTE_CONTAINERS_IPC env vars)
  • Docker (/.dockerenv file)

The detection is best-effort and does not guarantee accuracy in all environments. It is intended for feature gating and diagnostics, not security decisions.

func IsInteractiveTerminal added in v1.23.14

func IsInteractiveTerminal(f *os.File) bool

IsInteractiveTerminal reports whether the given file descriptor is connected to an interactive terminal (TTY).

Uses golang.org/x/term.IsTerminal for reliable cross-platform detection, correctly distinguishing TTYs from non-interactive character devices like /dev/null.

This function is safe to call with nil (returns false).

func IsProcessRunning added in v1.23.14

func IsProcessRunning(pid int) bool

IsProcessRunning checks whether a process with the given PID exists and is still running.

Platform behavior:

  • Unix (Linux/macOS): Sends signal 0 to the process. If the process exists (even if owned by another user), this returns true. If the process does not exist, it returns false. This does NOT verify that the process is the expected one (PID reuse is possible).
  • Windows: Opens the process with PROCESS_QUERY_LIMITED_INFORMATION access and checks the exit code. If the process handle is valid and the exit code is STILL_ACTIVE, returns true.

Note: PID reuse can cause false positives on all platforms. For critical use cases, combine PID checks with process name verification using GetProcessInfo.

Returns false if the PID is invalid (≤ 0).

func IsSecretReference added in v1.23.14

func IsSecretReference(s string) bool

IsSecretReference reports whether s is a Key Vault secret reference in any of the supported formats: akvs://, @Microsoft.KeyVault(SecretUri=...), or @Microsoft.KeyVault(VaultName=...;SecretName=...).

Leading/trailing whitespace and surrounding single or double quotes are stripped before matching, so values like "akvs://..." and ' akvs://... ' are recognized.

func IsStdinTerminal added in v1.23.14

func IsStdinTerminal() bool

IsStdinTerminal reports whether standard input is an interactive terminal.

func IsStdoutTerminal added in v1.23.14

func IsStdoutTerminal() bool

IsStdoutTerminal reports whether standard output is an interactive terminal.

func IsStructuredError added in v1.24.2

func IsStructuredError(err error) bool

IsStructuredError reports whether err is an azd extension structured error.

func LoadAzdEnvironment added in v1.23.14

func LoadAzdEnvironment(ctx context.Context) (map[string]string, error)

LoadAzdEnvironment loads environment variables from the current azd environment. It runs "azd env get-values" and parses the KEY=VALUE output. Returns a map of environment variable names to values.

func LookupTools added in v1.23.14

func LookupTools(names ...string) map[string]ToolInfo

LookupTools searches for multiple tools on PATH in a single call. Returns a map of tool name → ToolInfo. All tools are looked up regardless of whether earlier ones are found.

func MCPErrorResult

func MCPErrorResult(format string, args ...any) *mcp.CallToolResult

MCPErrorResult creates an error CallToolResult with IsError set to true.

func MCPJSONResult

func MCPJSONResult(data any) *mcp.CallToolResult

MCPJSONResult marshals data to JSON and creates a text-content CallToolResult. Returns an error result if marshaling fails.

func MCPTextResult

func MCPTextResult(format string, args ...any) *mcp.CallToolResult

MCPTextResult creates a text-content CallToolResult.

func MergeJSON added in v1.23.14

func MergeJSON(base, override map[string]any) map[string]any

MergeJSON performs a shallow merge of override into base, returning a new map. Both inputs must be JSON-compatible maps (map[string]any). Keys in override take precedence over keys in base.

This is NOT a deep merge — nested maps are replaced entirely by the override value. For predictable extension config behavior, keep config structures flat or use explicit path-based Set operations for nested values.

func NewContext deprecated

func NewContext() context.Context

NewContext initializes a new context with tracing information extracted from environment variables.

Deprecated: Use Run for custom-command extensions — it creates the context, injects the access token, reports structured errors, and handles os.Exit. For lifecycle-listener extensions, use NewListenCommand which sets up context and access token automatically. If you need parsed global flags (--debug, --no-prompt, --cwd, -e), use NewExtensionRootCommand together with Run.

func NewListenCommand

func NewListenCommand(configure func(host *ExtensionHost)) *cobra.Command

NewListenCommand creates the standard "listen" command for lifecycle event extensions. The configure function receives an ExtensionHost to register service targets, framework services, and event handlers before the host starts. If configure is nil, the host runs with no custom registrations.

func NewMetadataCommand

func NewMetadataCommand(schemaVersion, extensionId string, rootCmdProvider func() *cobra.Command) *cobra.Command

NewMetadataCommand creates the standard "metadata" command that outputs extension command metadata for IntelliSense/discovery. rootCmdProvider returns the root command to introspect.

func NewVersionCommand

func NewVersionCommand(extensionId, version string, outputFormat *string) *cobra.Command

NewVersionCommand creates the standard "version" command. outputFormat is a pointer to the output format string (for JSON support).

func PATHContains added in v1.23.14

func PATHContains(dir string) bool

PATHContains reports whether dir is present in the current PATH.

Platform behavior:

  • Windows: Comparison is case-insensitive and normalizes path separators.
  • Unix: Comparison is case-sensitive and exact.

func ParseEnvironmentVariables added in v1.23.14

func ParseEnvironmentVariables(envVars []string) map[string]string

ParseEnvironmentVariables parses a slice of KEY=VALUE strings into a map. Values may optionally be quoted with double quotes, which are stripped. Empty lines and comment lines (starting with #) are skipped.

func PrependPATH added in v1.23.14

func PrependPATH(dirs ...string) error

PrependPATH adds dirs to the front of the PATH environment variable and sets it in the current process environment. Duplicate entries already in PATH are not added again.

Platform behavior:

  • Windows: Uses ';' as the path separator.
  • Unix: Uses ':' as the path separator.

PrependPATH modifies the current process environment. It does not affect parent or child processes beyond normal inheritance.

func RegisterAccountServiceServer

func RegisterAccountServiceServer(s grpc.ServiceRegistrar, srv AccountServiceServer)

func RegisterAiModelServiceServer

func RegisterAiModelServiceServer(s grpc.ServiceRegistrar, srv AiModelServiceServer)

func RegisterContainerServiceServer

func RegisterContainerServiceServer(s grpc.ServiceRegistrar, srv ContainerServiceServer)

func RegisterDeploymentServiceServer

func RegisterDeploymentServiceServer(s grpc.ServiceRegistrar, srv DeploymentServiceServer)

func RegisterEnvironmentServiceServer

func RegisterEnvironmentServiceServer(s grpc.ServiceRegistrar, srv EnvironmentServiceServer)

func RegisterEventServiceServer

func RegisterEventServiceServer(s grpc.ServiceRegistrar, srv EventServiceServer)

func RegisterExtensionServiceServer

func RegisterExtensionServiceServer(s grpc.ServiceRegistrar, srv ExtensionServiceServer)

func RegisterFlagOptions added in v1.24.3

func RegisterFlagOptions(cmd *cobra.Command, opts FlagOptions) *cobra.Command

RegisterFlagOptions configures per-subcommand behavior for an inherited persistent flag (typically one registered by NewExtensionRootCommand, such as -o/--output). One declaration drives:

  • help/usage rendering — flag usage gets "(supported: ...)" appended, and shows the per-command usage/default behavior
  • extension metadata (see GenerateExtensionMetadata) — populates the flag's ValidValues field and overrides its Default/Description fields
  • parse-time validation — values outside AllowedValues are rejected before the command's RunE runs
  • shell completion — AllowedValues are suggested for the flag
  • default substitution — when the user does not pass the flag, the bound variable is set to Default before RunE runs

Empty AllowedValues skips validation/completion. Empty Default leaves the SDK default in place unless HideDefault is true. Repeat calls for the same flag overwrite. A nil command is a no-op.

Panics if Name is empty, or if Default is set but not in a non-empty AllowedValues. Returns an error from PersistentPreRunE if Name does not match any flag visible to the executing command (typo guard; inherited flags only become visible after the command is attached to its parent).

Typical usage:

cmd := &cobra.Command{Use: "list", RunE: runList}
azdext.RegisterFlagOptions(cmd, azdext.FlagOptions{
    Name:          "output",
    AllowedValues: []string{"json", "table"},
    Default:       "json",
})

func RegisterFrameworkServiceServer

func RegisterFrameworkServiceServer(s grpc.ServiceRegistrar, srv FrameworkServiceServer)

func RegisterProjectServiceServer

func RegisterProjectServiceServer(s grpc.ServiceRegistrar, srv ProjectServiceServer)

func RegisterPromptServiceServer

func RegisterPromptServiceServer(s grpc.ServiceRegistrar, srv PromptServiceServer)

func RegisterProvisioningServiceServer added in v1.24.2

func RegisterProvisioningServiceServer(s grpc.ServiceRegistrar, srv ProvisioningServiceServer)

func RegisterServiceTargetServiceServer

func RegisterServiceTargetServiceServer(s grpc.ServiceRegistrar, srv ServiceTargetServiceServer)

func RegisterUserConfigServiceServer

func RegisterUserConfigServiceServer(s grpc.ServiceRegistrar, srv UserConfigServiceServer)

func RegisterValidationServiceServer added in v1.26.0

func RegisterValidationServiceServer(s grpc.ServiceRegistrar, srv ValidationServiceServer)

func RegisterWorkflowServiceServer

func RegisterWorkflowServiceServer(s grpc.ServiceRegistrar, srv WorkflowServiceServer)

func ReportError

func ReportError(ctx context.Context, err error) error

ReportError sends a structured extension error to the azd host via gRPC. It creates a temporary gRPC client using the AZD_SERVER environment variable. Returns nil if AZD_SERVER is not set (extension running outside azd).

func RequireTools added in v1.23.14

func RequireTools(names ...string) error

RequireTools checks that all named tools are available on PATH. Returns nil if all tools are found, or a *ToolsNotFoundError listing the missing tools.

This is useful in extension preRun hooks to fail fast with a clear message:

if err := azdext.RequireTools("docker", "kubectl"); err != nil {
    return err
}

func ReservedFlagNames added in v1.24.0

func ReservedFlagNames() []string

ReservedFlagNames returns the long names of all reserved global flags. This is intended for documentation and error messages.

func Run

func Run(rootCmd *cobra.Command, opts ...RunOption)

Run is the standard entry point for azd extensions. It handles all lifecycle boilerplate that every extension needs:

  • FORCE_COLOR environment variable → color.NoColor
  • cobra SilenceErrors (Run controls error output)
  • Context creation with tracing propagation
  • gRPC access token injection via WithAccessToken
  • Command execution
  • Structured error reporting via gRPC ReportError
  • Error + suggestion display
  • os.Exit on failure

A typical extension main.go becomes:

func main() {
    azdext.Run(cmd.NewRootCommand())
}

func SSRFSafeRedirect

func SSRFSafeRedirect(req *http.Request, via []*http.Request) error

SSRFSafeRedirect is an http.Client CheckRedirect function that blocks redirects to private/loopback IP literals, hostnames that resolve to private networks, and cloud metadata endpoints. It prevents redirect-based SSRF attacks where an attacker-controlled URL redirects to an internal service.

Usage:

client := &http.Client{CheckRedirect: azdext.SSRFSafeRedirect}

func SetupLogging added in v1.23.14

func SetupLogging(opts LoggerOptions)

SetupLogging configures the process-wide default slog.Logger. It is typically called once at startup (for example from NewExtensionRootCommand's PersistentPreRunE callback).

Calling SetupLogging is optional — NewLogger works without it and creates loggers that inherit from slog.Default. SetupLogging is provided for extensions that want explicit control over the global log level and format.

func ShellCommand added in v1.23.14

func ShellCommand(ctx context.Context, script string) (*exec.Cmd, error)

ShellCommand creates an exec.Cmd that executes script through the appropriate shell for the current platform.

Platform behavior:

  • Windows cmd: cmd.exe /C <script>
  • PowerShell: pwsh -NoProfile -NonInteractive -Command <script>
  • Unix shells: <shell> -c <script>

The returned Cmd inherits the provided context for cancellation and timeout. The caller is responsible for setting Stdin, Stdout, Stderr, Dir, and Env on the returned Cmd before running it.

Returns an error if the shell type is unknown and no fallback is available.

Security note: script is passed directly to the shell and may contain arbitrary commands. Callers MUST NOT pass unsanitized user input as the script argument. For executing a known program with arguments (no shell interpolation), use ExecCommand instead.

func ShellCommandWith added in v1.23.14

func ShellCommandWith(ctx context.Context, info ShellInfo, script string) (*exec.Cmd, error)

ShellCommandWith creates an exec.Cmd using the specified ShellInfo. This allows callers to override shell detection for testing or when a specific shell is required.

See ShellCommand for platform behavior details.

func UnwrapError

func UnwrapError(msg *ExtensionError) error

UnwrapError converts an ExtensionError proto back to a typed Go error. It is called from the azd host (via [ExtensionService.ReportError] handler and envelope GetError methods) to deserialize errors received from extensions for telemetry classification and error handling. It returns the appropriate error type based on the origin field.

func UnwrapErrorLinks(links []*ErrorLink) []errorhandler.ErrorLink

UnwrapErrorLinks converts proto ErrorLink messages back into errorhandler.ErrorLink values.

func ValidateConfig added in v1.23.14

func ValidateConfig(path string, data []byte, validators ...ConfigValidator) error

ValidateConfig unmarshals the raw JSON data and runs all supplied validators. Returns the first validation error encountered, wrapped in a *ConfigError.

func ValidateHostname added in v1.23.14

func ValidateHostname(hostname string) error

ValidateHostname checks that hostname conforms to RFC 952/1123.

Rules:

  • Each label must start and end with an alphanumeric character.
  • Labels may contain alphanumeric characters and '-'.
  • Each label is 1–63 characters.
  • Total hostname length is ≤ 253 characters.

Returns a *ValidationError on failure.

func ValidateNoReservedFlagConflicts added in v1.24.0

func ValidateNoReservedFlagConflicts(root *cobra.Command) error

ValidateNoReservedFlagConflicts walks the command tree rooted at cmd and returns an error listing every extension-defined flag that collides with an azd reserved global flag.

Flags registered on the root command's persistent flag set are allowed because the extension SDK intentionally mirrors azd's global flags there (see NewExtensionRootCommand). Only flags added by the extension on subcommands (local or inherited persistent flags not from root) are checked.

func ValidateScriptName added in v1.23.14

func ValidateScriptName(name string) error

ValidateScriptName checks that name does not contain shell metacharacters or path traversal sequences that could lead to command injection.

Rejected patterns:

  • Shell metacharacters: ; | & ` $ ( ) { } [ ] < > ! # ~ * ? " ' \ %
  • Path traversal: ".."
  • Null bytes and newlines
  • Empty names

Returns a *ValidationError on failure.

func ValidateServiceName added in v1.23.14

func ValidateServiceName(name string) error

ValidateServiceName checks that name is a valid DNS-safe service identifier.

Rules:

  • Must start with an alphanumeric character.
  • May contain alphanumeric characters, '.', '_', and '-'.
  • Must be 1–63 characters (DNS label length limit per RFC 1035).

Returns a *ValidationError on failure.

func VerifyProvidersMatchManifest added in v1.28.0

func VerifyProvidersMatchManifest(configure func(host *ExtensionHost), manifestPath string) error

VerifyProvidersMatchManifest asserts that the providers an extension registers via the supplied configure callback exactly match the providers declared in its extension.yaml manifest at manifestPath.

It runs configure against a bare ExtensionHost (no azd connection; provider factories are never invoked) and compares the registered names against the manifest's `providers:` list. Only service-target and provisioning-provider types are compared; framework-service and validation registrations have no manifest representation.

It returns a descriptive error when a provider is declared but not registered, registered but not declared, or listed more than once on either side.

func WaitForDebugger

func WaitForDebugger(ctx context.Context, azdClient *AzdClient) error

WaitForDebugger checks if AZD_EXT_DEBUG environment variable is set to a truthy value. If set, prompts the user to attach a debugger to the current process. This should be called at the start of extension command implementations to enable debugging.

Returns nil if debugging is not enabled or if user confirms.

Returns ErrDebuggerAborted if the user declines to attach a debugger. Returns context.Canceled if the user cancels the prompt (e.g., via Ctrl+C).

func WithAccessToken

func WithAccessToken(ctx context.Context, params ...string) context.Context

WithAccessToken sets the access token for the `azd` client into a new Go context. It also forwards the W3C trace context so telemetry the host records while serving the call joins the azd command's trace instead of starting an unrelated one.

func WriteFileAtomic added in v1.23.14

func WriteFileAtomic(path string, data []byte, perm os.FileMode) error

WriteFileAtomic writes data to the named file atomically. It writes to a temporary file in the same directory as path and renames it into place. This ensures that readers never see a partially-written file and that the operation is crash-safe on file systems that support atomic rename (ext4, APFS, NTFS).

Platform behavior:

  • Unix: os.Rename is atomic within the same filesystem.
  • Windows: os.Rename replaces the target if it exists (Go 1.16+). On older Go runtimes or cross-device moves, the operation may fail. WriteFileAtomic always places the temp file in the same directory to avoid cross-device issues.

The file is created with the specified permissions. If the target already exists its permissions are preserved unless perm is explicitly non-zero.

Returns an error if the directory does not exist, the temp file cannot be created, data cannot be written, or the rename fails.

Types

type AccountServiceClient

type AccountServiceClient = v1.AccountServiceClient

type AccountServiceServer

type AccountServiceServer = v1.AccountServiceServer

type ActionableErrorDetail added in v1.24.3

type ActionableErrorDetail = v1.ActionableErrorDetail

func ActionableErrorDetailFromError added in v1.24.3

func ActionableErrorDetailFromError(err error) *ActionableErrorDetail

ActionableErrorDetailFromError extracts host-originated actionable guidance from a gRPC status error.

func ActionableErrorDetailFromStatus added in v1.24.3

func ActionableErrorDetailFromStatus(st *status.Status) *ActionableErrorDetail

ActionableErrorDetailFromStatus extracts host-originated actionable guidance from a gRPC status.

type AddServiceRequest

type AddServiceRequest = v1.AddServiceRequest

type AiModel

type AiModel = v1.AiModel

type AiModelDeployment

type AiModelDeployment = v1.AiModelDeployment

type AiModelDeploymentOptions

type AiModelDeploymentOptions = v1.AiModelDeploymentOptions

type AiModelFilterOptions

type AiModelFilterOptions = v1.AiModelFilterOptions

type AiModelServiceClient

type AiModelServiceClient = v1.AiModelServiceClient

type AiModelServiceServer

type AiModelServiceServer = v1.AiModelServiceServer

type AiModelSku

type AiModelSku = v1.AiModelSku

type AiModelUsage

type AiModelUsage = v1.AiModelUsage

type AiModelVersion

type AiModelVersion = v1.AiModelVersion

type Artifact

type Artifact = v1.Artifact

type ArtifactKind

type ArtifactKind = v1.ArtifactKind

type ArtifactList

type ArtifactList = v1.ArtifactList

type AzdClient

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

AzdClient is the client for the `azd` gRPC server.

func NewAzdClient

func NewAzdClient(opts ...AzdClientOption) (*AzdClient, error)

NewAzdClient creates a new `azd` client.

func (*AzdClient) Account

func (c *AzdClient) Account() AccountServiceClient

Account returns the account service client.

func (*AzdClient) Ai

Ai returns the AI model service client.

func (*AzdClient) Close

func (c *AzdClient) Close()

Close closes the connection to the `azd` server.

func (*AzdClient) Compose

func (c *AzdClient) Compose() v1beta.ComposeServiceClient

Compose returns the preview compose service client.

func (*AzdClient) Container

func (c *AzdClient) Container() ContainerServiceClient

Container returns the container service client.

func (*AzdClient) Copilot

func (c *AzdClient) Copilot() v1beta.CopilotServiceClient

Copilot returns the preview Copilot agent service client.

func (*AzdClient) Deployment

func (c *AzdClient) Deployment() DeploymentServiceClient

Deployment returns the deployment service client.

func (*AzdClient) Environment

func (c *AzdClient) Environment() EnvironmentServiceClient

Environment returns the environment service client.

func (*AzdClient) Events

func (c *AzdClient) Events() EventServiceClient

Events returns the event service client.

func (*AzdClient) Extension

func (c *AzdClient) Extension() ExtensionServiceClient

Extension returns the extension service client.

func (*AzdClient) FrameworkService

func (c *AzdClient) FrameworkService() FrameworkServiceClient

FrameworkService returns the framework service client.

func (*AzdClient) Project

func (c *AzdClient) Project() ProjectServiceClient

Project returns the project service client.

func (*AzdClient) Prompt

func (c *AzdClient) Prompt() PromptServiceClient

Prompt returns the prompt service client.

func (*AzdClient) Provisioning added in v1.24.2

func (c *AzdClient) Provisioning() ProvisioningServiceClient

Provisioning returns the provisioning service client.

func (*AzdClient) ServiceTarget

func (c *AzdClient) ServiceTarget() ServiceTargetServiceClient

ServiceTarget returns the service target service client.

func (*AzdClient) Telemetry added in v1.31.0

func (c *AzdClient) Telemetry() v1beta.TelemetryServiceClient

Telemetry returns the telemetry service client used to report extension usage events. See extensions/microsoft.azd.demo/internal/cmd/telemetry.go for a worked example.

A fresh client is returned on each call rather than caching it on the AzdClient struct. Service target providers can deploy services concurrently, so an unsynchronized lazily-written cache field could race on first use. The generated client wrapper is cheap and shares the existing connection.

func (*AzdClient) UserConfig

func (c *AzdClient) UserConfig() UserConfigServiceClient

UserConfig returns the user config service client.

func (*AzdClient) Validation added in v1.26.0

func (c *AzdClient) Validation() ValidationServiceClient

Validation returns the validation service client.

func (*AzdClient) Workflow

func (c *AzdClient) Workflow() WorkflowServiceClient

Workflow returns the workflow service client.

type AzdClientOption

type AzdClientOption func(*AzdClient) error

func WithAddress

func WithAddress(address string) AzdClientOption

WithAddress sets the address of the `azd` gRPC server.

type AzureContext

type AzureContext = v1.AzureContext

type AzureScope

type AzureScope = v1.AzureScope

type BaseServiceTargetProvider

type BaseServiceTargetProvider struct{}

BaseServiceTargetProvider provides no-op default implementations for all ServiceTargetProvider methods. Extensions should embed this struct and override only the methods they need.

Example:

type MyProvider struct {
    azdext.BaseServiceTargetProvider
}

func (p *MyProvider) Deploy(
    ctx context.Context,
    serviceConfig *azdext.ServiceConfig,
    serviceContext *azdext.ServiceContext,
    targetResource *azdext.TargetResource,
    progress azdext.ProgressReporter,
) (*azdext.ServiceDeployResult, error) {
    // custom deploy logic
}

func (*BaseServiceTargetProvider) Deploy

func (b *BaseServiceTargetProvider) Deploy(
	ctx context.Context,
	serviceConfig *ServiceConfig,
	serviceContext *ServiceContext,
	targetResource *TargetResource,
	progress ProgressReporter,
) (*ServiceDeployResult, error)

func (*BaseServiceTargetProvider) Endpoints

func (b *BaseServiceTargetProvider) Endpoints(
	ctx context.Context,
	serviceConfig *ServiceConfig,
	targetResource *TargetResource,
) ([]string, error)

func (*BaseServiceTargetProvider) GetTargetResource

func (b *BaseServiceTargetProvider) GetTargetResource(
	ctx context.Context,
	subscriptionId string,
	serviceConfig *ServiceConfig,
	defaultResolver func() (*TargetResource, error),
) (*TargetResource, error)

func (*BaseServiceTargetProvider) Initialize

func (b *BaseServiceTargetProvider) Initialize(ctx context.Context, serviceConfig *ServiceConfig) error

func (*BaseServiceTargetProvider) Package

func (b *BaseServiceTargetProvider) Package(
	ctx context.Context,
	serviceConfig *ServiceConfig,
	serviceContext *ServiceContext,
	progress ProgressReporter,
) (*ServicePackageResult, error)

func (*BaseServiceTargetProvider) Publish

func (b *BaseServiceTargetProvider) Publish(
	ctx context.Context,
	serviceConfig *ServiceConfig,
	serviceContext *ServiceContext,
	targetResource *TargetResource,
	publishOptions *PublishOptions,
	progress ProgressReporter,
) (*ServicePublishResult, error)

type ComponentManager

type ComponentManager[T Provider] struct {
	// contains filtered or unexported fields
}

ComponentManager provides common instance management functionality for both service targets and framework services

func NewComponentManager

func NewComponentManager[T Provider](factoryKeyFunc FactoryKeyProvider, managerTypeName string) *ComponentManager[T]

NewComponentManager creates a new ComponentManager with the specified factory key function

func (*ComponentManager[T]) Close

func (m *ComponentManager[T]) Close() error

Close cleans up all instances

func (*ComponentManager[T]) GetAnyInstance

func (m *ComponentManager[T]) GetAnyInstance() (T, error)

GetAnyInstance gets any available instance (used for Requirements call)

func (*ComponentManager[T]) GetInstance

func (m *ComponentManager[T]) GetInstance(serviceName string) (T, error)

GetInstance gets an existing instance for the service, returns error if not found

func (*ComponentManager[T]) GetOrCreateInstance

func (m *ComponentManager[T]) GetOrCreateInstance(ctx context.Context, serviceConfig *ServiceConfig) (T, error)

GetOrCreateInstance gets an existing instance or creates a new one using the factory

func (*ComponentManager[T]) HasFactory

func (m *ComponentManager[T]) HasFactory(factoryKey string) bool

HasFactory checks if a factory is registered for the given key

func (*ComponentManager[T]) RegisterFactory

func (m *ComponentManager[T]) RegisterFactory(factoryKey string, factory func() T)

RegisterFactory registers a factory function for the given key

type ConfigError added in v1.23.14

type ConfigError struct {
	// Path is the config path that was being accessed.
	Path string

	// Reason classifies the failure.
	Reason ConfigReason

	// Err is the underlying error.
	Err error
}

ConfigError is returned by ConfigHelper methods on domain-level failures.

func (*ConfigError) Error added in v1.23.14

func (e *ConfigError) Error() string

func (*ConfigError) Unwrap added in v1.23.14

func (e *ConfigError) Unwrap() error

type ConfigHelper added in v1.23.14

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

ConfigHelper provides typed, ergonomic access to azd configuration through the gRPC UserConfig and Environment services. It eliminates the boilerplate of raw gRPC calls and JSON marshaling that extension authors otherwise need.

Configuration sources (in merge priority, lowest to highest):

  1. User config (global azd config) — via UserConfigService
  2. Environment config (per-env) — via EnvironmentService

Usage:

ch := azdext.NewConfigHelper(client)
port, err := ch.GetUserString(ctx, "extensions.myext.port")
var cfg MyConfig
err = ch.GetUserJSON(ctx, "extensions.myext", &cfg)

func NewConfigHelper added in v1.23.14

func NewConfigHelper(client *AzdClient) (*ConfigHelper, error)

NewConfigHelper creates a ConfigHelper for the given AZD client.

func (*ConfigHelper) GetEnvJSON added in v1.23.14

func (ch *ConfigHelper) GetEnvJSON(ctx context.Context, path string, out any) (bool, error)

GetEnvJSON retrieves a value from the current environment's config and unmarshals it into out. Returns (false, nil) when the path does not exist.

func (*ConfigHelper) GetEnvString added in v1.23.14

func (ch *ConfigHelper) GetEnvString(ctx context.Context, path string) (string, bool, error)

GetEnvString retrieves a string config value from the current environment. Returns ("", false, nil) when the path does not exist.

func (*ConfigHelper) GetUserJSON added in v1.23.14

func (ch *ConfigHelper) GetUserJSON(ctx context.Context, path string, out any) (bool, error)

GetUserJSON retrieves a value from the global user config and unmarshals it into out. Returns (false, nil) when the path does not exist.

func (*ConfigHelper) GetUserString added in v1.23.14

func (ch *ConfigHelper) GetUserString(ctx context.Context, path string) (string, bool, error)

GetUserString retrieves a string value from the global user config at the given dot-separated path. Returns ("", false, nil) when the path does not exist, and ("", false, err) on gRPC errors.

func (*ConfigHelper) SetEnvJSON added in v1.23.14

func (ch *ConfigHelper) SetEnvJSON(ctx context.Context, path string, value any) error

SetEnvJSON marshals value as JSON and writes it to the current environment's config.

func (*ConfigHelper) SetUserJSON added in v1.23.14

func (ch *ConfigHelper) SetUserJSON(ctx context.Context, path string, value any) error

SetUserJSON marshals value as JSON and writes it to the global user config at the given path.

func (*ConfigHelper) UnsetEnv added in v1.23.14

func (ch *ConfigHelper) UnsetEnv(ctx context.Context, path string) error

UnsetEnv removes a value from the current environment's config.

func (*ConfigHelper) UnsetUser added in v1.23.14

func (ch *ConfigHelper) UnsetUser(ctx context.Context, path string) error

UnsetUser removes a value from the global user config.

type ConfigReason added in v1.23.14

type ConfigReason int

ConfigReason classifies the cause of a ConfigError.

const (
	// ConfigReasonMissing indicates the config path does not exist or is empty.
	ConfigReasonMissing ConfigReason = iota

	// ConfigReasonInvalidFormat indicates the config value is not valid JSON
	// or cannot be unmarshaled into the target type.
	ConfigReasonInvalidFormat

	// ConfigReasonValidationFailed indicates a validator rejected the config value.
	ConfigReasonValidationFailed
)

func (ConfigReason) String added in v1.23.14

func (r ConfigReason) String() string

String returns a human-readable label.

type ConfigValidator added in v1.23.14

type ConfigValidator func(value any) error

ConfigValidator defines a function that validates a config value. It returns nil if valid, or an error describing the validation failure.

func RequiredKeys added in v1.23.14

func RequiredKeys(keys ...string) ConfigValidator

RequiredKeys returns a ConfigValidator that checks for the presence of the specified keys in a map value.

type ConfirmOptions

type ConfirmOptions = v1.ConfirmOptions

type ConfirmRequest

type ConfirmRequest = v1.ConfirmRequest

type ConfirmResponse

type ConfirmResponse = v1.ConfirmResponse

type ContainerBuildRequest

type ContainerBuildRequest = v1.ContainerBuildRequest

type ContainerBuildResponse

type ContainerBuildResponse = v1.ContainerBuildResponse

type ContainerPackageRequest

type ContainerPackageRequest = v1.ContainerPackageRequest

type ContainerPackageResponse

type ContainerPackageResponse = v1.ContainerPackageResponse

type ContainerPublishRequest

type ContainerPublishRequest = v1.ContainerPublishRequest

type ContainerPublishResponse

type ContainerPublishResponse = v1.ContainerPublishResponse

type ContainerServiceClient

type ContainerServiceClient = v1.ContainerServiceClient

type ContainerServiceServer

type ContainerServiceServer = v1.ContainerServiceServer

type Deployment

type Deployment = v1.Deployment

type DeploymentServiceClient

type DeploymentServiceClient = v1.DeploymentServiceClient

type DeploymentServiceServer

type DeploymentServiceServer = v1.DeploymentServiceServer

type DockerProjectOptions

type DockerProjectOptions = v1.DockerProjectOptions

type EmptyRequest

type EmptyRequest = v1.EmptyRequest

type EmptyResponse

type EmptyResponse = v1.EmptyResponse

type Environment

type Environment = v1.Environment

type EnvironmentDescription

type EnvironmentDescription = v1.EnvironmentDescription

type EnvironmentListResponse

type EnvironmentListResponse = v1.EnvironmentListResponse

type EnvironmentResponse

type EnvironmentResponse = v1.EnvironmentResponse

type EnvironmentServiceClient

type EnvironmentServiceClient = v1.EnvironmentServiceClient

type EnvironmentServiceServer

type EnvironmentServiceServer = v1.EnvironmentServiceServer
type ErrorLink = v1.ErrorLink
func WrapErrorLinks(links []errorhandler.ErrorLink) []*ErrorLink

WrapErrorLinks converts errorhandler.ErrorLink values into proto ErrorLink messages.

type ErrorOrigin

type ErrorOrigin = v1.ErrorOrigin

type EventManager

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

func NewEventManager

func NewEventManager(extensionId string, azdClient *AzdClient, brokerLogger *log.Logger) *EventManager

func (*EventManager) AddProjectEventHandler

func (em *EventManager) AddProjectEventHandler(ctx context.Context, eventName string, handler ProjectEventHandler) error

func (*EventManager) AddServiceEventHandler

func (em *EventManager) AddServiceEventHandler(
	ctx context.Context,
	eventName string,
	handler ServiceEventHandler,
	options *ServiceEventOptions,
) error

func (*EventManager) Close

func (em *EventManager) Close() error

func (*EventManager) Ready

func (em *EventManager) Ready(ctx context.Context) error

Ready blocks until the message broker starts receiving messages or the context is cancelled. This ensures the stream is initialized and then waits for the broker to be ready. Returns nil when ready, or context error if the context is cancelled before ready.

func (*EventManager) Receive

func (em *EventManager) Receive(ctx context.Context) error

Receive starts the broker's message dispatcher and blocks until the stream completes. Returns nil on graceful shutdown, or an error if the stream fails. This method is safe for concurrent access but only allows one active Run() at a time. Receive starts the broker's message dispatcher and blocks until the stream completes. This method ensures the stream is initialized then runs the broker.

func (*EventManager) RemoveProjectEventHandler

func (em *EventManager) RemoveProjectEventHandler(eventName string)

func (*EventManager) RemoveServiceEventHandler

func (em *EventManager) RemoveServiceEventHandler(eventName string)

type EventMessage

type EventMessage = v1.EventMessage

type EventMessageEnvelope

type EventMessageEnvelope struct{}

EventMessageEnvelope provides message operations for EventMessage It implements the grpcbroker.MessageEnvelope interface This envelope extracts extension ID from gRPC context for correlation.

func NewEventMessageEnvelope

func NewEventMessageEnvelope() *EventMessageEnvelope

NewEventMessageEnvelope creates a new EventMessageEnvelope instance.

func (*EventMessageEnvelope) CreateProgressMessage

func (ops *EventMessageEnvelope) CreateProgressMessage(requestId string, message string) *EventMessage

CreateProgressMessage returns nil as EventMessage doesn't support progress messages

func (*EventMessageEnvelope) GetError

func (ops *EventMessageEnvelope) GetError(msg *EventMessage) error

GetError returns nil as EventMessage doesn't have an Error field. Error handling is done through status strings in handler status messages.

func (*EventMessageEnvelope) GetInnerMessage

func (ops *EventMessageEnvelope) GetInnerMessage(msg *EventMessage) any

GetInnerMessage returns the inner message from the oneof field

func (*EventMessageEnvelope) GetProgressMessage

func (ops *EventMessageEnvelope) GetProgressMessage(msg *EventMessage) string

GetProgressMessage returns empty string as EventMessage doesn't support progress messages

func (*EventMessageEnvelope) GetRequestId

func (ops *EventMessageEnvelope) GetRequestId(ctx context.Context, msg *EventMessage) string

GetRequestId generates a correlation key from the message content and context. For EventMessage, the correlation key is generated from extension.Id (from context) + eventName + serviceName.

func (*EventMessageEnvelope) IsProgressMessage

func (ops *EventMessageEnvelope) IsProgressMessage(msg *EventMessage) bool

IsProgressMessage returns false as EventMessage doesn't support progress messages

func (*EventMessageEnvelope) SetError

func (ops *EventMessageEnvelope) SetError(msg *EventMessage, err error)

SetError is a no-op for EventMessage as it doesn't have an Error field.

func (*EventMessageEnvelope) SetRequestId

func (ops *EventMessageEnvelope) SetRequestId(ctx context.Context, msg *EventMessage, id string)

SetRequestId is a no-op for EventMessage as it doesn't have a RequestId field. Correlation is managed through message content (event names).

type EventMessage_InvokeProjectHandler

type EventMessage_InvokeProjectHandler = v1.EventMessage_InvokeProjectHandler

type EventMessage_InvokeServiceHandler

type EventMessage_InvokeServiceHandler = v1.EventMessage_InvokeServiceHandler

type EventMessage_ProjectHandlerStatus

type EventMessage_ProjectHandlerStatus = v1.EventMessage_ProjectHandlerStatus

type EventMessage_ServiceHandlerStatus

type EventMessage_ServiceHandlerStatus = v1.EventMessage_ServiceHandlerStatus

type EventMessage_SubscribeProjectEvent

type EventMessage_SubscribeProjectEvent = v1.EventMessage_SubscribeProjectEvent

type EventMessage_SubscribeServiceEvent

type EventMessage_SubscribeServiceEvent = v1.EventMessage_SubscribeServiceEvent

type EventServiceClient

type EventServiceClient = v1.EventServiceClient

type EventServiceServer

type EventServiceServer = v1.EventServiceServer

type EventService_EventStreamClient

type EventService_EventStreamClient = v1.EventService_EventStreamClient

type EventService_EventStreamServer

type EventService_EventStreamServer = v1.EventService_EventStreamServer

type ExtensionCommandOptions

type ExtensionCommandOptions struct {
	// Name is the extension name (used in command Use field)
	Name string
	// Version is the extension version
	Version string
	// Use overrides the default Use string (defaults to Name)
	Use string
	// Short is a short description
	Short string
	// Long is a long description
	Long string
}

ExtensionCommandOptions configures the extension root command.

type ExtensionContext

type ExtensionContext struct {
	Debug        bool
	NoPrompt     bool
	Cwd          string
	Environment  string
	OutputFormat string
	// contains filtered or unexported fields
}

ExtensionContext holds parsed global state available to extension commands.

func NewExtensionRootCommand

func NewExtensionRootCommand(opts ExtensionCommandOptions) (*cobra.Command, *ExtensionContext)

NewExtensionRootCommand creates a root cobra.Command pre-configured for azd extensions. It automatically:

  • Registers azd's global flags (--debug, --no-prompt, --cwd, -e/--environment, --output)
  • Reads AZD_* environment variables set by the azd framework
  • Sets up OpenTelemetry trace context from TRACEPARENT/TRACESTATE env vars
  • Calls WithAccessToken() on the command context

Sets cobra.EnableTraverseRunHooks = true so the SDK's PersistentPreRunE runs even when subcommands define their own. Per-command flag overrides registered via RegisterFlagOptions are applied before subcommand pre-runs see them.

NOTE: This function and its companion helpers (NewListenCommand, NewMetadataCommand, NewVersionCommand) depend on github.com/spf13/cobra. If non-cobra CLI frameworks gain adoption among extension authors, these symbols are candidates for extraction into an azdext/cobra sub-package so the core SDK remains framework-agnostic.

func (*ExtensionContext) Context

func (ec *ExtensionContext) Context() context.Context

Context returns the prepared context with tracing and access token metadata.

type ExtensionError

type ExtensionError = v1.ExtensionError

func ExtensionErrorFromStatus added in v1.34.0

func ExtensionErrorFromStatus(st *status.Status) *ExtensionError

ExtensionErrorFromStatus extracts a relayed extension error detail from a gRPC status.

func WrapError

func WrapError(err error) *ExtensionError

WrapError converts a Go error into an ExtensionError proto for transmission to the azd host. It is called from extension processes (via ReportError and envelope SetError methods) to serialize errors before sending them over gRPC.

The function applies detection in priority order:

  1. ServiceError / LocalError / ToolError — already structured by extension code (highest specificity)
  2. azcore.ResponseError — Azure SDK HTTP errors
  3. gRPC status — host-originated errors carrying ActionableErrorDetail and/or auth ErrorInfo
  4. Fallback — unclassified error with original message

The counterpart UnwrapError is called from the azd host to deserialize the proto back into typed Go errors for telemetry classification.

type ExtensionError_LocalError

type ExtensionError_LocalError = v1.ExtensionError_LocalError

type ExtensionError_ServiceError

type ExtensionError_ServiceError = v1.ExtensionError_ServiceError

type ExtensionHost

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

ExtensionHost coordinates registering service targets, wiring event handlers, and signaling readiness.

func NewExtensionHost

func NewExtensionHost(client *AzdClient) *ExtensionHost

NewExtensionHost creates a new ExtensionHost for the supplied azd client.

func (*ExtensionHost) Client

func (er *ExtensionHost) Client() *AzdClient

Client returns the underlying AzdClient. This is useful when service target or framework service factories need the client, for example when called from a NewListenCommand configure callback:

azdext.NewListenCommand(func(host *azdext.ExtensionHost) {
    host.WithServiceTarget("appservice", func() azdext.ServiceTargetProvider {
        return NewAppServiceProvider(host.Client())
    })
})

func (*ExtensionHost) ProvisioningProviders added in v1.28.0

func (er *ExtensionHost) ProvisioningProviders() []ProvisioningProviderRegistration

ProvisioningProviders returns a copy of the provisioning providers registered so far. See ExtensionHost.ServiceTargets.

func (*ExtensionHost) Run

func (er *ExtensionHost) Run(ctx context.Context) error

Run wires the configured service targets and event handlers, signals readiness, and blocks until shutdown.

func (*ExtensionHost) ServiceTargets added in v1.28.0

func (er *ExtensionHost) ServiceTargets() []ServiceTargetRegistration

ServiceTargets returns a copy of the service target providers registered so far, letting tests and tooling introspect registrations without invoking Run.

func (*ExtensionHost) WithFrameworkService

func (er *ExtensionHost) WithFrameworkService(language string, factory FrameworkServiceFactory) *ExtensionHost

WithFrameworkService registers a framework service provider to be wired when Run is invoked.

func (*ExtensionHost) WithProjectEventHandler

func (er *ExtensionHost) WithProjectEventHandler(eventName string, handler ProjectEventHandler) *ExtensionHost

WithProjectEventHandler registers a project-level event handler to be wired when Run is invoked.

func (*ExtensionHost) WithProvisioningProvider added in v1.24.2

func (er *ExtensionHost) WithProvisioningProvider(
	name string,
	factory ProvisioningProviderFactory,
) *ExtensionHost

WithProvisioningProvider registers a provisioning provider to be wired when Run is invoked.

func (*ExtensionHost) WithServiceEventHandler

func (er *ExtensionHost) WithServiceEventHandler(
	eventName string,
	handler ServiceEventHandler,
	options *ServiceEventOptions,
) *ExtensionHost

WithServiceEventHandler registers a service-level event handler to be wired when Run is invoked.

func (*ExtensionHost) WithServiceTarget

func (er *ExtensionHost) WithServiceTarget(host string, factory ServiceTargetFactory) *ExtensionHost

WithServiceTarget registers a service target provider to be wired when Run is invoked.

func (*ExtensionHost) WithValidationCheck added in v1.26.0

func (er *ExtensionHost) WithValidationCheck(
	reg ValidationCheckRegistration,
) *ExtensionHost

WithValidationCheck registers a validation check to be wired when Run is invoked. The checkType identifies the validation context (e.g. "provision"), and the ruleID is a stable identifier for this check.

type ExtensionServiceClient

type ExtensionServiceClient = v1.ExtensionServiceClient

type ExtensionServiceServer

type ExtensionServiceServer = v1.ExtensionServiceServer

type ExternalTool

type ExternalTool = v1.ExternalTool

type FactoryKeyProvider

type FactoryKeyProvider func(*ServiceConfig) string

FactoryKeyProvider extracts the factory key from a ServiceConfig

type FlagConflict added in v1.24.0

type FlagConflict struct {
	// Command is the full command path (e.g. "model custom create").
	Command string
	// FlagName is the long name of the conflicting flag.
	FlagName string
	// FlagShort is the short name of the conflicting flag (may be empty).
	FlagShort string
	// ReservedLong is the long name of the reserved flag it conflicts with.
	ReservedLong string
	// Reason describes why it conflicts (e.g. "short flag -e is reserved").
	Reason string
}

FlagConflict describes a single flag that conflicts with a reserved azd global flag.

func (FlagConflict) String added in v1.24.0

func (c FlagConflict) String() string

type FlagOptions added in v1.24.3

type FlagOptions struct {
	// Name is the flag name without leading dashes (e.g. "output"). Required.
	Name string

	// AllowedValues, when non-empty, restricts accepted values, drives
	// "(supported: ...)" help text, populates metadata ValidValues, and
	// powers shell completion. Matched case-sensitively; order is preserved.
	AllowedValues []string

	// Default, when non-empty, becomes the per-subcommand default: shown in
	// help, surfaced in metadata, and substituted into the bound variable
	// (e.g. [ExtensionContext.OutputFormat]) when the user does not pass
	// the flag. Substitution preserves cmd.Flags().Changed(name) == false.
	Default string

	// Usage, when non-empty, replaces the inherited flag usage text for this
	// subcommand's help and metadata.
	Usage string

	// HideDefault suppresses the inherited flag default in help and metadata
	// without changing the bound runtime value.
	HideDefault bool
}

FlagOptions describes per-subcommand configuration for an inherited persistent flag. See RegisterFlagOptions for the effects each field drives.

type FrameworkPackageRequirements

type FrameworkPackageRequirements = v1.FrameworkPackageRequirements

type FrameworkRequirements

type FrameworkRequirements = v1.FrameworkRequirements

type FrameworkServiceBuildRequest

type FrameworkServiceBuildRequest = v1.FrameworkServiceBuildRequest

type FrameworkServiceBuildResponse

type FrameworkServiceBuildResponse = v1.FrameworkServiceBuildResponse

type FrameworkServiceClient

type FrameworkServiceClient = v1.FrameworkServiceClient

type FrameworkServiceEnvelope

type FrameworkServiceEnvelope struct{}

FrameworkServiceEnvelope provides message operations for FrameworkServiceMessage It implements the grpcbroker.MessageEnvelope interface

func NewFrameworkServiceEnvelope

func NewFrameworkServiceEnvelope() *FrameworkServiceEnvelope

NewFrameworkServiceEnvelope creates a new FrameworkServiceEnvelope instance

func (*FrameworkServiceEnvelope) CreateProgressMessage

func (ops *FrameworkServiceEnvelope) CreateProgressMessage(requestId string, message string) *FrameworkServiceMessage

CreateProgressMessage creates a new progress message envelope with the given text. This is used by server-side handlers to send progress updates back to clients.

func (*FrameworkServiceEnvelope) GetError

GetError returns the error from the message as a Go error type. It returns a typed error based on the ErrorOrigin that preserves structured information for telemetry.

func (*FrameworkServiceEnvelope) GetInnerMessage

func (ops *FrameworkServiceEnvelope) GetInnerMessage(msg *FrameworkServiceMessage) any

GetInnerMessage returns the inner message from the oneof field

func (*FrameworkServiceEnvelope) GetProgressMessage

func (ops *FrameworkServiceEnvelope) GetProgressMessage(msg *FrameworkServiceMessage) string

GetProgressMessage extracts the progress message text from a progress message. Returns empty string if the message is not a progress message.

func (*FrameworkServiceEnvelope) GetRequestId

GetRequestId returns the request ID from the message

func (*FrameworkServiceEnvelope) IsProgressMessage

func (ops *FrameworkServiceEnvelope) IsProgressMessage(msg *FrameworkServiceMessage) bool

IsProgressMessage returns true if the message contains a progress message

func (*FrameworkServiceEnvelope) SetError

func (ops *FrameworkServiceEnvelope) SetError(msg *FrameworkServiceMessage, err error)

SetError sets an error on the message. It detects the error type and populates the appropriate source details.

func (*FrameworkServiceEnvelope) SetRequestId

func (ops *FrameworkServiceEnvelope) SetRequestId(ctx context.Context, msg *FrameworkServiceMessage, id string)

SetRequestId sets the request ID on the message

type FrameworkServiceFactory

type FrameworkServiceFactory ProviderFactory[FrameworkServiceProvider]

FrameworkServiceFactory describes a function that creates an instance of a framework service provider

type FrameworkServiceInitializeRequest

type FrameworkServiceInitializeRequest = v1.FrameworkServiceInitializeRequest

type FrameworkServiceInitializeResponse

type FrameworkServiceInitializeResponse = v1.FrameworkServiceInitializeResponse

type FrameworkServiceManager

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

FrameworkServiceManager handles registration and request forwarding for a framework service provider.

func NewFrameworkServiceManager

func NewFrameworkServiceManager(extensionId string, client *AzdClient, brokerLogger *log.Logger) *FrameworkServiceManager

NewFrameworkServiceManager creates a new FrameworkServiceManager for an AzdClient.

func (*FrameworkServiceManager) Close

func (m *FrameworkServiceManager) Close() error

Close closes the framework service manager and cleans up resources. This method is thread-safe for concurrent access.

func (*FrameworkServiceManager) Ready

Ready blocks until the message broker starts receiving messages or the context is cancelled. This ensures the stream is initialized and then waits for the broker to be ready. Returns nil when ready, or context error if the context is cancelled before ready.

func (*FrameworkServiceManager) Receive

func (m *FrameworkServiceManager) Receive(ctx context.Context) error

Receive starts the broker's message dispatcher and blocks until the stream completes. This method ensures the stream is initialized then runs the broker.

func (*FrameworkServiceManager) Register

func (m *FrameworkServiceManager) Register(
	ctx context.Context,
	factory FrameworkServiceFactory,
	language string,
) error

Register registers a framework service provider with the specified language name.

type FrameworkServiceMessage

type FrameworkServiceMessage = v1.FrameworkServiceMessage

type FrameworkServiceMessage_BuildRequest

type FrameworkServiceMessage_BuildRequest = v1.FrameworkServiceMessage_BuildRequest

type FrameworkServiceMessage_BuildResponse

type FrameworkServiceMessage_BuildResponse = v1.FrameworkServiceMessage_BuildResponse

type FrameworkServiceMessage_InitializeRequest

type FrameworkServiceMessage_InitializeRequest = v1.FrameworkServiceMessage_InitializeRequest

type FrameworkServiceMessage_InitializeResponse

type FrameworkServiceMessage_InitializeResponse = v1.FrameworkServiceMessage_InitializeResponse

type FrameworkServiceMessage_PackageRequest

type FrameworkServiceMessage_PackageRequest = v1.FrameworkServiceMessage_PackageRequest

type FrameworkServiceMessage_PackageResponse

type FrameworkServiceMessage_PackageResponse = v1.FrameworkServiceMessage_PackageResponse

type FrameworkServiceMessage_ProgressMessage

type FrameworkServiceMessage_ProgressMessage = v1.FrameworkServiceMessage_ProgressMessage

type FrameworkServiceMessage_RequirementsRequest

type FrameworkServiceMessage_RequirementsRequest = v1.FrameworkServiceMessage_RequirementsRequest

type FrameworkServiceMessage_RequirementsResponse

type FrameworkServiceMessage_RequirementsResponse = v1.FrameworkServiceMessage_RequirementsResponse

type FrameworkServiceMessage_RestoreRequest

type FrameworkServiceMessage_RestoreRequest = v1.FrameworkServiceMessage_RestoreRequest

type FrameworkServiceMessage_RestoreResponse

type FrameworkServiceMessage_RestoreResponse = v1.FrameworkServiceMessage_RestoreResponse

type FrameworkServicePackageRequest

type FrameworkServicePackageRequest = v1.FrameworkServicePackageRequest

type FrameworkServicePackageResponse

type FrameworkServicePackageResponse = v1.FrameworkServicePackageResponse

type FrameworkServiceProgressMessage

type FrameworkServiceProgressMessage = v1.FrameworkServiceProgressMessage

type FrameworkServiceProvider

type FrameworkServiceProvider interface {
	Initialize(ctx context.Context, serviceConfig *ServiceConfig) error
	RequiredExternalTools(ctx context.Context, serviceConfig *ServiceConfig) ([]*ExternalTool, error)
	Requirements() (*FrameworkRequirements, error)
	Restore(
		ctx context.Context,
		serviceConfig *ServiceConfig,
		serviceContext *ServiceContext,
		progress grpcbroker.ProgressFunc,
	) (*ServiceRestoreResult, error)
	Build(
		ctx context.Context,
		serviceConfig *ServiceConfig,
		serviceContext *ServiceContext,
		progress grpcbroker.ProgressFunc,
	) (*ServiceBuildResult, error)
	Package(
		ctx context.Context,
		serviceConfig *ServiceConfig,
		serviceContext *ServiceContext,
		progress grpcbroker.ProgressFunc,
	) (*ServicePackageResult, error)
}

FrameworkServiceProvider defines the interface for framework service logic.

type FrameworkServiceRegistration

type FrameworkServiceRegistration struct {
	Language string
	Factory  func() FrameworkServiceProvider
}

FrameworkServiceRegistration describes a framework service provider to register with azd core.

type FrameworkServiceRequiredExternalToolsRequest

type FrameworkServiceRequiredExternalToolsRequest = v1.FrameworkServiceRequiredExternalToolsRequest

type FrameworkServiceRequiredExternalToolsResponse

type FrameworkServiceRequiredExternalToolsResponse = v1.FrameworkServiceRequiredExternalToolsResponse

type FrameworkServiceRequirementsRequest

type FrameworkServiceRequirementsRequest = v1.FrameworkServiceRequirementsRequest

type FrameworkServiceRequirementsResponse

type FrameworkServiceRequirementsResponse = v1.FrameworkServiceRequirementsResponse

type FrameworkServiceRestoreRequest

type FrameworkServiceRestoreRequest = v1.FrameworkServiceRestoreRequest

type FrameworkServiceRestoreResponse

type FrameworkServiceRestoreResponse = v1.FrameworkServiceRestoreResponse

type FrameworkServiceServer

type FrameworkServiceServer = v1.FrameworkServiceServer

type FrameworkService_StreamClient

type FrameworkService_StreamClient = v1.FrameworkService_StreamClient

type FrameworkService_StreamServer

type FrameworkService_StreamServer = v1.FrameworkService_StreamServer

type GetConfigRequest

type GetConfigRequest = v1.GetConfigRequest

type GetConfigResponse

type GetConfigResponse = v1.GetConfigResponse

type GetConfigSectionRequest

type GetConfigSectionRequest = v1.GetConfigSectionRequest

type GetConfigSectionResponse

type GetConfigSectionResponse = v1.GetConfigSectionResponse

type GetConfigStringRequest

type GetConfigStringRequest = v1.GetConfigStringRequest

type GetConfigStringResponse

type GetConfigStringResponse = v1.GetConfigStringResponse

type GetDeploymentContextResponse

type GetDeploymentContextResponse = v1.GetDeploymentContextResponse

type GetDeploymentResponse

type GetDeploymentResponse = v1.GetDeploymentResponse

type GetEnvRequest

type GetEnvRequest = v1.GetEnvRequest

type GetEnvironmentRequest

type GetEnvironmentRequest = v1.GetEnvironmentRequest

type GetProjectConfigSectionRequest

type GetProjectConfigSectionRequest = v1.GetProjectConfigSectionRequest

type GetProjectConfigSectionResponse

type GetProjectConfigSectionResponse = v1.GetProjectConfigSectionResponse

type GetProjectConfigValueRequest

type GetProjectConfigValueRequest = v1.GetProjectConfigValueRequest

type GetProjectConfigValueResponse

type GetProjectConfigValueResponse = v1.GetProjectConfigValueResponse

type GetProjectResponse

type GetProjectResponse = v1.GetProjectResponse

type GetResolvedServicesResponse

type GetResolvedServicesResponse = v1.GetResolvedServicesResponse

type GetServiceConfigSectionRequest

type GetServiceConfigSectionRequest = v1.GetServiceConfigSectionRequest

type GetServiceConfigSectionResponse

type GetServiceConfigSectionResponse = v1.GetServiceConfigSectionResponse

type GetServiceConfigValueRequest

type GetServiceConfigValueRequest = v1.GetServiceConfigValueRequest

type GetServiceConfigValueResponse

type GetServiceConfigValueResponse = v1.GetServiceConfigValueResponse

type GetServiceTargetResourceRequest

type GetServiceTargetResourceRequest = v1.GetServiceTargetResourceRequest

type GetServiceTargetResourceResponse

type GetServiceTargetResourceResponse = v1.GetServiceTargetResourceResponse

type GetTargetResourceRequest

type GetTargetResourceRequest = v1.GetTargetResourceRequest

type GetTargetResourceResponse

type GetTargetResourceResponse = v1.GetTargetResourceResponse

type GetUserConfigRequest

type GetUserConfigRequest = v1.GetUserConfigRequest

type GetUserConfigResponse

type GetUserConfigResponse = v1.GetUserConfigResponse

type GetUserConfigSectionRequest

type GetUserConfigSectionRequest = v1.GetUserConfigSectionRequest

type GetUserConfigSectionResponse

type GetUserConfigSectionResponse = v1.GetUserConfigSectionResponse

type GetUserConfigStringRequest

type GetUserConfigStringRequest = v1.GetUserConfigStringRequest

type GetUserConfigStringResponse

type GetUserConfigStringResponse = v1.GetUserConfigStringResponse

type HTTPDoer

type HTTPDoer interface {
	Do(ctx context.Context, method, url string, body io.Reader) (*http.Response, error)
}

HTTPDoer abstracts the HTTP call so that ResilientClient or any *http.Client can power pagination.

type InfraOptions

type InfraOptions = v1.InfraOptions

type InteractiveInfo added in v1.23.14

type InteractiveInfo struct {
	// Mode is the detected interactive mode.
	Mode InteractiveMode
	// StdinTTY is true if stdin is a terminal.
	StdinTTY bool
	// StdoutTTY is true if stdout is a terminal.
	StdoutTTY bool
	// StderrTTY is true if stderr is a terminal.
	StderrTTY bool
	// NoPrompt is true if the AZD_NO_PROMPT environment variable is set,
	// indicating that the user or host has explicitly disabled interactive
	// prompts.
	NoPrompt bool
	// CI is true if a CI environment was detected (CI, GITHUB_ACTIONS,
	// TF_BUILD, JENKINS_URL, etc.).
	CI bool
	// Agent is true if an AI coding agent was detected (CLAUDECODE,
	// COPILOT_CLI, etc.). This identifies the process environment but
	// does not override terminal capabilities.
	Agent bool
}

InteractiveInfo describes the interactive capabilities of the current process environment.

func DetectInteractive added in v1.23.14

func DetectInteractive() InteractiveInfo

DetectInteractive inspects the current process environment to determine interactive capabilities.

Detection checks:

  • os.Stdin / os.Stdout / os.Stderr file mode (character device = TTY)
  • AZD_NO_PROMPT environment variable
  • CI environment variables: CI, GITHUB_ACTIONS, TF_BUILD, JENKINS_URL, GITLAB_CI, CIRCLECI, TRAVIS, BUILDKITE, CODEBUILD_BUILD_ID
  • Agent environment variables: CLAUDECODE, COPILOT_CLI, and other known agent markers

Platform behavior:

  • All platforms: Uses os.File.Stat() ModeCharDevice to detect TTY.
  • Windows: Windows Terminal, ConPTY, and mintty are detected as TTY.
  • Unix: Standard isatty behavior via file mode.

func (InteractiveInfo) CanColorize added in v1.23.14

func (i InteractiveInfo) CanColorize() bool

CanColorize reports whether it is safe to use ANSI color/style codes in output. This requires stdout to be a TTY (unless FORCE_COLOR is set).

func (InteractiveInfo) CanPrompt added in v1.23.14

func (i InteractiveInfo) CanPrompt() bool

CanPrompt reports whether it is safe to show interactive prompts to the user. This requires:

  1. stdin is a TTY
  2. stdout is a TTY
  3. AZD_NO_PROMPT is not set
  4. Not in CI

type InteractiveMode added in v1.23.14

type InteractiveMode string

InteractiveMode describes the level of interactive support available.

const (
	// InteractiveFull means the process has a TTY on stdin, stdout, and stderr.
	// Full interactive prompts and TUI elements are available.
	InteractiveFull InteractiveMode = "full"
	// InteractiveLimited means some stdio is a terminal but not all.
	// Limited interaction is possible (e.g., output coloring but no prompts).
	InteractiveLimited InteractiveMode = "limited"
	// InteractiveNone means no stdio is a terminal. The process is running
	// non-interactively (piped, CI, background, cron, etc.).
	InteractiveNone InteractiveMode = "none"
)

func (InteractiveMode) String added in v1.23.14

func (m InteractiveMode) String() string

String returns the string representation of the interactive mode.

type InvokeProjectHandler

type InvokeProjectHandler = v1.InvokeProjectHandler

type InvokeServiceHandler

type InvokeServiceHandler = v1.InvokeServiceHandler

type KeyValue

type KeyValue = v1.KeyValue

type KeyValueListResponse

type KeyValueListResponse = v1.KeyValueListResponse

type KeyValueResponse

type KeyValueResponse = v1.KeyValueResponse

type KeyVaultResolveError added in v1.23.14

type KeyVaultResolveError struct {
	// Reference is the original akvs:// URI that was being resolved.
	Reference string

	// Reason classifies the failure.
	Reason ResolveReason

	// Err is the underlying error.
	Err error
}

KeyVaultResolveError is returned when KeyVaultResolver.Resolve fails.

func (*KeyVaultResolveError) Error added in v1.23.14

func (e *KeyVaultResolveError) Error() string

func (*KeyVaultResolveError) Unwrap added in v1.23.14

func (e *KeyVaultResolveError) Unwrap() error

type KeyVaultResolver added in v1.23.14

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

KeyVaultResolver resolves Azure Key Vault secret references for extension scenarios. It uses the extension's TokenProvider for authentication and the Azure SDK data-plane client for secret retrieval.

Three reference formats are supported:

akvs://<subscription-id>/<vault-name>/<secret-name>
@Microsoft.KeyVault(SecretUri=https://<vault>.vault.azure.net/secrets/<secret>[/<version>])
@Microsoft.KeyVault(VaultName=<vault>;SecretName=<secret>[;SecretVersion=<version>])

The akvs:// scheme is the preferred compact form. The @Microsoft.KeyVault format supports both the SecretUri= variant and the VaultName/SecretName form.

Usage:

tp, _ := azdext.NewTokenProvider(ctx, client, nil)
resolver, _ := azdext.NewKeyVaultResolver(tp, nil)
value, err := resolver.Resolve(ctx, "akvs://sub-id/my-vault/my-secret")

func NewKeyVaultResolver added in v1.23.14

func NewKeyVaultResolver(credential azcore.TokenCredential, opts *KeyVaultResolverOptions) (*KeyVaultResolver, error)

NewKeyVaultResolver creates a KeyVaultResolver with the given credential.

credential must not be nil; it is typically a *TokenProvider. If opts is nil, production defaults are used.

func (*KeyVaultResolver) Resolve added in v1.23.14

func (r *KeyVaultResolver) Resolve(ctx context.Context, ref string) (string, error)

Resolve fetches the secret value for a Key Vault secret reference.

Both akvs:// and @Microsoft.KeyVault(SecretUri=...) formats are accepted.

Returns a *KeyVaultResolveError for all domain errors (invalid reference, secret not found, authentication failure). No silent fallbacks or hidden retries.

func (*KeyVaultResolver) ResolveEnvironment added in v1.23.14

func (r *KeyVaultResolver) ResolveEnvironment(ctx context.Context, env map[string]string) (map[string]string, error)

ResolveEnvironment resolves secret references within an environment variable map. It scans all values, resolves any that are secret references, and returns the complete map with secrets substituted. Non-reference values are passed through unchanged.

func (*KeyVaultResolver) ResolveMap added in v1.23.14

func (r *KeyVaultResolver) ResolveMap(ctx context.Context, refs map[string]string) (map[string]string, error)

ResolveMap resolves a map of key → secret references, returning a map of key → resolved secret values. Both akvs:// and @Microsoft.KeyVault formats are accepted. All entries are attempted; errors are collected and returned together via errors.Join so that callers see every failure at once.

Non-secret values are passed through unchanged, so callers can safely resolve a mixed map of plain values and secret references.

Keys are processed in sorted order so that error messages are deterministic.

type KeyVaultResolverOptions added in v1.23.14

type KeyVaultResolverOptions struct {
	// VaultSuffix overrides the default Key Vault DNS suffix.
	// Defaults to "vault.azure.net" (Azure public cloud).
	VaultSuffix string

	// ClientFactory overrides the default secret client constructor.
	// Useful for testing. When nil, the production [azsecrets.NewClient] is used.
	ClientFactory func(vaultURL string, credential azcore.TokenCredential) (SecretGetter, error)
}

KeyVaultResolverOptions configures a KeyVaultResolver.

type ListLocationsWithQuotaRequest

type ListLocationsWithQuotaRequest = v1.ListLocationsWithQuotaRequest

type ListLocationsWithQuotaResponse

type ListLocationsWithQuotaResponse = v1.ListLocationsWithQuotaResponse

type ListModelLocationsWithQuotaRequest

type ListModelLocationsWithQuotaRequest = v1.ListModelLocationsWithQuotaRequest

type ListModelLocationsWithQuotaResponse

type ListModelLocationsWithQuotaResponse = v1.ListModelLocationsWithQuotaResponse

type ListModelsRequest

type ListModelsRequest = v1.ListModelsRequest

type ListModelsResponse

type ListModelsResponse = v1.ListModelsResponse

type ListSubscriptionsRequest

type ListSubscriptionsRequest = v1.ListSubscriptionsRequest

type ListSubscriptionsResponse

type ListSubscriptionsResponse = v1.ListSubscriptionsResponse

type ListUsagesRequest

type ListUsagesRequest = v1.ListUsagesRequest

type ListUsagesResponse

type ListUsagesResponse = v1.ListUsagesResponse

type LocalError

type LocalError struct {
	// Message is the human-readable error message
	Message string
	// Code is an extension-defined machine-readable error code (lowercase snake_case, e.g. "missing_subscription_id").
	// It appears in telemetry as the last segment of ext.<category>.<code>.
	Code string
	// Category classifies the local error (for example: user, validation, dependency)
	Category LocalErrorCategory
	// CauseTypes contains extension-provided diagnostic labels from an
	// unexpected fallback chain. The host normalizes and hashes them for
	// telemetry; they do not change classification.
	CauseTypes []string
	// Suggestion contains optional user-facing remediation guidance.
	Suggestion string
	// Links contains optional reference links rendered alongside the suggestion.
	Links []errorhandler.ErrorLink
}

LocalError represents non-service extension errors, such as validation/config failures.

func (*LocalError) Error

func (e *LocalError) Error() string

Error implements the error interface.

type LocalErrorCategory

type LocalErrorCategory string

LocalErrorCategory is the canonical category type for extension local errors. Keep values aligned with telemetry ResultCode families in internal/cmd/errors.go.

const (
	LocalErrorCategoryValidation    LocalErrorCategory = "validation"
	LocalErrorCategoryAuth          LocalErrorCategory = "auth"
	LocalErrorCategoryDependency    LocalErrorCategory = "dependency"
	LocalErrorCategoryCompatibility LocalErrorCategory = "compatibility"
	LocalErrorCategoryUser          LocalErrorCategory = "user"
	LocalErrorCategoryInternal      LocalErrorCategory = "internal"
	LocalErrorCategoryLocal         LocalErrorCategory = "local"
)

func NormalizeLocalErrorCategory

func NormalizeLocalErrorCategory(category LocalErrorCategory) LocalErrorCategory

NormalizeLocalErrorCategory validates a typed category value, returning the canonical constant. Unknown values are collapsed to LocalErrorCategoryLocal.

func ParseLocalErrorCategory

func ParseLocalErrorCategory(category string) LocalErrorCategory

ParseLocalErrorCategory parses a raw category string (e.g. from proto deserialization) into its canonical LocalErrorCategory constant. Unknown values map to LocalErrorCategoryLocal.

type LocalErrorDetail

type LocalErrorDetail = v1.LocalErrorDetail

type Location

type Location = v1.Location

type LocationKind

type LocationKind = v1.LocationKind

type Logger added in v1.23.14

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

Logger provides component-scoped structured logging built on log/slog.

Each Logger carries a "component" attribute so log lines can be filtered or routed by subsystem. Additional context can be attached via Logger.With, Logger.WithComponent, or Logger.WithOperation.

Logger writes to stderr by default and never writes to stdout, so it does not interfere with command output or JSON-mode piping.

func NewLogger added in v1.23.14

func NewLogger(component string, opts ...LoggerOptions) *Logger

NewLogger creates a Logger scoped to the given component name.

If the AZD_DEBUG environment variable is set to a truthy value ("1", "true", "yes") and opts.Debug is false, debug logging is enabled automatically. This lets extension authors respect the framework's debug flag without extra plumbing.

When opts is omitted (zero value), the logger uses Info level with text format on stderr.

func (*Logger) Component added in v1.23.14

func (l *Logger) Component() string

Component returns the component name this logger was created with.

func (*Logger) Debug added in v1.23.14

func (l *Logger) Debug(msg string, args ...any)

Debug logs a message at debug level with optional key-value pairs.

func (*Logger) Error added in v1.23.14

func (l *Logger) Error(msg string, args ...any)

Error logs a message at error level with optional key-value pairs.

func (*Logger) Info added in v1.23.14

func (l *Logger) Info(msg string, args ...any)

Info logs a message at info level with optional key-value pairs.

func (*Logger) Slogger added in v1.23.14

func (l *Logger) Slogger() *slog.Logger

Slogger returns the underlying *slog.Logger for advanced use cases such as passing to libraries that accept a standard slog logger.

func (*Logger) Warn added in v1.23.14

func (l *Logger) Warn(msg string, args ...any)

Warn logs a message at warn level with optional key-value pairs.

func (*Logger) With added in v1.23.14

func (l *Logger) With(args ...any) *Logger

With returns a new Logger that includes the given key-value pairs in every subsequent log entry. Keys must be strings; values can be any type supported by slog.

Example:

l := logger.With("request_id", reqID)
l.Info("processing")   // includes component + request_id

func (*Logger) WithComponent added in v1.23.14

func (l *Logger) WithComponent(name string) *Logger

WithComponent returns a new Logger with a different component name. The original component is preserved as "parent_component".

func (*Logger) WithOperation added in v1.23.14

func (l *Logger) WithOperation(name string) *Logger

WithOperation returns a new Logger with an "operation" attribute.

type LoggerOptions added in v1.23.14

type LoggerOptions struct {
	// Debug enables debug-level logging. When false, messages below Info are
	// suppressed. If not set explicitly, [NewLogger] checks the AZD_DEBUG
	// environment variable.
	Debug bool
	// Structured selects JSON output when true, human-readable text when false.
	Structured bool
	// Writer overrides the output destination. Defaults to os.Stderr.
	Writer io.Writer
}

LoggerOptions configures SetupLogging and NewLogger.

type LookupTenantRequest

type LookupTenantRequest = v1.LookupTenantRequest

type LookupTenantResponse

type LookupTenantResponse = v1.LookupTenantResponse

type MCPSecurityPolicy

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

MCPSecurityPolicy validates URLs and file paths for MCP tool calls.

func DefaultMCPSecurityPolicy

func DefaultMCPSecurityPolicy() *MCPSecurityPolicy

DefaultMCPSecurityPolicy returns a policy with metadata endpoints blocked, private networks blocked, HTTPS required, and common sensitive headers redacted.

func NewMCPSecurityPolicy

func NewMCPSecurityPolicy() *MCPSecurityPolicy

NewMCPSecurityPolicy creates an empty security policy.

func (*MCPSecurityPolicy) BlockMetadataEndpoints

func (p *MCPSecurityPolicy) BlockMetadataEndpoints() *MCPSecurityPolicy

BlockMetadataEndpoints blocks cloud metadata service endpoints (169.254.169.254, fd00:ec2::254, metadata.google.internal, etc.)

func (*MCPSecurityPolicy) BlockPrivateNetworks

func (p *MCPSecurityPolicy) BlockPrivateNetworks() *MCPSecurityPolicy

BlockPrivateNetworks blocks RFC 1918 private networks, loopback, link-local, CGNAT (RFC 6598), deprecated IPv6 transition mechanisms (6to4, Teredo, NAT64), and IPv4-translated IPv6 addresses (RFC 2765).

func (*MCPSecurityPolicy) CheckPath

func (p *MCPSecurityPolicy) CheckPath(path string) error

CheckPath validates a file path against the security policy. Resolves symlinks and checks for directory traversal.

SECURITY NOTE (TOCTOU): This check is inherently susceptible to time-of-check-to-time-of-use races — the filesystem state may change between the validation here and the actual file access by the caller. Callers that operate in adversarial environments (e.g., shared file systems) should open the file immediately after validation and re-verify the resolved path via /proc/self/fd or fstat before processing.

func (*MCPSecurityPolicy) CheckURL

func (p *MCPSecurityPolicy) CheckURL(rawURL string) error

CheckURL validates a URL against the security policy. Returns an error describing the violation, or nil if allowed.

func (*MCPSecurityPolicy) IsHeaderBlocked

func (p *MCPSecurityPolicy) IsHeaderBlocked(header string) bool

IsHeaderBlocked checks if a header name is in the redacted set. Returns true if the header should be blocked.

func (*MCPSecurityPolicy) OnBlocked

func (p *MCPSecurityPolicy) OnBlocked(fn func(violation string)) *MCPSecurityPolicy

OnBlocked registers a callback invoked whenever a URL or path check fails. The callback receives a human-readable description of the violation. This is intended for audit logging; the callback must not block.

func (*MCPSecurityPolicy) RedactHeaders

func (p *MCPSecurityPolicy) RedactHeaders(headers ...string) *MCPSecurityPolicy

RedactHeaders marks headers that should be blocked/redacted in requests.

func (*MCPSecurityPolicy) RequireHTTPS

func (p *MCPSecurityPolicy) RequireHTTPS() *MCPSecurityPolicy

RequireHTTPS requires HTTPS for all URLs except localhost/127.0.0.1.

func (*MCPSecurityPolicy) ValidatePathsWithinBase

func (p *MCPSecurityPolicy) ValidatePathsWithinBase(basePaths ...string) *MCPSecurityPolicy

ValidatePathsWithinBase restricts file paths to be within the given base directories.

type MCPServerBuilder

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

MCPServerBuilder provides a fluent API for building MCP servers with middleware.

NOTE: This builder and the associated types (MCPToolHandler, MCPToolOptions, ToolArgs, MCP result helpers) depend on github.com/mark3labs/mcp-go. If alternative Go MCP libraries gain traction, these symbols are candidates for extraction into an azdext/mcpgo sub-package so the core SDK remains MCP-library-agnostic.

func NewMCPServerBuilder

func NewMCPServerBuilder(name, version string) *MCPServerBuilder

NewMCPServerBuilder creates a new builder for an MCP server.

func (*MCPServerBuilder) AddResources

func (b *MCPServerBuilder) AddResources(resources ...server.ServerResource) *MCPServerBuilder

AddResources registers static resources with the server.

func (*MCPServerBuilder) AddTool

func (b *MCPServerBuilder) AddTool(
	name string,
	handler MCPToolHandler,
	opts MCPToolOptions,
	params ...mcp.ToolOption,
) *MCPServerBuilder

AddTool registers a tool with the server. The handler receives parsed ToolArgs (not raw mcp.CallToolRequest). Rate limiting is automatically applied. For URL/path security validation, use MCPServerBuilder.SecurityPolicy within the handler. params defines the tool's input parameters as mcp.ToolOption items.

func (*MCPServerBuilder) Build

func (b *MCPServerBuilder) Build() *server.MCPServer

Build creates the configured MCP server ready to serve.

func (*MCPServerBuilder) SecurityPolicy

func (b *MCPServerBuilder) SecurityPolicy() *MCPSecurityPolicy

SecurityPolicy returns the configured security policy, or nil if none was set. Tool handlers should use this to validate URLs and file paths:

if policy := builder.SecurityPolicy(); policy != nil {
    if err := policy.CheckURL(url); err != nil {
        return MCPErrorResult("blocked: %v", err), nil
    }
}

func (*MCPServerBuilder) WithInstructions

func (b *MCPServerBuilder) WithInstructions(instructions string) *MCPServerBuilder

WithInstructions sets system instructions that guide AI clients on how to use the server's tools.

func (*MCPServerBuilder) WithPromptCapabilities

func (b *MCPServerBuilder) WithPromptCapabilities(listChanged bool) *MCPServerBuilder

WithPromptCapabilities enables prompt support on the server. listChanged controls whether the server notifies clients when the prompt list changes.

func (*MCPServerBuilder) WithRateLimit

func (b *MCPServerBuilder) WithRateLimit(burst int, refillRate float64) *MCPServerBuilder

WithRateLimit configures a token bucket rate limiter. burst is the maximum number of concurrent requests, refillRate is tokens per second.

func (*MCPServerBuilder) WithResourceCapabilities

func (b *MCPServerBuilder) WithResourceCapabilities(subscribe, listChanged bool) *MCPServerBuilder

WithResourceCapabilities enables resource support on the server. subscribe controls whether clients can subscribe to resource changes. listChanged controls whether the server notifies clients when the resource list changes.

func (*MCPServerBuilder) WithSecurityPolicy

func (b *MCPServerBuilder) WithSecurityPolicy(policy *MCPSecurityPolicy) *MCPServerBuilder

WithSecurityPolicy attaches a security policy for URL/path validation. The policy is available to tool handlers via MCPServerBuilder.SecurityPolicy. Tool handlers should call CheckURL/CheckPath on it for relevant parameters, since the builder cannot automatically determine which arguments are URLs or paths.

func (*MCPServerBuilder) WithServerOption

func (b *MCPServerBuilder) WithServerOption(opt server.ServerOption) *MCPServerBuilder

WithServerOption adds a raw mcp-go server option for capabilities not directly exposed by the builder.

type MCPToolHandler

type MCPToolHandler func(ctx context.Context, args ToolArgs) (*mcp.CallToolResult, error)

MCPToolHandler is the handler function signature for MCP tools. It receives parsed ToolArgs and the server's security policy (may be nil).

type MCPToolOptions

type MCPToolOptions struct {
	Description string
	Title       string // TitleAnnotation
	ReadOnly    bool   // ReadOnlyHint annotation
	Idempotent  bool   // IdempotentHint annotation
	Destructive bool   // DestructiveHint annotation
}

MCPToolOptions configures an MCP tool registration.

type ModelLocationQuota

type ModelLocationQuota = v1.ModelLocationQuota

type MultiSelectChoice

type MultiSelectChoice = v1.MultiSelectChoice

type MultiSelectOptions

type MultiSelectOptions = v1.MultiSelectOptions

type MultiSelectRequest

type MultiSelectRequest = v1.MultiSelectRequest

type MultiSelectResponse

type MultiSelectResponse = v1.MultiSelectResponse

type Output added in v1.23.14

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

Output provides formatted, format-aware output for extension commands. In default mode it writes human-readable text with ANSI color; in JSON mode it writes structured JSON objects to stdout and suppresses decorative output.

Output is safe for use from a single goroutine. If concurrent use is needed callers should synchronize externally.

func NewOutput added in v1.23.14

func NewOutput(opts OutputOptions) *Output

NewOutput creates an Output configured by opts. If opts.Writer or opts.ErrWriter are nil they default to os.Stdout / os.Stderr.

func (*Output) Error added in v1.23.14

func (o *Output) Error(format string, args ...any)

Error prints an error message prefixed with a red cross. Errors are always written to ErrWriter.

func (*Output) Info added in v1.23.14

func (o *Output) Info(format string, args ...any)

Info prints an informational message prefixed with an info symbol. In JSON mode the call is a no-op (use Output.JSON for structured data).

func (*Output) IsJSON added in v1.23.14

func (o *Output) IsJSON() bool

IsJSON returns true when the output format is JSON. Callers can use this to skip decorative output that is only relevant in human-readable mode.

func (*Output) JSON added in v1.23.14

func (o *Output) JSON(data any) error

JSON writes data as a pretty-printed JSON object to stdout. It is active in all output modes so callers can unconditionally emit structured payloads (in default mode the JSON is still human-readable).

func (*Output) Message added in v1.23.14

func (o *Output) Message(format string, args ...any)

Message prints an undecorated message to stdout. In JSON mode the call is a no-op.

func (*Output) Success added in v1.23.14

func (o *Output) Success(format string, args ...any)

Success prints a success message prefixed with a green check mark. In JSON mode the call is a no-op (use Output.JSON for structured data).

func (*Output) Table added in v1.23.14

func (o *Output) Table(headers []string, rows [][]string)

Table prints a formatted text table with headers and rows. In JSON mode the table is emitted as a JSON array of objects instead.

headers defines the column names. Each row is a slice of cell values with the same length as headers. Rows with fewer cells are padded with empty strings; extra cells are silently ignored.

func (*Output) Warning added in v1.23.14

func (o *Output) Warning(format string, args ...any)

Warning prints a warning message prefixed with a yellow exclamation mark. Warnings are written to ErrWriter in both default and JSON mode so they are visible even when stdout is piped through a JSON consumer.

type OutputFormat added in v1.23.14

type OutputFormat string

OutputFormat represents the output format for extension commands.

const (
	// OutputFormatDefault is human-readable text with optional color.
	OutputFormatDefault OutputFormat = "default"
	// OutputFormatJSON outputs structured JSON for machine consumption.
	OutputFormatJSON OutputFormat = "json"
)

func ParseOutputFormat added in v1.23.14

func ParseOutputFormat(s string) (OutputFormat, error)

ParseOutputFormat converts a string to an OutputFormat. Returns OutputFormatDefault for unrecognized values and a non-nil error.

type OutputOptions added in v1.23.14

type OutputOptions struct {
	// Format controls the output style. Defaults to OutputFormatDefault.
	Format OutputFormat
	// Writer is the destination for normal output. Defaults to os.Stdout.
	Writer io.Writer
	// ErrWriter is the destination for error/warning output. Defaults to os.Stderr.
	ErrWriter io.Writer
}

OutputOptions configures an Output instance.

type PageResponse

type PageResponse[T any] struct {
	// Value contains the items for this page.
	Value []T `json:"value"`

	// NextLink is the URL to the next page, or empty if this is the last page.
	NextLink string `json:"nextLink,omitempty"`
}

PageResponse is a single page returned by Pager.NextPage.

type Pager

type Pager[T any] struct {
	// contains filtered or unexported fields
}

Pager provides a generic, lazy iterator over paginated Azure REST API responses that use the standard { value, nextLink } pattern.

Usage:

pager := azdext.NewPager[MyItem](client, firstURL, nil)
for pager.More() {
    page, err := pager.NextPage(ctx)
    if err != nil { ... }
    for _, item := range page.Value {
        // process item
    }
}

func NewPager

func NewPager[T any](client HTTPDoer, firstURL string, opts *PagerOptions) *Pager[T]

NewPager creates a Pager that iterates over a paginated endpoint.

client may be a *ResilientClient or any type satisfying HTTPDoer. firstURL is the initial page URL.

func NewPagerFromHTTPClient

func NewPagerFromHTTPClient[T any](client *http.Client, firstURL string, opts *PagerOptions) *Pager[T]

NewPagerFromHTTPClient creates a Pager backed by a standard *http.Client. If client is nil, http.DefaultClient is used.

func (*Pager[T]) Collect

func (p *Pager[T]) Collect(ctx context.Context) ([]T, error)

Collect is a convenience method that fetches all remaining pages and returns all items in a single slice.

To prevent unbounded memory growth from runaway pagination, Collect enforces PagerOptions.MaxPages (defaults to [defaultMaxPages] when unset) and PagerOptions.MaxItems. When either limit is reached, iteration stops and the items collected so far are returned.

If NextPage returns both page data and an error (e.g. rejected nextLink), the page data is included in the returned slice before returning the error.

func (*Pager[T]) More

func (p *Pager[T]) More() bool

More reports whether there are more pages to fetch.

func (*Pager[T]) NextPage

func (p *Pager[T]) NextPage(ctx context.Context) (*PageResponse[T], error)

NextPage fetches the next page of results. Returns an error if the request fails, the response is not 2xx, or the body cannot be decoded.

Response bodies are bounded to [maxPageResponseSize] to prevent excessive memory consumption. nextLink URLs are validated to prevent SSRF attacks (must stay on the same host with HTTPS).

After the last page is consumed, [More] returns false.

func (*Pager[T]) Truncated

func (p *Pager[T]) Truncated() bool

Truncated reports whether the last [Collect] call stopped early because a collection bound (MaxPages or MaxItems) was hit.

type PagerOptions

type PagerOptions struct {
	// Method overrides the HTTP method used for page requests. Defaults to GET.
	Method string

	// MaxPages limits the maximum number of pages that [Pager.Collect] will
	// fetch. When set to a positive value, Collect stops after fetching that
	// many pages. A value of 0 means unlimited (no cap) for manual NextPage
	// iteration; Collect applies [defaultMaxPages] when this is 0.
	MaxPages int

	// MaxItems limits the maximum total items that [Pager.Collect] will
	// accumulate. When the collected items reach this count, Collect stops
	// and returns the items gathered so far (truncated to MaxItems).
	// A value of 0 means unlimited (no cap).
	MaxItems int
}

PagerOptions configures a Pager.

type PaginationError

type PaginationError struct {
	StatusCode int
	URL        string
	Body       string
}

PaginationError is returned when a page request receives a non-2xx response.

func (*PaginationError) Error

func (e *PaginationError) Error() string

type ParseGitHubUrlRequest

type ParseGitHubUrlRequest = v1.ParseGitHubUrlRequest

type ParseGitHubUrlResponse

type ParseGitHubUrlResponse = v1.ParseGitHubUrlResponse

type PredictedResource added in v1.26.0

type PredictedResource struct {
	// Type is the resource type including namespace (e.g. "Microsoft.Storage/storageAccounts").
	Type string `json:"type"`
	// APIVersion is the REST API version for the resource (e.g. "2023-01-01").
	APIVersion string `json:"apiVersion"`
	// Name is the resource name, may contain ARM template expressions.
	Name string `json:"name"`
	// Location is the deployment location for the resource.
	Location string `json:"location,omitempty"`
	// Kind is the resource kind (e.g. "StorageV2" for storage or "app,linux" for web apps).
	Kind string `json:"kind,omitempty"`
	// DependsOn lists symbolic names or resource IDs of resources that must be deployed first.
	DependsOn []string `json:"dependsOn,omitempty"`
	// Properties is the resource-specific configuration as raw JSON.
	Properties json.RawMessage `json:"properties,omitempty"`
	// SKU is the pricing tier / SKU block as raw JSON.
	SKU json.RawMessage `json:"sku,omitempty"`
	// Tags holds resource tags as raw JSON (may be a map or ARM expression).
	Tags json.RawMessage `json:"tags,omitempty"`
	// Scope is used for extension or cross-scope resources.
	Scope string `json:"scope,omitempty"`
}

PredictedResource represents a resource from the Bicep snapshot's predicted resources list. This mirrors the essential fields of the ARM template resource definition that extension authors commonly need for validation checks.

type PrepareValidationContextChunk added in v1.26.0

type PrepareValidationContextChunk = v1.PrepareValidationContextChunk

type PrepareValidationContextResponse added in v1.26.0

type PrepareValidationContextResponse = v1.PrepareValidationContextResponse

type ProcessEnvironment added in v1.23.14

type ProcessEnvironment struct {
	// PID is the current process ID.
	PID int
	// PPID is the parent process ID.
	PPID int
	// Executable is the current process executable path.
	Executable string
	// WorkingDir is the current working directory.
	WorkingDir string
	// OS is the operating system (runtime.GOOS).
	OS string
	// Arch is the CPU architecture (runtime.GOARCH).
	Arch string
	// NumCPU is the number of logical CPUs available.
	NumCPU int
}

ProcessEnvironment describes the process execution context for diagnostics.

func GetProcessEnvironment added in v1.23.14

func GetProcessEnvironment() ProcessEnvironment

GetProcessEnvironment collects process execution context useful for diagnostics, logging, and support information.

func (ProcessEnvironment) String added in v1.23.14

func (pe ProcessEnvironment) String() string

String returns a human-readable summary of the process environment.

type ProcessInfo added in v1.23.14

type ProcessInfo struct {
	// PID is the process identifier.
	PID int
	// Name is the process name (executable basename without extension).
	Name string
	// Executable is the full path to the process executable, if available.
	Executable string
	// Running is true if the process was found and appears to be alive.
	Running bool
}

ProcessInfo contains information about a running process.

func CurrentProcessInfo added in v1.23.14

func CurrentProcessInfo() ProcessInfo

CurrentProcessInfo returns ProcessInfo for the current process.

func FindProcessByName added in v1.23.14

func FindProcessByName(name string) []ProcessInfo

FindProcessByName searches for running processes with the given name. The search is case-insensitive and matches the executable basename (without file extension on Windows).

Platform behavior:

  • Linux: Scans /proc/*/comm.
  • macOS: Uses ps(1) to list processes.
  • Windows: Uses CreateToolhelp32Snapshot to enumerate processes.

Returns a slice of matching ProcessInfo. If no processes are found, returns an empty (non-nil) slice.

This function is best-effort: some processes may be inaccessible due to permissions.

func GetProcessInfo added in v1.23.14

func GetProcessInfo(pid int) ProcessInfo

GetProcessInfo retrieves information about the process with the given PID.

Platform behavior:

  • Linux: Reads /proc/<pid>/comm, /proc/<pid>/exe.
  • macOS: Uses ps(1) to query process info.
  • Windows: Uses QueryFullProcessImageName via Windows API.

Returns a ProcessInfo with Running=false if the process does not exist or cannot be queried (e.g., insufficient permissions).

func ParentProcessInfo added in v1.23.14

func ParentProcessInfo() ProcessInfo

ParentProcessInfo returns ProcessInfo for the parent of the current process.

Platform behavior:

  • All platforms: Uses os.Getppid() to obtain the parent PID, then delegates to GetProcessInfo.
  • On orphaned processes (parent PID = 1 on Unix), the returned info describes the init/launchd process.

type ProgressReporter

type ProgressReporter = grpcbroker.ProgressFunc

ProgressReporter is an alias for the broker's ProgressFunc

type ProjectConfig

type ProjectConfig = v1.ProjectConfig

type ProjectEventArgs

type ProjectEventArgs struct {
	Project *ProjectConfig
}

type ProjectEventHandler

type ProjectEventHandler func(ctx context.Context, args *ProjectEventArgs) error

type ProjectEventRegistration

type ProjectEventRegistration struct {
	EventName string
	Handler   ProjectEventHandler
}

ProjectEventRegistration describes a project-level event handler to register.

type ProjectHandlerStatus

type ProjectHandlerStatus = v1.ProjectHandlerStatus

type ProjectMetadata

type ProjectMetadata = v1.ProjectMetadata

type ProjectServiceClient

type ProjectServiceClient = v1.ProjectServiceClient

type ProjectServiceServer

type ProjectServiceServer = v1.ProjectServiceServer

type PromptAiDeploymentRequest

type PromptAiDeploymentRequest = v1.PromptAiDeploymentRequest

type PromptAiDeploymentResponse

type PromptAiDeploymentResponse = v1.PromptAiDeploymentResponse

type PromptAiLocationWithQuotaRequest

type PromptAiLocationWithQuotaRequest = v1.PromptAiLocationWithQuotaRequest

type PromptAiLocationWithQuotaResponse

type PromptAiLocationWithQuotaResponse = v1.PromptAiLocationWithQuotaResponse

type PromptAiModelLocationWithQuotaRequest

type PromptAiModelLocationWithQuotaRequest = v1.PromptAiModelLocationWithQuotaRequest

type PromptAiModelLocationWithQuotaResponse

type PromptAiModelLocationWithQuotaResponse = v1.PromptAiModelLocationWithQuotaResponse

type PromptAiModelRequest

type PromptAiModelRequest = v1.PromptAiModelRequest

type PromptAiModelResponse

type PromptAiModelResponse = v1.PromptAiModelResponse

type PromptLocationRequest

type PromptLocationRequest = v1.PromptLocationRequest

type PromptLocationResponse

type PromptLocationResponse = v1.PromptLocationResponse

type PromptOptions

type PromptOptions = v1.PromptOptions

type PromptRequest

type PromptRequest = v1.PromptRequest

type PromptResourceGroupOptions

type PromptResourceGroupOptions = v1.PromptResourceGroupOptions

type PromptResourceGroupRequest

type PromptResourceGroupRequest = v1.PromptResourceGroupRequest

type PromptResourceGroupResourceRequest

type PromptResourceGroupResourceRequest = v1.PromptResourceGroupResourceRequest

type PromptResourceGroupResourceResponse

type PromptResourceGroupResourceResponse = v1.PromptResourceGroupResourceResponse

type PromptResourceGroupResponse

type PromptResourceGroupResponse = v1.PromptResourceGroupResponse

type PromptResourceOptions

type PromptResourceOptions = v1.PromptResourceOptions

type PromptResourceSelectOptions

type PromptResourceSelectOptions = v1.PromptResourceSelectOptions

type PromptResponse

type PromptResponse = v1.PromptResponse

type PromptServiceClient

type PromptServiceClient = v1.PromptServiceClient

type PromptServiceServer

type PromptServiceServer = v1.PromptServiceServer

type PromptSubscriptionRequest

type PromptSubscriptionRequest = v1.PromptSubscriptionRequest

type PromptSubscriptionResourceRequest

type PromptSubscriptionResourceRequest = v1.PromptSubscriptionResourceRequest

type PromptSubscriptionResourceResponse

type PromptSubscriptionResourceResponse = v1.PromptSubscriptionResourceResponse

type PromptSubscriptionResponse

type PromptSubscriptionResponse = v1.PromptSubscriptionResponse

type Provider

type Provider interface {
	Initialize(ctx context.Context, serviceConfig *ServiceConfig) error
}

Provider is a generic interface that both ServiceTargetProvider and FrameworkServiceProvider implement

type ProviderFactory

type ProviderFactory[T any] func() T

ProviderFactory describes a function that creates a provider instance

type ProvisioningDeployRequest added in v1.24.2

type ProvisioningDeployRequest = v1.ProvisioningDeployRequest

type ProvisioningDeployResponse added in v1.24.2

type ProvisioningDeployResponse = v1.ProvisioningDeployResponse

type ProvisioningDeployResult added in v1.24.2

type ProvisioningDeployResult = v1.ProvisioningDeployResult

type ProvisioningDeployment added in v1.24.2

type ProvisioningDeployment = v1.ProvisioningDeployment

type ProvisioningDeploymentPreview added in v1.24.2

type ProvisioningDeploymentPreview = v1.ProvisioningDeploymentPreview

type ProvisioningDeploymentPreviewChange added in v1.27.0

type ProvisioningDeploymentPreviewChange = v1.ProvisioningDeploymentPreviewChange

type ProvisioningDestroyOptions added in v1.24.2

type ProvisioningDestroyOptions = v1.ProvisioningDestroyOptions

type ProvisioningDestroyRequest added in v1.24.2

type ProvisioningDestroyRequest = v1.ProvisioningDestroyRequest

type ProvisioningDestroyResponse added in v1.24.2

type ProvisioningDestroyResponse = v1.ProvisioningDestroyResponse

type ProvisioningDestroyResult added in v1.24.2

type ProvisioningDestroyResult = v1.ProvisioningDestroyResult

type ProvisioningEnsureEnvRequest added in v1.24.2

type ProvisioningEnsureEnvRequest = v1.ProvisioningEnsureEnvRequest

type ProvisioningEnsureEnvResponse added in v1.24.2

type ProvisioningEnsureEnvResponse = v1.ProvisioningEnsureEnvResponse

type ProvisioningEnvelope added in v1.24.2

type ProvisioningEnvelope struct{}

ProvisioningEnvelope provides message operations for ProvisioningMessage. It implements the grpcbroker.MessageEnvelope interface.

func NewProvisioningEnvelope added in v1.24.2

func NewProvisioningEnvelope() *ProvisioningEnvelope

NewProvisioningEnvelope creates a new ProvisioningEnvelope instance.

func (*ProvisioningEnvelope) CreateProgressMessage added in v1.24.2

func (ops *ProvisioningEnvelope) CreateProgressMessage(
	requestId string,
	message string,
) *ProvisioningMessage

CreateProgressMessage creates a new progress message envelope with the given text. This is used by server-side handlers to send progress updates back to clients.

func (*ProvisioningEnvelope) GetError added in v1.24.2

func (ops *ProvisioningEnvelope) GetError(msg *ProvisioningMessage) error

GetError returns the error from the message as a Go error type. It returns a typed error based on the ErrorOrigin that preserves structured information for telemetry.

func (*ProvisioningEnvelope) GetInnerMessage added in v1.24.2

func (ops *ProvisioningEnvelope) GetInnerMessage(msg *ProvisioningMessage) any

GetInnerMessage returns the inner message from the oneof field.

func (*ProvisioningEnvelope) GetProgressMessage added in v1.24.2

func (ops *ProvisioningEnvelope) GetProgressMessage(msg *ProvisioningMessage) string

GetProgressMessage extracts the progress message text from a progress message. Returns empty string if the message is not a progress message.

func (*ProvisioningEnvelope) GetRequestId added in v1.24.2

func (ops *ProvisioningEnvelope) GetRequestId(ctx context.Context, msg *ProvisioningMessage) string

GetRequestId returns the request ID from the message.

func (*ProvisioningEnvelope) IsProgressMessage added in v1.24.2

func (ops *ProvisioningEnvelope) IsProgressMessage(msg *ProvisioningMessage) bool

IsProgressMessage returns true if the message contains a progress message.

func (*ProvisioningEnvelope) SetError added in v1.24.2

func (ops *ProvisioningEnvelope) SetError(msg *ProvisioningMessage, err error)

SetError sets an error on the message. It detects the error type and populates the appropriate source details.

func (*ProvisioningEnvelope) SetRequestId added in v1.24.2

func (ops *ProvisioningEnvelope) SetRequestId(ctx context.Context, msg *ProvisioningMessage, id string)

SetRequestId sets the request ID on the message.

type ProvisioningInitializeRequest added in v1.24.2

type ProvisioningInitializeRequest = v1.ProvisioningInitializeRequest

type ProvisioningInitializeResponse added in v1.24.2

type ProvisioningInitializeResponse = v1.ProvisioningInitializeResponse

type ProvisioningInputParameter added in v1.24.2

type ProvisioningInputParameter = v1.ProvisioningInputParameter

type ProvisioningManager added in v1.24.2

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

ProvisioningManager manages provisioning provider instances using a two-map pattern (factories + instances). Unlike ServiceTargetManager which delegates to ComponentManager[T], ProvisioningManager uses direct maps because ProvisioningProvider.Initialize() has a different signature (projectPath + ProvisioningOptions) than ComponentManager's Provider interface (ServiceConfig). The routing key is provider name (from ProvisioningOptions.Provider) rather than service config host.

func NewProvisioningManager added in v1.24.2

func NewProvisioningManager(
	extensionId string,
	client *AzdClient,
	brokerLogger *log.Logger,
) *ProvisioningManager

NewProvisioningManager creates a new ProvisioningManager for an AzdClient.

func (*ProvisioningManager) Close added in v1.24.2

func (m *ProvisioningManager) Close() error

Close terminates the underlying gRPC stream if it's been initialized. This method is thread-safe for concurrent access.

func (*ProvisioningManager) Ready added in v1.24.2

func (m *ProvisioningManager) Ready(ctx context.Context) error

Ready blocks until the message broker starts receiving messages or the context is cancelled.

func (*ProvisioningManager) Receive added in v1.24.2

func (m *ProvisioningManager) Receive(ctx context.Context) error

Receive starts the broker's message dispatcher and blocks until the stream completes.

func (*ProvisioningManager) Register added in v1.24.2

func (m *ProvisioningManager) Register(
	ctx context.Context,
	factory ProvisioningProviderFactory,
	providerName string,
) error

Register registers a provisioning provider factory with the server, waits for the response, then starts background handling of provisioning requests. Multiple providers can be registered per extension; calling Register with the same name twice returns an error.

type ProvisioningMessage added in v1.24.2

type ProvisioningMessage = v1.ProvisioningMessage

type ProvisioningMessage_DeployRequest added in v1.24.2

type ProvisioningMessage_DeployRequest = v1.ProvisioningMessage_DeployRequest

type ProvisioningMessage_DeployResponse added in v1.24.2

type ProvisioningMessage_DeployResponse = v1.ProvisioningMessage_DeployResponse

type ProvisioningMessage_DestroyRequest added in v1.24.2

type ProvisioningMessage_DestroyRequest = v1.ProvisioningMessage_DestroyRequest

type ProvisioningMessage_DestroyResponse added in v1.24.2

type ProvisioningMessage_DestroyResponse = v1.ProvisioningMessage_DestroyResponse

type ProvisioningMessage_EnsureEnvRequest added in v1.24.2

type ProvisioningMessage_EnsureEnvRequest = v1.ProvisioningMessage_EnsureEnvRequest

type ProvisioningMessage_EnsureEnvResponse added in v1.24.2

type ProvisioningMessage_EnsureEnvResponse = v1.ProvisioningMessage_EnsureEnvResponse

type ProvisioningMessage_InitializeRequest added in v1.24.2

type ProvisioningMessage_InitializeRequest = v1.ProvisioningMessage_InitializeRequest

type ProvisioningMessage_InitializeResponse added in v1.24.2

type ProvisioningMessage_InitializeResponse = v1.ProvisioningMessage_InitializeResponse

type ProvisioningMessage_ParametersRequest added in v1.24.2

type ProvisioningMessage_ParametersRequest = v1.ProvisioningMessage_ParametersRequest

type ProvisioningMessage_ParametersResponse added in v1.24.2

type ProvisioningMessage_ParametersResponse = v1.ProvisioningMessage_ParametersResponse

type ProvisioningMessage_PlannedOutputsRequest added in v1.24.2

type ProvisioningMessage_PlannedOutputsRequest = v1.ProvisioningMessage_PlannedOutputsRequest

type ProvisioningMessage_PlannedOutputsResponse added in v1.24.2

type ProvisioningMessage_PlannedOutputsResponse = v1.ProvisioningMessage_PlannedOutputsResponse

type ProvisioningMessage_PreviewRequest added in v1.24.2

type ProvisioningMessage_PreviewRequest = v1.ProvisioningMessage_PreviewRequest

type ProvisioningMessage_PreviewResponse added in v1.24.2

type ProvisioningMessage_PreviewResponse = v1.ProvisioningMessage_PreviewResponse

type ProvisioningMessage_ProgressMessage added in v1.24.2

type ProvisioningMessage_ProgressMessage = v1.ProvisioningMessage_ProgressMessage

type ProvisioningMessage_RegisterProvisioningProviderRequest added in v1.24.2

type ProvisioningMessage_RegisterProvisioningProviderRequest = v1.ProvisioningMessage_RegisterProvisioningProviderRequest

type ProvisioningMessage_RegisterProvisioningProviderResponse added in v1.24.2

type ProvisioningMessage_RegisterProvisioningProviderResponse = v1.ProvisioningMessage_RegisterProvisioningProviderResponse

type ProvisioningMessage_StateRequest added in v1.24.2

type ProvisioningMessage_StateRequest = v1.ProvisioningMessage_StateRequest

type ProvisioningMessage_StateResponse added in v1.24.2

type ProvisioningMessage_StateResponse = v1.ProvisioningMessage_StateResponse

type ProvisioningOptions added in v1.24.2

type ProvisioningOptions = v1.ProvisioningOptions

type ProvisioningOutputParameter added in v1.24.2

type ProvisioningOutputParameter = v1.ProvisioningOutputParameter

type ProvisioningParameter added in v1.24.2

type ProvisioningParameter = v1.ProvisioningParameter

type ProvisioningParametersRequest added in v1.24.2

type ProvisioningParametersRequest = v1.ProvisioningParametersRequest

type ProvisioningParametersResponse added in v1.24.2

type ProvisioningParametersResponse = v1.ProvisioningParametersResponse

type ProvisioningPlannedOutput added in v1.24.2

type ProvisioningPlannedOutput = v1.ProvisioningPlannedOutput

type ProvisioningPlannedOutputsRequest added in v1.24.2

type ProvisioningPlannedOutputsRequest = v1.ProvisioningPlannedOutputsRequest

type ProvisioningPlannedOutputsResponse added in v1.24.2

type ProvisioningPlannedOutputsResponse = v1.ProvisioningPlannedOutputsResponse

type ProvisioningPreviewRequest added in v1.24.2

type ProvisioningPreviewRequest = v1.ProvisioningPreviewRequest

type ProvisioningPreviewResponse added in v1.24.2

type ProvisioningPreviewResponse = v1.ProvisioningPreviewResponse

type ProvisioningPreviewResult added in v1.24.2

type ProvisioningPreviewResult = v1.ProvisioningPreviewResult

type ProvisioningProgressMessage added in v1.24.2

type ProvisioningProgressMessage = v1.ProvisioningProgressMessage

type ProvisioningProvider added in v1.24.2

type ProvisioningProvider interface {
	Initialize(ctx context.Context, projectPath string, options *ProvisioningOptions) error
	State(ctx context.Context, options *ProvisioningStateOptions) (*ProvisioningStateResult, error)
	Deploy(ctx context.Context, progress grpcbroker.ProgressFunc) (*ProvisioningDeployResult, error)
	Preview(ctx context.Context, progress grpcbroker.ProgressFunc) (*ProvisioningPreviewResult, error)
	Destroy(
		ctx context.Context,
		options *ProvisioningDestroyOptions,
		progress grpcbroker.ProgressFunc,
	) (*ProvisioningDestroyResult, error)
	EnsureEnv(ctx context.Context) error
	Parameters(ctx context.Context) ([]*ProvisioningParameter, error)
	PlannedOutputs(ctx context.Context) ([]*ProvisioningPlannedOutput, error)
}

ProvisioningProvider defines the interface for provisioning logic on the extension side.

Note: Deploy, Preview, and Destroy include a progress callback parameter that the core provisioning.Provider interface does not have. This is intentional — extension providers use in-band progress streaming via the gRPC broker, while core providers report progress through separate channels managed by the provisioning Manager.

type ProvisioningProviderFactory added in v1.24.2

type ProvisioningProviderFactory func() ProvisioningProvider

ProvisioningProviderFactory creates a new ProvisioningProvider instance.

type ProvisioningProviderRegistration added in v1.24.2

type ProvisioningProviderRegistration struct {
	Name    string
	Factory ProvisioningProviderFactory
}

ProvisioningProviderRegistration describes a provisioning provider to register with azd core.

type ProvisioningResource added in v1.24.2

type ProvisioningResource = v1.ProvisioningResource

type ProvisioningServiceClient added in v1.24.2

type ProvisioningServiceClient = v1.ProvisioningServiceClient

func NewProvisioningServiceClient added in v1.24.2

func NewProvisioningServiceClient(cc grpc.ClientConnInterface) ProvisioningServiceClient

type ProvisioningServiceServer added in v1.24.2

type ProvisioningServiceServer = v1.ProvisioningServiceServer

type ProvisioningService_StreamClient added in v1.24.2

type ProvisioningService_StreamClient = v1.ProvisioningService_StreamClient

type ProvisioningService_StreamServer added in v1.24.2

type ProvisioningService_StreamServer = v1.ProvisioningService_StreamServer

type ProvisioningSkippedReason added in v1.24.2

type ProvisioningSkippedReason = v1.ProvisioningSkippedReason

type ProvisioningState added in v1.24.2

type ProvisioningState = v1.ProvisioningState

type ProvisioningStateOptions added in v1.24.2

type ProvisioningStateOptions = v1.ProvisioningStateOptions

type ProvisioningStateRequest added in v1.24.2

type ProvisioningStateRequest = v1.ProvisioningStateRequest

type ProvisioningStateResponse added in v1.24.2

type ProvisioningStateResponse = v1.ProvisioningStateResponse

type ProvisioningStateResult added in v1.24.2

type ProvisioningStateResult = v1.ProvisioningStateResult

type PublishOptions

type PublishOptions = v1.PublishOptions

type QuotaCheckOptions

type QuotaCheckOptions = v1.QuotaCheckOptions

type QuotaRequirement

type QuotaRequirement = v1.QuotaRequirement

type ReadyRequest

type ReadyRequest = v1.ReadyRequest

type ReadyResponse

type ReadyResponse = v1.ReadyResponse

type RegisterFrameworkServiceRequest

type RegisterFrameworkServiceRequest = v1.RegisterFrameworkServiceRequest

type RegisterFrameworkServiceResponse

type RegisterFrameworkServiceResponse = v1.RegisterFrameworkServiceResponse

type RegisterProvisioningProviderRequest added in v1.24.2

type RegisterProvisioningProviderRequest = v1.RegisterProvisioningProviderRequest

type RegisterProvisioningProviderResponse added in v1.24.2

type RegisterProvisioningProviderResponse = v1.RegisterProvisioningProviderResponse

type RegisterServiceTargetRequest

type RegisterServiceTargetRequest = v1.RegisterServiceTargetRequest

type RegisterServiceTargetResponse

type RegisterServiceTargetResponse = v1.RegisterServiceTargetResponse

type RegisterValidationCheckRequest added in v1.26.0

type RegisterValidationCheckRequest = v1.RegisterValidationCheckRequest

type RegisterValidationCheckResponse added in v1.26.0

type RegisterValidationCheckResponse = v1.RegisterValidationCheckResponse

type ReportErrorRequest

type ReportErrorRequest = v1.ReportErrorRequest

type ReportErrorResponse

type ReportErrorResponse = v1.ReportErrorResponse

type RequiredVersions

type RequiredVersions = v1.RequiredVersions

type ResilientClient

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

ResilientClient is an HTTP client with built-in retry, exponential backoff, timeout, and optional bearer-token injection. It is designed for extension authors who need to call Azure REST APIs directly.

Usage:

rc := azdext.NewResilientClient(tokenProvider, nil)
resp, err := rc.Do(ctx, http.MethodGet, "https://management.azure.com/...", nil)

func NewResilientClient

func NewResilientClient(tokenProvider azcore.TokenCredential, opts *ResilientClientOptions) *ResilientClient

NewResilientClient creates a ResilientClient.

tokenProvider may be nil if the caller handles Authorization headers manually. When non-nil, the client automatically injects a Bearer token using scopes resolved from the request URL via the ScopeDetector.

func (*ResilientClient) Do

func (rc *ResilientClient) Do(ctx context.Context, method, url string, body io.Reader) (*http.Response, error)

Do executes an HTTP request with retry logic and optional bearer-token injection.

body may be nil for requests without a body (GET, DELETE). When body is non-nil and retries are enabled (MaxRetries > 0), the body must implement io.ReadSeeker so it can be re-read on each attempt. If a retry is needed and the body does not implement io.ReadSeeker, Do returns an error.

type ResilientClientOptions

type ResilientClientOptions struct {
	// MaxRetries is the maximum number of retry attempts for transient failures.
	// Defaults to 3.
	MaxRetries int

	// InitialDelay is the base delay before the first retry. Subsequent retries
	// use exponential backoff (delay * 2^attempt) capped at MaxDelay.
	// Defaults to 500ms.
	InitialDelay time.Duration

	// MaxDelay caps the computed backoff delay. Defaults to 30s.
	MaxDelay time.Duration

	// Timeout is the per-request timeout.
	// A value of zero or less uses the default of 30s.
	Timeout time.Duration

	// Transport overrides the default HTTP transport. Useful for testing.
	Transport http.RoundTripper

	// ScopeDetector overrides the default scope detector used for automatic
	// scope resolution. When nil, a default detector is created.
	ScopeDetector *ScopeDetector
}

ResilientClientOptions configures a ResilientClient.

type ResolveModelDeploymentsRequest

type ResolveModelDeploymentsRequest = v1.ResolveModelDeploymentsRequest

type ResolveModelDeploymentsResponse

type ResolveModelDeploymentsResponse = v1.ResolveModelDeploymentsResponse

type ResolveReason added in v1.23.14

type ResolveReason int

ResolveReason classifies the cause of a KeyVaultResolveError.

const (
	// ResolveReasonInvalidReference indicates the secret reference is malformed.
	ResolveReasonInvalidReference ResolveReason = iota

	// ResolveReasonClientCreation indicates failure to create the Key Vault client.
	ResolveReasonClientCreation

	// ResolveReasonNotFound indicates the secret does not exist.
	ResolveReasonNotFound

	// ResolveReasonAccessDenied indicates an authentication or authorization failure.
	ResolveReasonAccessDenied

	// ResolveReasonServiceError indicates an unexpected Key Vault service error.
	ResolveReasonServiceError
)

func (ResolveReason) String added in v1.23.14

func (r ResolveReason) String() string

String returns a human-readable label for the reason.

type Resource

type Resource = v1.Resource

type ResourceExtended

type ResourceExtended = v1.ResourceExtended

type ResourceGroup

type ResourceGroup = v1.ResourceGroup

type RetryableHTTPError

type RetryableHTTPError struct {
	StatusCode int
	Status     string
}

RetryableHTTPError represents a retryable HTTP failure.

func (*RetryableHTTPError) Error

func (e *RetryableHTTPError) Error() string

type RunOption

type RunOption func(*runConfig)

RunOption configures the behavior of Run.

func WithPreExecute

func WithPreExecute(fn func(ctx context.Context, cmd *cobra.Command) error) RunOption

WithPreExecute registers a hook that runs after context creation but before command execution. If the hook returns a non-nil error, Run prints it and exits. This is useful for extensions that need special setup such as dual-mode host detection or working-directory changes.

type RunWorkflowRequest

type RunWorkflowRequest = v1.RunWorkflowRequest

type SSRFError added in v1.23.14

type SSRFError struct {
	// URL is the rejected URL (or a sanitized representation).
	URL string

	// Reason is a machine-readable tag for the violation type.
	// Values: "blocked_host", "blocked_ip", "private_network",
	// "metadata_endpoint", "dns_failure", "https_required",
	// "invalid_url", "scheme_blocked".
	Reason string

	// Detail is a human-readable explanation.
	Detail string
}

SSRFError describes why a URL was rejected by the SSRFGuard.

func (*SSRFError) Error added in v1.23.14

func (e *SSRFError) Error() string

type SSRFGuard added in v1.23.14

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

SSRFGuard validates URLs against Server-Side Request Forgery (SSRF) attack patterns. It provides standalone SSRF protection for extension authors who need URL validation outside of MCP contexts.

SSRFGuard uses a fluent builder pattern for configuration:

guard := azdext.NewSSRFGuard().
    BlockMetadataEndpoints().
    BlockPrivateNetworks().
    RequireHTTPS()

if err := guard.Check("http://169.254.169.254/metadata"); err != nil {
    // blocked: cloud metadata endpoint
}

Use DefaultSSRFGuard for a preset configuration that blocks metadata endpoints, private networks, and requires HTTPS.

SSRFGuard is safe for concurrent use from multiple goroutines.

func DefaultSSRFGuard added in v1.23.14

func DefaultSSRFGuard() *SSRFGuard

DefaultSSRFGuard returns a guard preconfigured with:

  • Cloud metadata endpoint blocking (AWS, Azure, GCP, Alibaba)
  • Private network blocking (RFC 1918, loopback, link-local, CGNAT, IPv6 ULA, 6to4, Teredo, NAT64)
  • HTTPS enforcement (except localhost)

This is the recommended starting point for extension authors.

func NewSSRFGuard added in v1.23.14

func NewSSRFGuard() *SSRFGuard

NewSSRFGuard creates an empty SSRF guard with no active protections. Use the builder methods to configure protections, or use DefaultSSRFGuard for a preset secure configuration.

func (*SSRFGuard) AllowHost added in v1.23.14

func (g *SSRFGuard) AllowHost(hosts ...string) *SSRFGuard

AllowHost adds hosts to an explicit allowlist. Allowed hosts bypass all IP-based and metadata checks. Host names are compared case-insensitively.

Use this sparingly — over-broad allowlists weaken SSRF protection. Prefer allowing specific, known-good endpoints rather than wildcards.

func (*SSRFGuard) BlockMetadataEndpoints added in v1.23.14

func (g *SSRFGuard) BlockMetadataEndpoints() *SSRFGuard

BlockMetadataEndpoints blocks well-known cloud metadata service endpoints:

  • 169.254.169.254 (AWS, Azure, most cloud providers)
  • fd00:ec2::254 (AWS EC2 IPv6 metadata)
  • metadata.google.internal (GCP)
  • 100.100.100.200 (Alibaba Cloud)

func (*SSRFGuard) BlockPrivateNetworks added in v1.23.14

func (g *SSRFGuard) BlockPrivateNetworks() *SSRFGuard

BlockPrivateNetworks blocks RFC 1918 private networks, loopback, link-local, CGNAT (RFC 6598), and IPv6 transition mechanisms that can embed private IPv4 addresses (6to4, Teredo, NAT64, IPv4-compatible, IPv4-translated).

func (*SSRFGuard) Check added in v1.23.14

func (g *SSRFGuard) Check(rawURL string) error

Check validates a URL against the guard's SSRF policy.

Validation order:

  1. Parse the URL and reject non-HTTP(S) schemes.
  2. If HTTPS is required, reject plain HTTP to non-localhost hosts.
  3. Skip further checks if the host is explicitly allowed via [AllowHost].
  4. Skip further checks for localhost/loopback hosts (local development).
  5. Reject hosts matching the metadata endpoint blocklist.
  6. For IP-literal hosts, check directly against blocked CIDRs.
  7. For hostname hosts, resolve DNS (fail-closed on lookup failure) and check all resolved IPs against blocked CIDRs.

For IPv6 addresses, embedded IPv4 (IPv4-compatible, IPv4-mapped, IPv4-translated per RFC 2765) is extracted and re-checked against blocked CIDRs.

Returns nil if the URL is allowed, or a *SSRFError describing the violation.

func (*SSRFGuard) OnBlocked added in v1.23.14

func (g *SSRFGuard) OnBlocked(fn func(reason, detail string)) *SSRFGuard

OnBlocked registers a callback invoked whenever a URL is blocked. This enables security audit logging without coupling the guard to a logging framework. The callback receives the machine-readable reason tag and a human-readable detail string. It must be safe for concurrent invocation.

func (*SSRFGuard) RequireHTTPS added in v1.23.14

func (g *SSRFGuard) RequireHTTPS() *SSRFGuard

RequireHTTPS requires HTTPS for all URLs except localhost and loopback addresses. HTTP to localhost/127.0.0.1/[::1] is always permitted for local development.

type ScopeDetector

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

ScopeDetector maps Azure resource endpoint URLs to the OAuth 2.0 scopes required for token acquisition. Extensions use this to automatically determine the correct scope for a given API call without hard-coding values.

Usage:

sd := azdext.NewScopeDetector(nil)
scopes, err := sd.ScopesForURL("https://management.azure.com/subscriptions/...")
// scopes = []string{"https://management.azure.com/.default"}

func NewScopeDetector

func NewScopeDetector(opts *ScopeDetectorOptions) *ScopeDetector

NewScopeDetector creates a ScopeDetector with the built-in Azure endpoint mappings. Additional custom rules can be supplied via opts. Custom rules are evaluated before defaults, so they can override built-in mappings.

func (*ScopeDetector) ScopesForURL

func (sd *ScopeDetector) ScopesForURL(rawURL string) ([]string, error)

ScopesForURL returns the OAuth 2.0 scopes required to access the given URL. Returns an error if the URL is malformed or no matching scope is found.

type ScopeDetectorError

type ScopeDetectorError struct {
	URL    string
	Reason string
}

ScopeDetectorError is returned when ScopeDetector.ScopesForURL cannot resolve a scope for the given URL.

func (*ScopeDetectorError) Error

func (e *ScopeDetectorError) Error() string

type ScopeDetectorOptions

type ScopeDetectorOptions struct {
	// CustomRules appends additional host → scope mappings.
	// Each entry maps a host suffix (e.g. ".openai.azure.com") to a scope
	// (e.g. "https://cognitiveservices.azure.com/.default").
	// Suffixes should start with a dot for subdomain matching; entries
	// without a leading dot are treated as exact host matches to prevent
	// unintended partial-host matching (e.g. "azure.com" matching "fakeazure.com").
	// Empty keys are ignored.
	CustomRules map[string]string
}

ScopeDetectorOptions allows adding custom endpoint-to-scope mappings.

type SecretGetter added in v1.23.14

type SecretGetter interface {
	GetSecret(
		ctx context.Context,
		name string,
		version string,
		options *azsecrets.GetSecretOptions,
	) (azsecrets.GetSecretResponse, error)
}

SecretGetter abstracts the Azure SDK secret client's GetSecret method. The azsecrets.Client type satisfies this interface.

type SecretReference added in v1.23.14

type SecretReference struct {
	// SubscriptionID is the Azure subscription containing the Key Vault.
	// Present for akvs:// references; empty for @Microsoft.KeyVault references.
	SubscriptionID string

	// VaultName is the Key Vault name (not the full URL).
	VaultName string

	// SecretName is the name of the secret within the vault.
	SecretName string

	// SecretVersion is the specific secret version to retrieve.
	// Empty string means latest version.
	SecretVersion string

	// VaultURL is the full vault URL (e.g., "https://my-vault.vault.azure.net").
	// Present for @Microsoft.KeyVault references; empty for akvs:// references
	// (where the URL is constructed from VaultName + VaultSuffix).
	VaultURL string
}

SecretReference represents a parsed Key Vault secret reference. It may be populated from either the akvs:// or @Microsoft.KeyVault format.

func ParseSecretReference added in v1.23.14

func ParseSecretReference(ref string) (*SecretReference, error)

ParseSecretReference parses a Key Vault secret reference into its components.

Three formats are supported:

akvs://<subscription-id>/<vault-name>/<secret-name>
@Microsoft.KeyVault(SecretUri=https://<vault>.vault.azure.net/secrets/<secret>[/<version>])
@Microsoft.KeyVault(VaultName=<vault>;SecretName=<secret>[;SecretVersion=<version>])

Leading/trailing whitespace and surrounding single or double quotes are stripped before parsing.

For the akvs:// format, the vault name is validated against Azure Key Vault naming rules (3–24 characters, starts with letter, alphanumeric and hyphens only, does not end with a hyphen).

For the VaultName/SecretName format, SubscriptionID and VaultURL will be empty in the returned SecretReference; the caller (typically KeyVaultResolver.Resolve) derives the vault URL from VaultName and the configured vault suffix.

type SelectChoice

type SelectChoice = v1.SelectChoice

type SelectEnvironmentRequest

type SelectEnvironmentRequest = v1.SelectEnvironmentRequest

type SelectOptions

type SelectOptions = v1.SelectOptions

type SelectRequest

type SelectRequest = v1.SelectRequest

type SelectResponse

type SelectResponse = v1.SelectResponse

type ServiceBuildResult

type ServiceBuildResult = v1.ServiceBuildResult

type ServiceConfig

type ServiceConfig = v1.ServiceConfig

type ServiceContext

type ServiceContext = v1.ServiceContext

type ServiceDeployResult

type ServiceDeployResult = v1.ServiceDeployResult

type ServiceError

type ServiceError struct {
	// Message is the human-readable error message
	Message string
	// ErrorCode is the error code from the service (e.g., "Conflict", "NotFound")
	ErrorCode string
	// StatusCode is the HTTP status code (e.g., 409, 404, 500)
	StatusCode int
	// ServiceName is the service host/name for telemetry (e.g., "ai.azure.com")
	ServiceName string
	// Suggestion contains optional user-facing remediation guidance.
	Suggestion string
	// Links contains optional reference links rendered alongside the suggestion.
	Links []errorhandler.ErrorLink
}

ServiceError represents an HTTP/gRPC service error from an extension. It preserves structured error information for telemetry and error handling.

func (*ServiceError) Error

func (e *ServiceError) Error() string

Error implements the error interface.

type ServiceErrorDetail

type ServiceErrorDetail = v1.ServiceErrorDetail

func ServiceErrorDetailFromStatus added in v1.34.0

func ServiceErrorDetailFromStatus(st *status.Status) *ServiceErrorDetail

ServiceErrorDetailFromStatus extracts a service error detail from a gRPC status.

type ServiceEventArgs

type ServiceEventArgs struct {
	Project        *ProjectConfig
	Service        *ServiceConfig
	ServiceContext *ServiceContext
}

type ServiceEventHandler

type ServiceEventHandler func(ctx context.Context, args *ServiceEventArgs) error

type ServiceEventOptions

type ServiceEventOptions struct {
	Host     string
	Language string
}

type ServiceEventRegistration

type ServiceEventRegistration struct {
	EventName string
	Handler   ServiceEventHandler
	Options   *ServiceEventOptions
}

ServiceEventRegistration describes a service-level event handler to register.

type ServiceHandlerStatus

type ServiceHandlerStatus = v1.ServiceHandlerStatus

type ServicePackageResult

type ServicePackageResult = v1.ServicePackageResult

type ServicePublishResult

type ServicePublishResult = v1.ServicePublishResult

type ServiceRestoreResult

type ServiceRestoreResult = v1.ServiceRestoreResult

type ServiceTargetDeployRequest

type ServiceTargetDeployRequest = v1.ServiceTargetDeployRequest

type ServiceTargetDeployResponse

type ServiceTargetDeployResponse = v1.ServiceTargetDeployResponse

type ServiceTargetEndpointsRequest

type ServiceTargetEndpointsRequest = v1.ServiceTargetEndpointsRequest

type ServiceTargetEndpointsResponse

type ServiceTargetEndpointsResponse = v1.ServiceTargetEndpointsResponse

type ServiceTargetEnvelope

type ServiceTargetEnvelope struct{}

ServiceTargetEnvelope provides message operations for ServiceTargetMessage It implements the grpcbroker.MessageOperations interface

func NewServiceTargetEnvelope

func NewServiceTargetEnvelope() *ServiceTargetEnvelope

NewServiceTargetEnvelope creates a new ServiceTargetMessageOps instance

func (*ServiceTargetEnvelope) CreateProgressMessage

func (ops *ServiceTargetEnvelope) CreateProgressMessage(requestId string, message string) *ServiceTargetMessage

CreateProgressMessage creates a new progress message envelope with the given text. This is used by server-side handlers to send progress updates back to clients.

func (*ServiceTargetEnvelope) GetError

func (ops *ServiceTargetEnvelope) GetError(msg *ServiceTargetMessage) error

GetError returns the error from the message as a Go error type. It returns a typed error based on the ErrorOrigin that preserves structured information for telemetry.

func (*ServiceTargetEnvelope) GetInnerMessage

func (ops *ServiceTargetEnvelope) GetInnerMessage(msg *ServiceTargetMessage) any

GetInnerMessage returns the inner message from the oneof field

func (*ServiceTargetEnvelope) GetProgressMessage

func (ops *ServiceTargetEnvelope) GetProgressMessage(msg *ServiceTargetMessage) string

GetProgressMessage extracts the progress message text from a progress message. Returns empty string if the message is not a progress message.

func (*ServiceTargetEnvelope) GetRequestId

func (ops *ServiceTargetEnvelope) GetRequestId(ctx context.Context, msg *ServiceTargetMessage) string

GetRequestId returns the request ID from the message

func (*ServiceTargetEnvelope) IsProgressMessage

func (ops *ServiceTargetEnvelope) IsProgressMessage(msg *ServiceTargetMessage) bool

IsProgressMessage returns true if the message contains a progress message

func (*ServiceTargetEnvelope) SetError

func (ops *ServiceTargetEnvelope) SetError(msg *ServiceTargetMessage, err error)

SetError sets an error on the message. It detects the error type and populates the appropriate source details.

func (*ServiceTargetEnvelope) SetRequestId

func (ops *ServiceTargetEnvelope) SetRequestId(ctx context.Context, msg *ServiceTargetMessage, id string)

SetRequestId sets the request ID on the message

type ServiceTargetFactory

type ServiceTargetFactory ProviderFactory[ServiceTargetProvider]

ProviderFactory describes a function that creates an instance of a service target provider

type ServiceTargetInitializeRequest

type ServiceTargetInitializeRequest = v1.ServiceTargetInitializeRequest

type ServiceTargetInitializeResponse

type ServiceTargetInitializeResponse = v1.ServiceTargetInitializeResponse

type ServiceTargetInputParameter

type ServiceTargetInputParameter = v1.ServiceTargetInputParameter

type ServiceTargetManager

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

ServiceTargetManager handles registration and provisioning request forwarding for a provider.

func NewServiceTargetManager

func NewServiceTargetManager(extensionId string, client *AzdClient, brokerLogger *log.Logger) *ServiceTargetManager

NewServiceTargetManager creates a new ServiceTargetManager for an AzdClient.

func (*ServiceTargetManager) Close

func (m *ServiceTargetManager) Close() error

Close terminates the underlying gRPC stream if it's been initialized. This method is thread-safe for concurrent access.

func (*ServiceTargetManager) Ready

func (m *ServiceTargetManager) Ready(ctx context.Context) error

Ready blocks until the message broker starts receiving messages or the context is cancelled. This ensures the stream is initialized and then waits for the broker to be ready. Returns nil when ready, or context error if the context is cancelled before ready.

func (*ServiceTargetManager) Receive

func (m *ServiceTargetManager) Receive(ctx context.Context) error

Receive starts the broker's message dispatcher and blocks until the stream completes. This method ensures the stream is initialized then runs the broker.

func (*ServiceTargetManager) Register

func (m *ServiceTargetManager) Register(ctx context.Context, factory ServiceTargetFactory, hostType string) error

Register registers the provider with the server, waits for the response, then starts background handling of provisioning requests.

type ServiceTargetMessage

type ServiceTargetMessage = v1.ServiceTargetMessage

type ServiceTargetMessage_DeployRequest

type ServiceTargetMessage_DeployRequest = v1.ServiceTargetMessage_DeployRequest

type ServiceTargetMessage_DeployResponse

type ServiceTargetMessage_DeployResponse = v1.ServiceTargetMessage_DeployResponse

type ServiceTargetMessage_EndpointsRequest

type ServiceTargetMessage_EndpointsRequest = v1.ServiceTargetMessage_EndpointsRequest

type ServiceTargetMessage_EndpointsResponse

type ServiceTargetMessage_EndpointsResponse = v1.ServiceTargetMessage_EndpointsResponse

type ServiceTargetMessage_GetTargetResourceRequest

type ServiceTargetMessage_GetTargetResourceRequest = v1.ServiceTargetMessage_GetTargetResourceRequest

type ServiceTargetMessage_GetTargetResourceResponse

type ServiceTargetMessage_GetTargetResourceResponse = v1.ServiceTargetMessage_GetTargetResourceResponse

type ServiceTargetMessage_InitializeRequest

type ServiceTargetMessage_InitializeRequest = v1.ServiceTargetMessage_InitializeRequest

type ServiceTargetMessage_InitializeResponse

type ServiceTargetMessage_InitializeResponse = v1.ServiceTargetMessage_InitializeResponse

type ServiceTargetMessage_PackageRequest

type ServiceTargetMessage_PackageRequest = v1.ServiceTargetMessage_PackageRequest

type ServiceTargetMessage_PackageResponse

type ServiceTargetMessage_PackageResponse = v1.ServiceTargetMessage_PackageResponse

type ServiceTargetMessage_ProgressMessage

type ServiceTargetMessage_ProgressMessage = v1.ServiceTargetMessage_ProgressMessage

type ServiceTargetMessage_PublishRequest

type ServiceTargetMessage_PublishRequest = v1.ServiceTargetMessage_PublishRequest

type ServiceTargetMessage_PublishResponse

type ServiceTargetMessage_PublishResponse = v1.ServiceTargetMessage_PublishResponse

type ServiceTargetOptions

type ServiceTargetOptions = v1.ServiceTargetOptions

type ServiceTargetOutputParameter

type ServiceTargetOutputParameter = v1.ServiceTargetOutputParameter

type ServiceTargetPackageRequest

type ServiceTargetPackageRequest = v1.ServiceTargetPackageRequest

type ServiceTargetPackageResponse

type ServiceTargetPackageResponse = v1.ServiceTargetPackageResponse

type ServiceTargetProgressMessage

type ServiceTargetProgressMessage = v1.ServiceTargetProgressMessage

type ServiceTargetProvider

type ServiceTargetProvider interface {
	Initialize(ctx context.Context, serviceConfig *ServiceConfig) error
	Endpoints(
		ctx context.Context,
		serviceConfig *ServiceConfig,
		targetResource *TargetResource,
	) ([]string, error)
	GetTargetResource(
		ctx context.Context,
		subscriptionId string,
		serviceConfig *ServiceConfig,
		defaultResolver func() (*TargetResource, error),
	) (*TargetResource, error)
	Package(
		ctx context.Context,
		serviceConfig *ServiceConfig,
		serviceContext *ServiceContext,
		progress ProgressReporter,
	) (*ServicePackageResult, error)
	Publish(
		ctx context.Context,
		serviceConfig *ServiceConfig,
		serviceContext *ServiceContext,
		targetResource *TargetResource,
		publishOptions *PublishOptions,
		progress ProgressReporter,
	) (*ServicePublishResult, error)
	Deploy(
		ctx context.Context,
		serviceConfig *ServiceConfig,
		serviceContext *ServiceContext,
		targetResource *TargetResource,
		progress ProgressReporter,
	) (*ServiceDeployResult, error)
}

ServiceTargetProvider defines the interface for service target logic.

type ServiceTargetPublishRequest

type ServiceTargetPublishRequest = v1.ServiceTargetPublishRequest

type ServiceTargetPublishResponse

type ServiceTargetPublishResponse = v1.ServiceTargetPublishResponse

type ServiceTargetRegistration

type ServiceTargetRegistration struct {
	Host    string
	Factory func() ServiceTargetProvider
}

ServiceTargetRegistration describes a service target provider to register with azd core.

type ServiceTargetResource

type ServiceTargetResource = v1.ServiceTargetResource

type ServiceTargetServiceClient

type ServiceTargetServiceClient = v1.ServiceTargetServiceClient

type ServiceTargetServiceServer

type ServiceTargetServiceServer = v1.ServiceTargetServiceServer

type ServiceTargetService_StreamClient

type ServiceTargetService_StreamClient = v1.ServiceTargetService_StreamClient

type ServiceTargetService_StreamServer

type ServiceTargetService_StreamServer = v1.ServiceTargetService_StreamServer

type SetConfigRequest

type SetConfigRequest = v1.SetConfigRequest

type SetEnvRequest

type SetEnvRequest = v1.SetEnvRequest

type SetProjectConfigSectionRequest

type SetProjectConfigSectionRequest = v1.SetProjectConfigSectionRequest

type SetProjectConfigValueRequest

type SetProjectConfigValueRequest = v1.SetProjectConfigValueRequest

type SetServiceConfigSectionRequest

type SetServiceConfigSectionRequest = v1.SetServiceConfigSectionRequest

type SetServiceConfigValueRequest

type SetServiceConfigValueRequest = v1.SetServiceConfigValueRequest

type SetUserConfigRequest

type SetUserConfigRequest = v1.SetUserConfigRequest

type ShellInfo added in v1.23.14

type ShellInfo struct {
	// Type is the detected shell type.
	Type ShellType
	// Path is the filesystem path to the shell executable, if known.
	Path string
	// Source describes how the shell was detected.
	Source string
}

ShellInfo contains information about the detected shell.

func DetectShell added in v1.23.14

func DetectShell() ShellInfo

DetectShell identifies the current shell environment.

Detection strategy (in order):

  1. SHELL environment variable (Unix) — most reliable on macOS/Linux.
  2. PSModulePath environment variable — indicates PowerShell on any platform.
  3. ComSpec environment variable (Windows) — standard Windows shell path.
  4. Platform default fallback (sh on Unix, cmd on Windows).

Platform behavior:

  • Windows: Detects cmd.exe (default), PowerShell, or WSL shells.
  • macOS/Linux: Detects from $SHELL (bash, zsh, fish, sh).
  • If $SHELL is unset, falls back to platform default.

DetectShell never returns an error. If detection fails, Type is ShellTypeUnknown.

type ShellType added in v1.23.14

type ShellType string

ShellType represents a detected shell environment.

const (
	// ShellTypeBash is the Bourne Again Shell.
	ShellTypeBash ShellType = "bash"
	// ShellTypeSh is the POSIX shell.
	ShellTypeSh ShellType = "sh"
	// ShellTypeZsh is the Z Shell.
	ShellTypeZsh ShellType = "zsh"
	// ShellTypeFish is the Fish shell.
	ShellTypeFish ShellType = "fish"
	// ShellTypePowerShell is PowerShell (pwsh/powershell.exe).
	ShellTypePowerShell ShellType = "powershell"
	// ShellTypeCmd is Windows cmd.exe.
	ShellTypeCmd ShellType = "cmd"
	// ShellTypeUnknown indicates the shell could not be determined.
	ShellTypeUnknown ShellType = ""
)

func (ShellType) String added in v1.23.14

func (s ShellType) String() string

String returns the string representation of the shell type.

type SubscribeProjectEvent

type SubscribeProjectEvent = v1.SubscribeProjectEvent

type SubscribeServiceEvent

type SubscribeServiceEvent = v1.SubscribeServiceEvent

type Subscription

type Subscription = v1.Subscription

type TargetResource

type TargetResource = v1.TargetResource

type TokenProvider

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

TokenProvider implements azcore.TokenCredential so that extensions can obtain Azure tokens without manual credential construction.

It uses the AZD deployment context (tenant/subscription) retrieved via gRPC and delegates to azidentity.AzureDeveloperCLICredential for the actual token acquisition flow.

Usage:

tp, err := azdext.NewTokenProvider(client, nil)
// use tp as azcore.TokenCredential with any Azure SDK client

func NewTokenProvider

func NewTokenProvider(ctx context.Context, client *AzdClient, opts *TokenProviderOptions) (*TokenProvider, error)

NewTokenProvider creates a TokenProvider for the given AZD client.

If opts is nil, the provider discovers the current tenant from the AZD deployment context and constructs an azidentity.AzureDeveloperCLICredential.

func (*TokenProvider) GetToken

GetToken satisfies azcore.TokenCredential.

func (*TokenProvider) TenantID

func (tp *TokenProvider) TenantID() string

TenantID returns the Azure tenant ID that was resolved or configured for this provider.

type TokenProviderOptions

type TokenProviderOptions struct {
	// TenantID overrides the tenant obtained from the AZD deployment context.
	// When empty, the provider queries the AZD gRPC server for the current tenant.
	TenantID string

	// Credential overrides the default credential chain.
	// When nil, [azidentity.AzureDeveloperCLICredential] is used.
	Credential azcore.TokenCredential
}

TokenProviderOptions configures a TokenProvider.

type ToolArgs

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

ToolArgs wraps parsed MCP tool arguments for typed access.

func ParseToolArgs

func ParseToolArgs(request mcp.CallToolRequest) ToolArgs

ParseToolArgs extracts the arguments map from an MCP CallToolRequest.

func (ToolArgs) Has

func (a ToolArgs) Has(key string) bool

Has returns true if the key exists in the arguments.

func (ToolArgs) OptionalBool

func (a ToolArgs) OptionalBool(key string, defaultValue bool) bool

OptionalBool returns a bool argument or the default if missing.

func (ToolArgs) OptionalFloat

func (a ToolArgs) OptionalFloat(key string, defaultValue float64) float64

OptionalFloat returns a float64 argument or the default if missing.

func (ToolArgs) OptionalInt

func (a ToolArgs) OptionalInt(key string, defaultValue int) int

OptionalInt returns an int argument or the default if missing.

func (ToolArgs) OptionalString

func (a ToolArgs) OptionalString(key, defaultValue string) string

OptionalString returns a string argument or the default if missing.

func (ToolArgs) Raw

func (a ToolArgs) Raw() map[string]any

Raw returns the underlying argument map.

func (ToolArgs) RequireInt

func (a ToolArgs) RequireInt(key string) (int, error)

RequireInt returns an int argument or an error if missing/wrong type. Note: JSON numbers come as float64, so convert appropriately.

func (ToolArgs) RequireString

func (a ToolArgs) RequireString(key string) (string, error)

RequireString returns a string argument or an error if missing/wrong type.

type ToolError added in v1.34.0

type ToolError struct {
	// Message is the human-readable error message.
	Message string
	// Err is the original local error when this value wraps one.
	Err error
	// ToolName is the normalized tool name (for example, "docker").
	ToolName string
	// Kind identifies whether the tool was missing or failed after starting.
	Kind ToolErrorKind
	// ExitCode is the process exit code when the tool ran and failed.
	ExitCode *int
	// Suggestion contains optional user-facing remediation guidance.
	Suggestion string
	// Links contains optional reference links rendered alongside the suggestion.
	Links []errorhandler.ErrorLink
}

ToolError represents a local external tool failure with safe structured metadata.

func (*ToolError) Error added in v1.34.0

func (e *ToolError) Error() string

Error implements the error interface.

func (*ToolError) Unwrap added in v1.34.0

func (e *ToolError) Unwrap() error

Unwrap returns the original local error when one is available.

type ToolErrorKind added in v1.34.0

type ToolErrorKind string

ToolErrorKind identifies how a local external tool operation failed.

const (
	// ToolErrorKindMissing indicates that the required tool was not found.
	ToolErrorKindMissing ToolErrorKind = "missing"
	// ToolErrorKindFailed indicates that the tool was found but the operation failed.
	ToolErrorKindFailed ToolErrorKind = "failed"
)

type ToolInfo added in v1.23.14

type ToolInfo struct {
	// Name is the tool name as requested (e.g., "docker").
	Name string
	// Path is the absolute filesystem path to the resolved executable.
	Path string
	// Found is true if the tool was located on PATH.
	Found bool
}

ToolInfo contains information about a discovered tool on PATH.

func LookupTool added in v1.23.14

func LookupTool(name string) ToolInfo

LookupTool searches for the named executable on the system PATH. If not found on PATH, it also checks the current working directory for a project-local executable with the same name (for example, ./mvnw).

SECURITY NOTE: Project-local tools take precedence over PATH entries. This means a project directory can shadow system tools by placing executables with matching names in the project root. This is by design — project wrapper scripts (e.g., mvnw, gradlew) should override system-installed versions to ensure reproducible builds. However, users should be aware that cloning untrusted repositories could expose them to malicious project-local binaries.

Platform behavior:

  • Windows: Searches PATH and PATHEXT extensions (.exe, .cmd, .bat, etc.).
  • Unix: Searches PATH for files with the executable bit set.

LookupTool never returns an error; if the tool is not found, Found is false and Path is empty.

type ToolsNotFoundError added in v1.23.14

type ToolsNotFoundError struct {
	// Tools lists the names of missing tools.
	Tools []string
}

ToolsNotFoundError reports one or more required tools that are not on PATH.

func (*ToolsNotFoundError) Error added in v1.23.14

func (e *ToolsNotFoundError) Error() string

type UnimplementedAccountServiceServer

type UnimplementedAccountServiceServer = v1.UnimplementedAccountServiceServer

type UnimplementedAiModelServiceServer

type UnimplementedAiModelServiceServer = v1.UnimplementedAiModelServiceServer

type UnimplementedContainerServiceServer

type UnimplementedContainerServiceServer = v1.UnimplementedContainerServiceServer

type UnimplementedDeploymentServiceServer

type UnimplementedDeploymentServiceServer = v1.UnimplementedDeploymentServiceServer

type UnimplementedEnvironmentServiceServer

type UnimplementedEnvironmentServiceServer = v1.UnimplementedEnvironmentServiceServer

type UnimplementedEventServiceServer

type UnimplementedEventServiceServer = v1.UnimplementedEventServiceServer

type UnimplementedExtensionServiceServer

type UnimplementedExtensionServiceServer = v1.UnimplementedExtensionServiceServer

type UnimplementedFrameworkServiceServer

type UnimplementedFrameworkServiceServer = v1.UnimplementedFrameworkServiceServer

type UnimplementedProjectServiceServer

type UnimplementedProjectServiceServer = v1.UnimplementedProjectServiceServer

type UnimplementedPromptServiceServer

type UnimplementedPromptServiceServer = v1.UnimplementedPromptServiceServer

type UnimplementedProvisioningServiceServer added in v1.24.2

type UnimplementedProvisioningServiceServer = v1.UnimplementedProvisioningServiceServer

type UnimplementedServiceTargetServiceServer

type UnimplementedServiceTargetServiceServer = v1.UnimplementedServiceTargetServiceServer

type UnimplementedUserConfigServiceServer

type UnimplementedUserConfigServiceServer = v1.UnimplementedUserConfigServiceServer

type UnimplementedValidationServiceServer added in v1.26.0

type UnimplementedValidationServiceServer = v1.UnimplementedValidationServiceServer

type UnimplementedWorkflowServiceServer

type UnimplementedWorkflowServiceServer = v1.UnimplementedWorkflowServiceServer

type UnsafeAccountServiceServer

type UnsafeAccountServiceServer = v1.UnsafeAccountServiceServer

type UnsafeAiModelServiceServer

type UnsafeAiModelServiceServer = v1.UnsafeAiModelServiceServer

type UnsafeContainerServiceServer

type UnsafeContainerServiceServer = v1.UnsafeContainerServiceServer

type UnsafeDeploymentServiceServer

type UnsafeDeploymentServiceServer = v1.UnsafeDeploymentServiceServer

type UnsafeEnvironmentServiceServer

type UnsafeEnvironmentServiceServer = v1.UnsafeEnvironmentServiceServer

type UnsafeEventServiceServer

type UnsafeEventServiceServer = v1.UnsafeEventServiceServer

type UnsafeExtensionServiceServer

type UnsafeExtensionServiceServer = v1.UnsafeExtensionServiceServer

type UnsafeFrameworkServiceServer

type UnsafeFrameworkServiceServer = v1.UnsafeFrameworkServiceServer

type UnsafeProjectServiceServer

type UnsafeProjectServiceServer = v1.UnsafeProjectServiceServer

type UnsafePromptServiceServer

type UnsafePromptServiceServer = v1.UnsafePromptServiceServer

type UnsafeProvisioningServiceServer added in v1.24.2

type UnsafeProvisioningServiceServer = v1.UnsafeProvisioningServiceServer

type UnsafeServiceTargetServiceServer

type UnsafeServiceTargetServiceServer = v1.UnsafeServiceTargetServiceServer

type UnsafeUserConfigServiceServer

type UnsafeUserConfigServiceServer = v1.UnsafeUserConfigServiceServer

type UnsafeValidationServiceServer added in v1.26.0

type UnsafeValidationServiceServer = v1.UnsafeValidationServiceServer

type UnsafeWorkflowServiceServer

type UnsafeWorkflowServiceServer = v1.UnsafeWorkflowServiceServer

type UnsetConfigRequest

type UnsetConfigRequest = v1.UnsetConfigRequest

type UnsetProjectConfigRequest

type UnsetProjectConfigRequest = v1.UnsetProjectConfigRequest

type UnsetServiceConfigRequest

type UnsetServiceConfigRequest = v1.UnsetServiceConfigRequest

type UnsetUserConfigRequest

type UnsetUserConfigRequest = v1.UnsetUserConfigRequest

type UserConfigServiceClient

type UserConfigServiceClient = v1.UserConfigServiceClient

type UserConfigServiceServer

type UserConfigServiceServer = v1.UserConfigServiceServer

type ValidationCheckProvider added in v1.26.0

type ValidationCheckProvider interface {
	// Validate runs the check against the provided context and returns results.
	Validate(
		ctx context.Context,
		valCtx *ValidationContext,
		req *ValidationCheckRequest,
	) (*ValidationCheckResponse, error)
}

ValidationCheckProvider is the extension-side interface for a validation check. Extensions implement this to provide custom checks that run during the azd validation pipeline (e.g. arm-provision during provisioning).

type ValidationCheckProviderFactory added in v1.26.0

type ValidationCheckProviderFactory func() ValidationCheckProvider

ValidationCheckProviderFactory creates a new ValidationCheckProvider instance.

type ValidationCheckRegistration added in v1.26.0

type ValidationCheckRegistration struct {
	// CheckType identifies the validation context (e.g. "arm-provision").
	CheckType string
	// RuleID is a stable, unique identifier for this check rule.
	RuleID string
	// Factory creates a new provider instance.
	Factory ValidationCheckProviderFactory
}

ValidationCheckRegistration describes a validation check to register with azd core.

type ValidationCheckRequest added in v1.26.0

type ValidationCheckRequest = v1.ValidationCheckRequest

type ValidationCheckResponse added in v1.26.0

type ValidationCheckResponse = v1.ValidationCheckResponse

type ValidationCheckResult added in v1.26.0

type ValidationCheckResult = v1.ValidationCheckResult

type ValidationCheckSeverity added in v1.26.0

type ValidationCheckSeverity = v1.ValidationCheckSeverity

type ValidationContext added in v1.26.0

type ValidationContext struct {
	// ContextID is the unique identifier for this context delivery.
	ContextID string
	// CheckType identifies the validation context (e.g. "arm-provision").
	CheckType string
	// Data is the reassembled context map (key → full value).
	Data map[string][]byte
}

ValidationContext holds the assembled context data for a validation check. It is populated from PrepareValidationContextChunk messages and injected into the provider's Validate call by the ValidationManager.

The contents of Data depend on CheckType — use the typed accessors below rather than reading Data directly:

  • ValidationCheckTypeArmProvision ("arm-provision"): a Bicep-only, ARM-rich context. Accessors: ARMTemplate, ARMParameters, ResourcesSnapshot, PredictedResources (plus EnvLocation).
  • ValidationCheckTypeProvision ("provision"): a provider-agnostic, lean context carrying no ARM data — only ambient environment values. Accessors: EnvName, SubscriptionID, EnvLocation, ResourceGroup, TargetScope. These are best-effort and may be empty on a cold run (see ValidationCheckTypeProvision for details).

func (*ValidationContext) ARMParameters added in v1.26.0

func (c *ValidationContext) ARMParameters() ([]byte, bool)

ARMParameters returns the resolved ARM parameters JSON from the context.

func (*ValidationContext) ARMTemplate added in v1.26.0

func (c *ValidationContext) ARMTemplate() ([]byte, bool)

ARMTemplate returns the compiled ARM template JSON from the context.

func (*ValidationContext) EnvLocation added in v1.26.0

func (c *ValidationContext) EnvLocation() (string, bool)

EnvLocation returns the Azure deployment location from the context. For "provision" checks this is a best-effort ambient value that may be empty on a cold first-time run, since the dispatch precedes the provider's location resolution/prompt.

func (*ValidationContext) EnvName added in v1.27.1

func (c *ValidationContext) EnvName() (string, bool)

EnvName returns the azd environment name from a "provision" check context.

func (*ValidationContext) ParsePredictedResources added in v1.26.0

func (c *ValidationContext) ParsePredictedResources() ([]PredictedResource, error)

ParsePredictedResources returns the predicted resources as typed structs. This is a convenience wrapper that parses the JSON array into []PredictedResource.

func (*ValidationContext) PredictedResources added in v1.26.0

func (c *ValidationContext) PredictedResources() ([]byte, bool)

PredictedResources returns the predicted resources JSON array from the context.

func (*ValidationContext) ResourceGroup added in v1.27.1

func (c *ValidationContext) ResourceGroup() (string, bool)

ResourceGroup returns the target resource group name from a "provision" check context. The "provision" dispatch always includes the resource group key, so ok is true whenever the context originates from a provision check; the value is an empty string for subscription-scoped deployments (use TargetScope to distinguish scopes rather than relying on ok).

This is a best-effort ambient value read from AZURE_RESOURCE_GROUP before the provider resolves/prompts for the resource group, so it may be empty on a cold run even for an RG-scoped template. Treat it as best-effort.

func (*ValidationContext) ResourcesSnapshot added in v1.26.0

func (c *ValidationContext) ResourcesSnapshot() ([]byte, bool)

ResourcesSnapshot returns the raw Bicep snapshot JSON from the context.

func (*ValidationContext) SubscriptionID added in v1.27.1

func (c *ValidationContext) SubscriptionID() (string, bool)

SubscriptionID returns the Azure subscription id from a "provision" check context. This is a best-effort ambient value: the "provision" dispatch runs before the provider resolves/prompts for the subscription, so it may be empty on a cold first-time run. Treat an empty value as "not yet known".

func (*ValidationContext) TargetScope added in v1.27.1

func (c *ValidationContext) TargetScope() (string, bool)

TargetScope returns the deployment target scope ("subscription" or "resourceGroup") from a "provision" check context.

This is best-effort, not authoritative: it is inferred solely from the presence of AZURE_RESOURCE_GROUP in the environment at dispatch time, before the provider (e.g. Bicep) determines the template's actual target scope. On a cold run it can report "subscription" for an RG-scoped template, or "resourceGroup" from a stale env var for a subscription-scoped deployment. Do not rely on it as the definitive scope.

type ValidationEnvelope added in v1.26.0

type ValidationEnvelope struct{}

ValidationEnvelope provides message operations for ValidationMessage. It implements the grpcbroker.MessageEnvelope interface.

func NewValidationEnvelope added in v1.26.0

func NewValidationEnvelope() *ValidationEnvelope

NewValidationEnvelope creates a new ValidationEnvelope instance.

func (*ValidationEnvelope) CreateProgressMessage added in v1.26.0

func (ops *ValidationEnvelope) CreateProgressMessage(
	requestId string, _ string,
) *ValidationMessage

CreateProgressMessage creates a progress message envelope. Validation does not use progress messages, but the interface requires this method. Returns a minimal message.

func (*ValidationEnvelope) GetError added in v1.26.0

func (ops *ValidationEnvelope) GetError(msg *ValidationMessage) error

GetError returns the error from the message as a Go error type.

func (*ValidationEnvelope) GetInnerMessage added in v1.26.0

func (ops *ValidationEnvelope) GetInnerMessage(
	msg *ValidationMessage,
) any

GetInnerMessage returns the inner message from the oneof field.

func (*ValidationEnvelope) GetProgressMessage added in v1.26.0

func (ops *ValidationEnvelope) GetProgressMessage(
	_ *ValidationMessage,
) string

GetProgressMessage returns empty string — validation has no progress.

func (*ValidationEnvelope) GetRequestId added in v1.26.0

func (ops *ValidationEnvelope) GetRequestId(
	_ context.Context, msg *ValidationMessage,
) string

GetRequestId returns the request ID from the message.

func (*ValidationEnvelope) IsProgressMessage added in v1.26.0

func (ops *ValidationEnvelope) IsProgressMessage(
	_ *ValidationMessage,
) bool

IsProgressMessage returns true if the message is a progress message. Validation messages do not support progress; always returns false.

func (*ValidationEnvelope) SetError added in v1.26.0

func (ops *ValidationEnvelope) SetError(
	msg *ValidationMessage, err error,
)

SetError sets an error on the message.

func (*ValidationEnvelope) SetRequestId added in v1.26.0

func (ops *ValidationEnvelope) SetRequestId(
	_ context.Context, msg *ValidationMessage, id string,
)

SetRequestId sets the request ID on the message.

type ValidationError added in v1.23.14

type ValidationError struct {
	// Field is the logical name of the input being validated (e.g. "service_name").
	Field string

	// Value is the rejected input value. For security-sensitive inputs the value
	// may be truncated or redacted by the caller before constructing the error.
	Value string

	// Rule is a short machine-readable tag for the violated constraint
	// (e.g. "format", "length", "characters").
	Rule string

	// Message is a human-readable explanation suitable for end-user display.
	Message string
}

ValidationError describes a failed input validation with structured context.

func (*ValidationError) Error added in v1.23.14

func (e *ValidationError) Error() string

type ValidationManager added in v1.26.0

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

ValidationManager manages validation check providers on the extension side. It handles registration with the core and dispatching incoming check requests to the appropriate provider.

func NewValidationManager added in v1.26.0

func NewValidationManager(
	extensionId string,
	client *AzdClient,
	brokerLogger *log.Logger,
) *ValidationManager

NewValidationManager creates a new ValidationManager.

func (*ValidationManager) Close added in v1.26.0

func (m *ValidationManager) Close() error

Close terminates the underlying gRPC stream.

func (*ValidationManager) Ready added in v1.26.0

func (m *ValidationManager) Ready(ctx context.Context) error

Ready blocks until the message broker is ready.

func (*ValidationManager) Receive added in v1.26.0

func (m *ValidationManager) Receive(ctx context.Context) error

Receive starts the broker dispatcher, blocking until stream ends.

func (*ValidationManager) Register added in v1.26.0

func (m *ValidationManager) Register(
	ctx context.Context,
	factory ValidationCheckProviderFactory,
	checkType string,
	ruleID string,
) error

Register registers a validation check with the core, waits for the response, then starts handling incoming check requests.

type ValidationMessage added in v1.26.0

type ValidationMessage = v1.ValidationMessage

type ValidationMessage_PrepareValidationContextChunk added in v1.26.0

type ValidationMessage_PrepareValidationContextChunk = v1.ValidationMessage_PrepareValidationContextChunk

type ValidationMessage_PrepareValidationContextResponse added in v1.26.0

type ValidationMessage_PrepareValidationContextResponse = v1.ValidationMessage_PrepareValidationContextResponse

type ValidationMessage_RegisterValidationCheckRequest added in v1.26.0

type ValidationMessage_RegisterValidationCheckRequest = v1.ValidationMessage_RegisterValidationCheckRequest

type ValidationMessage_RegisterValidationCheckResponse added in v1.26.0

type ValidationMessage_RegisterValidationCheckResponse = v1.ValidationMessage_RegisterValidationCheckResponse

type ValidationMessage_ValidationCheckRequest added in v1.26.0

type ValidationMessage_ValidationCheckRequest = v1.ValidationMessage_ValidationCheckRequest

type ValidationMessage_ValidationCheckResponse added in v1.26.0

type ValidationMessage_ValidationCheckResponse = v1.ValidationMessage_ValidationCheckResponse
type ValidationReportLink = v1.ValidationReportLink

type ValidationServiceClient added in v1.26.0

type ValidationServiceClient = v1.ValidationServiceClient

func NewValidationServiceClient added in v1.26.0

func NewValidationServiceClient(cc grpc.ClientConnInterface) ValidationServiceClient

type ValidationServiceServer added in v1.26.0

type ValidationServiceServer = v1.ValidationServiceServer

type ValidationService_StreamClient added in v1.26.0

type ValidationService_StreamClient = v1.ValidationService_StreamClient

type ValidationService_StreamServer added in v1.26.0

type ValidationService_StreamServer = v1.ValidationService_StreamServer

type Workflow

type Workflow = v1.Workflow

type WorkflowCommand

type WorkflowCommand = v1.WorkflowCommand

type WorkflowServiceClient

type WorkflowServiceClient = v1.WorkflowServiceClient

type WorkflowServiceServer

type WorkflowServiceServer = v1.WorkflowServiceServer

type WorkflowStep

type WorkflowStep = v1.WorkflowStep

Directories

Path Synopsis
contracts
v1

Jump to

Keyboard shortcuts

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