Skip to content
Open
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
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,14 +160,15 @@ For automation, `unic resources <query> --json` runs a read-only AWS query using
- `backup-vaults`
- `ec2-instances`
- `rds-instances`
- `sns-topics`
- `alarms`
- `ecs-rollout --cluster <name-or-arn> --service <name-or-arn>`
- `cloudtrail-events [--since 24h] [--resource <name>] [--mutations-only]`
- `elb-target-health --load-balancer <arn>`

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`, `cloudwatch:DescribeAlarms`, `ecs:DescribeServices`, `ecs:DescribeTaskDefinition`, `cloudtrail:LookupEvents`, `elasticloadbalancing:DescribeTargetGroups`, and `elasticloadbalancing:DescribeTargetHealth`; 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`, `sns:ListTopics`, `sns:GetTopicAttributes`, `sns:ListSubscriptionsByTopic`, `sns:GetSubscriptionAttributes`, `cloudwatch:DescribeAlarms`, `ecs:DescribeServices`, `ecs:DescribeTaskDefinition`, `cloudtrail:LookupEvents`, `elasticloadbalancing:DescribeTargetGroups`, and `elasticloadbalancing:DescribeTargetHealth`; AWS Backup retains the permissions documented below. CLI and MCP output never includes resolved credentials.

### MCP server

Expand Down Expand Up @@ -249,10 +250,11 @@ For Claude Desktop and other JSON-configured MCP clients, use:

In Kiro, open **Powers**, choose **Add Custom Power**, and import this repository from GitHub. The root `plugin.json`, `mcp.json`, and `skills/` directory follow the Agent Plugins format used by Kiro Powers.

The server provides `get_mcp_capabilities`, `get_capabilities`, `get_command_schema`, `list_backup_vaults`, `run_security_inspector`, and `plan_context_sync`. Agents should call `get_mcp_capabilities` first because it describes only operations callable through MCP, including permissions and output contracts. Example prompts:
The server exposes the read-only resource operations listed above—including `list_sns_topics`—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 my SNS topics, subscriptions, and dead-letter queue relationships.`
- `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
3 changes: 3 additions & 0 deletions docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,15 @@ Use the registered Cobra command tree and domain catalog as the source of truth
```bash
unic capabilities --json
unic schema context sync --json
unic schema resources sns-topics --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.

Read-only automation commands live under `internal/cli/`; keep their `--json` output versioned and deterministic, write only JSON to stdout, and cover human and JSON output paths with CLI tests.

`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.

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
33 changes: 32 additions & 1 deletion internal/cli/resources.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,37 @@ type backupVaultJSON struct {
Locked bool `json:"locked"`
}

type snsTopicJSON struct {
ARN string `json:"arn"`
Name string `json:"name"`
DisplayName string `json:"display_name,omitempty"`
Region string `json:"region"`
Type string `json:"type"`
KMSMasterKeyID string `json:"kms_master_key_id,omitempty"`
DeliveryPolicy string `json:"delivery_policy,omitempty"`
EffectiveDeliveryPolicy string `json:"effective_delivery_policy,omitempty"`
SubscriptionsConfirmed int `json:"subscriptions_confirmed"`
SubscriptionsPending int `json:"subscriptions_pending"`
SubscriptionsDeleted int `json:"subscriptions_deleted"`
ContentBasedDeduplication bool `json:"content_based_deduplication"`
AttributesKnown bool `json:"attributes_known"`
Subscriptions []snsSubscriptionJSON `json:"subscriptions"`
}

type snsSubscriptionJSON struct {
ARN string `json:"arn"`
Protocol string `json:"protocol"`
Endpoint string `json:"endpoint"`
Owner string `json:"owner"`
TopicARN string `json:"topic_arn"`
Status string `json:"status"`
RawMessageDelivery bool `json:"raw_message_delivery"`
DeadLetterTargetARN string `json:"dead_letter_target_arn,omitempty"`
FilterPolicy string `json:"filter_policy,omitempty"`
FilterPolicyScope string `json:"filter_policy_scope,omitempty"`
AttributesKnown bool `json:"attributes_known"`
}

var loadBackupVaults = func(ctx context.Context) ([]awsservice.BackupVault, []error, error) {
configPath, err := config.DefaultPath()
if err != nil {
Expand All @@ -58,7 +89,7 @@ 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(newECSRolloutCmd(), newCloudTrailEventsCmd(), newELBTargetHealthCmd())
cmd.AddCommand(newECSRolloutCmd(), newCloudTrailEventsCmd(), newELBTargetHealthCmd(), newSNSTopicsCmd())
return cmd
}

Expand Down
52 changes: 52 additions & 0 deletions internal/cli/resources_operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,13 @@ var (
}
return repo.ListTargetGroupHealth(ctx, arn)
}
loadSNSTopicResources = func(ctx context.Context) ([]awsservice.SNSTopicResource, []error, error) {
repo, err := resourceRepository(ctx)
if err != nil {
return nil, nil, err
}
return repo.ListSNSTopicResources(ctx)
}
)

func writeResourceJSON(cmd *cobra.Command, data any, complete bool, warnings []string) error {
Expand Down Expand Up @@ -180,3 +187,48 @@ func newELBTargetHealthCmd() *cobra.Command {
_ = cmd.MarkFlagRequired("load-balancer")
return cmd
}

func newSNSTopicsCmd() *cobra.Command {
var jsonOutput bool
cmd := &cobra.Command{
Use: "sns-topics", Short: "List SNS topics and subscriptions as JSON", Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
if !jsonOutput {
return errors.New("this automation command supports JSON output only")
}
resources, warningErrors, err := loadSNSTopicResources(cmd.Context())
if err != nil {
return err
}
data := make([]snsTopicJSON, 0, len(resources))
for _, resource := range resources {
subscriptions := make([]snsSubscriptionJSON, 0, len(resource.Subscriptions))
for _, subscription := range resource.Subscriptions {
subscriptions = append(subscriptions, snsSubscriptionJSON{
ARN: subscription.ARN, Protocol: subscription.Protocol, Endpoint: subscription.Endpoint,
Owner: subscription.Owner, TopicARN: subscription.TopicARN, Status: subscription.Status(),
RawMessageDelivery: subscription.RawMessageDelivery, DeadLetterTargetARN: subscription.DeadLetterTargetARN(),
FilterPolicy: subscription.FilterPolicy, FilterPolicyScope: subscription.FilterPolicyScope,
AttributesKnown: subscription.AttributesKnown,
})
}
topic := resource.Topic
data = append(data, snsTopicJSON{
ARN: topic.ARN, Name: topic.Name, DisplayName: topic.DisplayName, Region: topic.Region, Type: topic.KindLabel(),
KMSMasterKeyID: topic.KMSMasterKeyID, DeliveryPolicy: topic.DeliveryPolicy, EffectiveDeliveryPolicy: topic.EffectiveDeliveryPolicy,
SubscriptionsConfirmed: topic.SubscriptionsConfirmed, SubscriptionsPending: topic.SubscriptionsPending,
SubscriptionsDeleted: topic.SubscriptionsDeleted, ContentBasedDeduplication: topic.ContentBasedDeduplication,
AttributesKnown: topic.AttributesKnown, Subscriptions: subscriptions,
})
}
warnings := make([]string, 0, len(warningErrors))
for _, warning := range warningErrors {
warnings = append(warnings, warning.Error())
}
return writeResourceJSON(cmd, data, len(warnings) == 0, warnings)
},
}
cmd.Annotations = map[string]string{annotationReadOnly: "true", annotationOutputVersion: "v1"}
cmd.Flags().BoolVar(&jsonOutput, "json", true, "Emit stable machine-readable JSON")
return cmd
}
73 changes: 73 additions & 0 deletions internal/cli/resources_operations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"testing"

awsservice "unic/internal/services/aws"
Expand Down Expand Up @@ -66,6 +67,78 @@ func TestEC2InstancesEmptyDataIsArrayAndDiscoveryIsReadOnlyV1(t *testing.T) {
}
}

func TestSNSTopicsJSONContractPreservesWarningsAndEmptyArrays(t *testing.T) {
original := loadSNSTopicResources
defer func() { loadSNSTopicResources = original }()
loadSNSTopicResources = func(context.Context) ([]awsservice.SNSTopicResource, []error, error) {
return []awsservice.SNSTopicResource{
{
Topic: awsservice.SNSTopic{
ARN: "arn:aws:sns:eu-west-1:1:orders.fifo", Name: "orders.fifo", Region: "eu-west-1",
KMSMasterKeyID: "alias/aws/sns", SubscriptionsConfirmed: 1, FIFO: true,
ContentBasedDeduplication: true, AttributesKnown: true,
},
Subscriptions: []awsservice.SNSSubscription{{
ARN: "arn:sub:orders", Protocol: "sqs", Endpoint: "arn:queue", TopicARN: "arn:aws:sns:eu-west-1:1:orders.fifo",
RedrivePolicy: `{"deadLetterTargetArn":"arn:dlq"}`, FilterPolicy: `{"event":["created"]}`,
FilterPolicyScope: "MessageBody", AttributesKnown: true,
}},
},
{Topic: awsservice.SNSTopic{ARN: "arn:aws:sns:eu-west-1:1:locked", Name: "locked", Region: "eu-west-1"}, Subscriptions: []awsservice.SNSSubscription{}},
}, []error{errors.New("failed to list subscriptions for locked")}, nil
}

cmd := NewRootCmd()
var output bytes.Buffer
cmd.SetOut(&output)
cmd.SetArgs([]string{"resources", "sns-topics", "--json"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
var result struct {
SchemaVersion string `json:"schema_version"`
Data []struct {
Name string `json:"name"`
Type string `json:"type"`
Subscriptions []struct {
Status string `json:"status"`
DeadLetterTargetARN string `json:"dead_letter_target_arn"`
FilterPolicyScope string `json:"filter_policy_scope"`
} `json:"subscriptions"`
} `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 != "orders.fifo" || result.Data[0].Type != "FIFO" ||
len(result.Data[0].Subscriptions) != 1 || result.Data[0].Subscriptions[0].Status != "confirmed" || result.Data[0].Subscriptions[0].DeadLetterTargetARN != "arn:dlq" ||
result.Data[0].Subscriptions[0].FilterPolicyScope != "MessageBody" ||
result.Data[1].Subscriptions == nil || len(result.Warnings) != 1 || result.Pagination.Complete {
t.Fatalf("unexpected result: %+v", result)
}
}

func TestSNSTopicsLoaderErrorEmitsNoEnvelope(t *testing.T) {
original := loadSNSTopicResources
defer func() { loadSNSTopicResources = original }()
wantErr := errors.New("topic lookup failed")
loadSNSTopicResources = func(context.Context) ([]awsservice.SNSTopicResource, []error, error) {
return nil, nil, wantErr
}
cmd := NewRootCmd()
var output bytes.Buffer
cmd.SetOut(&output)
cmd.SetArgs([]string{"resources", "sns-topics", "--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())
}
}

func TestCloudTrailEventsReportsCapAsIncomplete(t *testing.T) {
original := loadCloudTrailEvents
defer func() { loadCloudTrailEvents = original }()
Expand Down
2 changes: 1 addition & 1 deletion internal/mcp/agent_surface_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ var agentSurfaceByFeature = map[domain.FeatureKind]agentSurface{
domain.FeatureECSExec: {command: "ecs-rollout", tool: "get_ecs_service_rollout", arguments: json.RawMessage(`{"cluster":"cluster","service":"service"}`)},
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.FeatureSNSBrowser: {command: "sns-topics", tool: "list_sns_topics"},
}

var agentSurfaceExempt = map[domain.FeatureKind]string{
Expand Down Expand Up @@ -56,7 +57,6 @@ var agentSurfaceExempt = map[domain.FeatureKind]string{
domain.FeatureS3Browser: "object browsing needs an explicitly bounded pagination contract",
domain.FeatureSecurityGroupBrowser: "no curated security-group rule query is defined yet",
domain.FeatureSecretsBrowser: "secret values require operator-controlled reveal and copy handling",
domain.FeatureSNSBrowser: "the joined topic and subscription view has no agent contract yet",
domain.FeatureSQSBrowser: "queue mutations are confirmation-gated and no separate read-only contract exists yet",
domain.FeatureSSMParameterBrowser: "parameter values require operator-controlled reveal and copy handling",
domain.FeatureSSMSession: "starts an interactive shell session instead of returning resource data",
Expand Down
13 changes: 11 additions & 2 deletions internal/mcp/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,15 @@ var tools = []tool{
Annotations: annotations{ReadOnlyHint: true, IdempotentHint: true, OpenWorldHint: true},
Metadata: toolMetadata{RequiredPermissions: []string{"rds:DescribeDBInstances"}, OutputContract: "unic.resources.rds-instances.v1", Paginated: true},
},
{
Name: "list_sns_topics", Description: "List SNS topics with subscriptions, delivery settings, and dead-letter queue relationships.",
InputSchema: awsContextSchema(nil, nil),
Annotations: annotations{ReadOnlyHint: true, IdempotentHint: true, OpenWorldHint: true},
Metadata: toolMetadata{
RequiredPermissions: []string{"sns:ListTopics", "sns:GetTopicAttributes", "sns:ListSubscriptionsByTopic", "sns:GetSubscriptionAttributes"},
OutputContract: "unic.resources.sns-topics.v1", Paginated: true, PartialResults: true,
},
},
{
Name: "list_cloudwatch_alarms", Description: "List CloudWatch alarms with firing alarms first.",
InputSchema: awsContextSchema(nil, nil),
Expand Down Expand Up @@ -405,15 +414,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":
case "list_ec2_instances", "list_rds_instances", "list_sns_topics", "list_cloudwatch_alarms":
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"}[name]
command := map[string]string{"list_ec2_instances": "ec2-instances", "list_rds_instances": "rds-instances", "list_sns_topics": "sns-topics", "list_cloudwatch_alarms": "alarms"}[name]
return withAWSContext([]string{"resources", command, "--json"}, args.Profile, args.Region), nil
case "get_ecs_service_rollout":
var args struct {
Expand Down
1 change: 1 addition & 0 deletions internal/mcp/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ func TestReadOnlyOperationToolArgs(t *testing.T) {
want []string
}{
{"list_ec2_instances", `{"profile":"prod","region":"eu-west-1"}`, []string{"resources", "ec2-instances", "--json", "--profile", "prod", "--region", "eu-west-1"}},
{"list_sns_topics", `{"profile":"prod","region":"eu-west-1"}`, []string{"resources", "sns-topics", "--json", "--profile", "prod", "--region", "eu-west-1"}},
{"get_ecs_service_rollout", `{"cluster":"prod","service":"api"}`, []string{"resources", "ecs-rollout", "--cluster", "prod", "--service", "api", "--json"}},
{"list_cloudtrail_events", `{"since":"6h","mutations_only":true}`, []string{"resources", "cloudtrail-events", "--since", "6h", "--json", "--mutations-only"}},
{"get_elb_target_health", `{"load_balancer":"arn:lb"}`, []string{"resources", "elb-target-health", "--load-balancer", "arn:lb", "--json"}},
Expand Down
Loading
Loading