Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ For automation, `unic resources <query> --json` runs a read-only AWS query using
- `rds-instances`
- `elasticache-resources`
- `sns-topics`
- `cloudformation-stacks`
- `alarms`
- `ecs-rollout --cluster <name-or-arn> --service <name-or-arn>`
- `cloudtrail-events [--since 24h] [--resource <name>] [--mutations-only]`
Expand All @@ -173,7 +174,7 @@ For automation, `unic resources <query> --json` runs a read-only AWS query using

Inspector runs outside `resources` because it is a scan, not a resource listing. `unic inspect --json` runs every built-in security and cost/waste rule pack against the active context and returns the same v1 envelope, with `data` carrying `scanned_at`, `scanner_count`, `finding_count`, `severity_counts`, and the `findings` array. Rule packs that fail — most often a denied API call — appear in `warnings` rather than being dropped, so a partially blocked scan is never reported as a clean one. The equivalent MCP tool is `run_security_inspector`. The root `--checklist` flag is inherited but rejected here: Checklist Inspector produces a different report shape and has no agent contract yet, so it fails loudly rather than returning security findings in its place.

The same operations are exposed by `unic-mcp` as read-only tools. Call `get_mcp_capabilities` to discover their versioned input contracts, strict input schemas, output contracts, pagination behavior, and required IAM permissions. The operation permissions are `ec2:DescribeInstances`, `rds:DescribeDBInstances`, `elasticache:DescribeCacheClusters`, `elasticache:DescribeReplicationGroups`, `cloudwatch:DescribeAlarms`, `ecs:DescribeServices`, `ecs:DescribeTaskDefinition`, `cloudtrail:LookupEvents`, `elasticloadbalancing:DescribeTargetGroups`, `elasticloadbalancing:DescribeTargetHealth`, `sns:ListTopics`, `sns:GetTopicAttributes`, `sns:ListSubscriptionsByTopic`, `sns:GetSubscriptionAttributes`, `sqs:ListQueues`, and `sqs:GetQueueAttributes`; AWS Backup retains the permissions documented below. CLI and MCP output never includes resolved credentials.
The same operations are exposed by `unic-mcp` as read-only tools. Call `get_mcp_capabilities` to discover their versioned input contracts, strict input schemas, output contracts, pagination behavior, and required IAM permissions. The operation permissions are `ec2:DescribeInstances`, `rds:DescribeDBInstances`, `elasticache:DescribeCacheClusters`, `elasticache:DescribeReplicationGroups`, `cloudwatch:DescribeAlarms`, `ecs:DescribeServices`, `ecs:DescribeTaskDefinition`, `cloudtrail:LookupEvents`, `cloudformation:DescribeStacks`, `elasticloadbalancing:DescribeTargetGroups`, `elasticloadbalancing:DescribeTargetHealth`, `sns:ListTopics`, `sns:GetTopicAttributes`, `sns:ListSubscriptionsByTopic`, `sns:GetSubscriptionAttributes`, `sqs:ListQueues`, and `sqs:GetQueueAttributes`; AWS Backup retains the permissions documented below. CLI and MCP output never includes resolved credentials.

### MCP server

Expand Down Expand Up @@ -260,6 +261,11 @@ The server provides the read-only resource operations listed above plus capabili
- `Show the AWS capabilities available through unic.`
- `List my AWS Backup vaults in ap-northeast-2.`
- `Show my deepest SQS backlogs and their dead-letter queue relationships.`
The server exposes the read-only resource operations listed above—including `list_cloudformation_stacks`—plus capability discovery, Security Inspector, and context-sync preview tools. Agents should call `get_mcp_capabilities` first because it describes only operations callable through MCP, including permissions and output contracts. Example prompts:

- `Show the AWS capabilities available through unic.`
- `List my AWS Backup vaults in ap-northeast-2.`
- `Show failed or rollback CloudFormation stacks and their status reasons.`
- `Preview a unic context sync without changing config.`

The context-sync tool is preview-only: it never passes `--apply` or writes configuration. If a client cannot start the server, verify `unic-mcp` is on the client's `PATH` and that the required AWS profile or SSO session is available in the client process environment.
Expand Down
4 changes: 4 additions & 0 deletions docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ unic schema context sync --json
unic schema resources elasticache-resources --json

unic schema resources sns-topics --json

unic schema resources cloudformation-stacks --json
```

Discovery output is deterministic, versioned JSON. New executable commands should set the `unic.dev/read-only`, `unic.dev/destructive`, and `unic.dev/output-version` annotations when their defaults do not describe the command accurately.
Expand All @@ -38,6 +40,8 @@ Read-only automation commands live under `internal/cli/`; keep their `--json` ou

`unic resources sns-topics --json` composes the existing topic and per-topic subscription reads. Keep partial lookup failures in the envelope's `warnings` array and keep the contract read-only; publishing and subscription changes remain outside the agent surface.

`unic resources cloudformation-stacks --json` reuses the browser's failure-first stack ordering and returns status reasons, drift state, parameters, and outputs. Recent events remain a separate per-stack detail lookup and are not implied by this listing contract.

The stdio MCP entry point lives at `cmd/unic-mcp` and delegates tool calls to those same CLI commands through `internal/cli.ExecuteAutomation`. Keep the MCP layer limited to protocol handling and argument mapping; AWS and config behavior belongs in the existing CLI, auth, and service packages. MCP mutation tools remain preview-only until their trust boundary is reviewed.

The repository root is also the portable agent-plugin package. Keep shared MCP guidance in `skills/unic-aws`, Kiro metadata in `plugin.json` and `mcp.json`, and client-specific manifests in `.codex-plugin`, `.claude-plugin`, and `.mcp.json`. All clients must launch the released `unic-mcp` binary from `PATH`; do not add client-specific MCP implementations.
Expand Down
43 changes: 42 additions & 1 deletion internal/cli/resources.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"text/tabwriter"
"time"

"github.com/spf13/cobra"

Expand Down Expand Up @@ -66,6 +67,46 @@ type snsSubscriptionJSON struct {
AttributesKnown bool `json:"attributes_known"`
}

type cloudFormationStackJSON struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Status string `json:"status"`
StatusReason string `json:"status_reason,omitempty"`
DriftStatus string `json:"drift_status"`
Region string `json:"region"`
LastDriftCheck string `json:"last_drift_check,omitempty"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at,omitempty"`
TerminationProtection bool `json:"termination_protection"`
Parameters []cloudFormationValueJSON `json:"parameters"`
Outputs []cloudFormationValueJSON `json:"outputs"`
}

type cloudFormationValueJSON struct {
Key string `json:"key"`
Value string `json:"value"`
Description string `json:"description,omitempty"`
ExportName string `json:"export_name,omitempty"`
}

func cloudFormationValuesJSON(values []awsservice.CloudFormationValue) []cloudFormationValueJSON {
result := make([]cloudFormationValueJSON, 0, len(values))
for _, value := range values {
result = append(result, cloudFormationValueJSON{
Key: value.Key, Value: value.Value, Description: value.Description, ExportName: value.ExportName,
})
}
return result
}

func cloudFormationTimeJSON(value time.Time) string {
if value.IsZero() {
return ""
}
return value.UTC().Format(time.RFC3339)
}

var loadBackupVaults = func(ctx context.Context) ([]awsservice.BackupVault, []error, error) {
configPath, err := config.DefaultPath()
if err != nil {
Expand All @@ -88,7 +129,7 @@ var loadBackupVaults = func(ctx context.Context) ([]awsservice.BackupVault, []er
func newResourcesCmd() *cobra.Command {
cmd := &cobra.Command{Use: "resources", Short: "Read-only resource queries for automation"}
cmd.AddCommand(newBackupVaultsCmd())
cmd.AddCommand(newEC2InstancesCmd(), newRDSInstancesCmd(), newAlarmsCmd())
cmd.AddCommand(newEC2InstancesCmd(), newRDSInstancesCmd(), newCloudFormationStacksCmd(), newAlarmsCmd())
cmd.AddCommand(newECSRolloutCmd(), newCloudTrailEventsCmd(), newELBTargetHealthCmd(), newSQSQueuesCmd(), newElastiCacheResourcesCmd(), newSNSTopicsCmd())
return cmd
}
Expand Down
24 changes: 24 additions & 0 deletions internal/cli/resources_operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,13 @@ var (
}
return repo.ListSNSTopicResources(ctx)
}
loadCloudFormationStacks = func(ctx context.Context) ([]awsservice.CloudFormationStack, error) {
repo, err := resourceRepository(ctx)
if err != nil {
return nil, err
}
return repo.ListCloudFormationStacks(ctx)
}
loadSQSQueues = func(ctx context.Context) ([]awsservice.SQSQueue, error) {
repo, err := resourceRepository(ctx)
if err != nil {
Expand Down Expand Up @@ -271,3 +278,20 @@ func newSNSTopicsCmd() *cobra.Command {
cmd.Flags().BoolVar(&jsonOutput, "json", true, "Emit stable machine-readable JSON")
return cmd
}

func newCloudFormationStacksCmd() *cobra.Command {
return jsonResourceCommand("cloudformation-stacks", "List CloudFormation stacks in triage order as JSON", func(ctx context.Context) (any, error) {
stacks, err := loadCloudFormationStacks(ctx)
data := make([]cloudFormationStackJSON, 0, len(stacks))
for _, stack := range stacks {
data = append(data, cloudFormationStackJSON{
ID: stack.ID, Name: stack.Name, Description: stack.Description,
Status: stack.Status, StatusReason: stack.StatusReason, DriftStatus: stack.DriftStatus, Region: stack.Region,
LastDriftCheck: cloudFormationTimeJSON(stack.LastDriftCheck), CreatedAt: cloudFormationTimeJSON(stack.CreatedAt), UpdatedAt: cloudFormationTimeJSON(stack.UpdatedAt),
TerminationProtection: stack.TerminationProtection,
Parameters: cloudFormationValuesJSON(stack.Parameters), Outputs: cloudFormationValuesJSON(stack.Outputs),
})
}
return data, err
})
}
76 changes: 76 additions & 0 deletions internal/cli/resources_operations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"testing"
"time"

awsservice "unic/internal/services/aws"
)
Expand Down Expand Up @@ -271,3 +272,78 @@ func TestSNSTopicsLoaderErrorEmitsNoEnvelope(t *testing.T) {
t.Fatalf("expected no success envelope, got %s", output.String())
}
}

func TestCloudFormationStacksJSONContract(t *testing.T) {
original := loadCloudFormationStacks
defer func() { loadCloudFormationStacks = original }()
now := time.Date(2026, 9, 15, 5, 0, 0, 0, time.FixedZone("KST", 9*60*60))
loadCloudFormationStacks = func(context.Context) ([]awsservice.CloudFormationStack, error) {
return []awsservice.CloudFormationStack{
{
ID: "stack-id", Name: "failed", Description: "production stack", Status: "CREATE_FAILED", StatusReason: "bucket exists",
DriftStatus: "DRIFTED", Region: "ap-northeast-2", LastDriftCheck: now, CreatedAt: now.Add(-time.Hour), UpdatedAt: now,
TerminationProtection: true,
Parameters: []awsservice.CloudFormationValue{{Key: "Environment", Value: "prod"}},
Outputs: []awsservice.CloudFormationValue{{Key: "Endpoint", Value: "example.com", Description: "service endpoint", ExportName: "prod-endpoint"}},
},
{Name: "empty", DriftStatus: "NOT_CHECKED", CreatedAt: now},
}, nil
}

cmd := NewRootCmd()
var output bytes.Buffer
cmd.SetOut(&output)
cmd.SetArgs([]string{"resources", "cloudformation-stacks", "--json"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
var result struct {
SchemaVersion string `json:"schema_version"`
Data []struct {
Name string `json:"name"`
Status string `json:"status"`
StatusReason string `json:"status_reason"`
DriftStatus string `json:"drift_status"`
LastDriftCheck string `json:"last_drift_check"`
CreatedAt string `json:"created_at"`
Parameters []struct {
Key string `json:"key"`
} `json:"parameters"`
Outputs []struct {
ExportName string `json:"export_name"`
} `json:"outputs"`
} `json:"data"`
Warnings []string `json:"warnings"`
Pagination jsonPagination `json:"pagination"`
}
if err := json.Unmarshal(output.Bytes(), &result); err != nil {
t.Fatal(err)
}
if result.SchemaVersion != "v1" || len(result.Data) != 2 || result.Data[0].Name != "failed" || result.Data[0].Status != "CREATE_FAILED" ||
result.Data[0].StatusReason != "bucket exists" || result.Data[0].DriftStatus != "DRIFTED" || result.Data[0].LastDriftCheck != "2026-09-14T20:00:00Z" ||
result.Data[0].CreatedAt != "2026-09-14T19:00:00Z" || len(result.Data[0].Parameters) != 1 || result.Data[0].Parameters[0].Key != "Environment" ||
len(result.Data[0].Outputs) != 1 || result.Data[0].Outputs[0].ExportName != "prod-endpoint" || result.Data[1].Parameters == nil || result.Data[1].Outputs == nil ||
result.Warnings == nil || !result.Pagination.Complete {
t.Fatalf("unexpected result: %+v", result)
}
if bytes.Contains(output.Bytes(), []byte(`"events"`)) {
t.Fatalf("stack listing must not imply that recent events were loaded: %s", output.String())
}
}

func TestCloudFormationStacksLoaderErrorEmitsNoEnvelope(t *testing.T) {
original := loadCloudFormationStacks
defer func() { loadCloudFormationStacks = original }()
wantErr := errors.New("stack lookup failed")
loadCloudFormationStacks = func(context.Context) ([]awsservice.CloudFormationStack, error) { return nil, wantErr }
cmd := NewRootCmd()
var output bytes.Buffer
cmd.SetOut(&output)
cmd.SetArgs([]string{"resources", "cloudformation-stacks", "--json"})
if err := cmd.Execute(); !errors.Is(err, wantErr) {
t.Fatalf("expected loader error, got %v", err)
}
if output.Len() != 0 {
t.Fatalf("expected no success envelope, got %s", output.String())
}
}
22 changes: 11 additions & 11 deletions internal/mcp/agent_surface_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,24 +22,24 @@ type agentCommandContract struct {
}

var agentSurfaceByFeature = map[domain.FeatureKind]agentSurface{
domain.FeatureBackupBrowser: {command: "backup-vaults", tool: "list_backup_vaults"},
domain.FeatureCloudTrailEvents: {command: "cloudtrail-events", tool: "list_cloudtrail_events"},
domain.FeatureCloudWatchAlarms: {command: "alarms", tool: "list_cloudwatch_alarms"},
domain.FeatureEC2InstanceBrowser: {command: "ec2-instances", tool: "list_ec2_instances"},
domain.FeatureECSExec: {command: "ecs-rollout", tool: "get_ecs_service_rollout", arguments: json.RawMessage(`{"cluster":"cluster","service":"service"}`)},
domain.FeatureElastiCacheBrowser: {command: "elasticache-resources", tool: "list_elasticache_resources"},
domain.FeatureELBBrowser: {command: "elb-target-health", tool: "get_elb_target_health", arguments: json.RawMessage(`{"load_balancer":"load-balancer"}`)},
domain.FeatureRDSBrowser: {command: "rds-instances", tool: "list_rds_instances"},
domain.FeatureSQSBrowser: {command: "sqs-queues", tool: "list_sqs_queues"},
domain.FeatureSNSBrowser: {command: "sns-topics", tool: "list_sns_topics"},
domain.FeatureBackupBrowser: {command: "backup-vaults", tool: "list_backup_vaults"},
domain.FeatureCloudFormationBrowser: {command: "cloudformation-stacks", tool: "list_cloudformation_stacks"},
domain.FeatureCloudTrailEvents: {command: "cloudtrail-events", tool: "list_cloudtrail_events"},
domain.FeatureCloudWatchAlarms: {command: "alarms", tool: "list_cloudwatch_alarms"},
domain.FeatureEC2InstanceBrowser: {command: "ec2-instances", tool: "list_ec2_instances"},
domain.FeatureECSExec: {command: "ecs-rollout", tool: "get_ecs_service_rollout", arguments: json.RawMessage(`{"cluster":"cluster","service":"service"}`)},
domain.FeatureElastiCacheBrowser: {command: "elasticache-resources", tool: "list_elasticache_resources"},
domain.FeatureELBBrowser: {command: "elb-target-health", tool: "get_elb_target_health", arguments: json.RawMessage(`{"load_balancer":"load-balancer"}`)},
domain.FeatureRDSBrowser: {command: "rds-instances", tool: "list_rds_instances"},
domain.FeatureSQSBrowser: {command: "sqs-queues", tool: "list_sqs_queues"},
domain.FeatureSNSBrowser: {command: "sns-topics", tool: "list_sns_topics"},
}

var agentSurfaceExempt = map[domain.FeatureKind]string{
domain.FeatureACMCertificateBrowser: "no curated certificate-expiry query is defined yet",
domain.FeatureAPIGatewayV2Browser: "no curated API and route query is defined yet",
domain.FeatureAutoScalingBrowser: "capacity changes are mutation-gated and no separate read-only contract exists yet",
domain.FeatureBedrockAPIKeys: "key management handles one-time secrets and mutations",
domain.FeatureCloudFormationBrowser: "the failure-first multi-call view has no curated agent contract yet",
domain.FeatureCloudWatchLogsBrowser: "log content needs an explicitly bounded query contract",
domain.FeatureCloudWatchMetrics: "interactive chart presets have no stable agent query contract",
domain.FeatureDynamoDBBrowser: "item reads need an explicitly bounded key and output contract",
Expand Down
10 changes: 8 additions & 2 deletions internal/mcp/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,12 @@ var tools = []tool{
OutputContract: "unic.resources.sns-topics.v1", Paginated: true, PartialResults: true,
},
},
{
Name: "list_cloudformation_stacks", Description: "List CloudFormation stacks in failure-first triage order with status, drift, parameters, and outputs.",
InputSchema: awsContextSchema(nil, nil),
Annotations: annotations{ReadOnlyHint: true, IdempotentHint: true, OpenWorldHint: true},
Metadata: toolMetadata{RequiredPermissions: []string{"cloudformation:DescribeStacks", "cloudformation:ListStacks"}, OutputContract: "unic.resources.cloudformation-stacks.v1", Paginated: true},
},
{
Name: "list_cloudwatch_alarms", Description: "List CloudWatch alarms with firing alarms first.",
InputSchema: awsContextSchema(nil, nil),
Expand Down Expand Up @@ -432,15 +438,15 @@ func toolArgs(name string, raw json.RawMessage) ([]string, error) {
result = append(result, "--region", args.Region)
}
return result, nil
case "list_ec2_instances", "list_rds_instances", "list_cloudwatch_alarms", "list_sqs_queues", "list_elasticache_resources", "list_sns_topics":
case "list_ec2_instances", "list_rds_instances", "list_cloudwatch_alarms", "list_sqs_queues", "list_elasticache_resources", "list_sns_topics", "list_cloudformation_stacks":
var args struct {
Profile string `json:"profile"`
Region string `json:"region"`
}
if err := decodeArguments(raw, &args); err != nil {
return nil, err
}
command := map[string]string{"list_ec2_instances": "ec2-instances", "list_rds_instances": "rds-instances", "list_cloudwatch_alarms": "alarms", "list_sqs_queues": "sqs-queues", "list_elasticache_resources": "elasticache-resources", "list_sns_topics": "sns-topics"}[name]
command := map[string]string{"list_ec2_instances": "ec2-instances", "list_rds_instances": "rds-instances", "list_cloudwatch_alarms": "alarms", "list_sqs_queues": "sqs-queues", "list_elasticache_resources": "elasticache-resources", "list_sns_topics": "sns-topics", "list_cloudformation_stacks": "cloudformation-stacks"}[name]
return withAWSContext([]string{"resources", command, "--json"}, args.Profile, args.Region), nil
case "get_ecs_service_rollout":
var args struct {
Expand Down
Loading
Loading