CC-203: Plugin Architecture Advanced

Listen instead
CC-203 Plugin Architecture Advanced
0:00

Beyond the Basics

This module covers advanced plugin architecture patterns for developers who have mastered the fundamentals from CC-201 and CC-201b. We will explore MCP server integration, plugin settings management, inter-plugin communication, advanced skill design, agent development best practices, and distribution strategies for production-grade plugins.

Official Documentation: Advanced plugin patterns build on the Claude Code Plugins documentation. Refer to it for the latest API surface and configuration schema.

MCP Server Integration in Plugins

Plugins can bundle MCP (Model Context Protocol) server configurations, giving Claude access to external tools and data sources. The .mcp.json file within a plugin directory declares MCP servers that should be started when the plugin loads.

// .claude/plugins/my-plugin/.mcp.json
{
  "mcpServers": {
    "database-explorer": {
      "command": "node",
      "args": ["${CLAUDE_PLUGIN_ROOT}/mcp-servers/db-explorer/index.js"],
      "env": {
        "DB_CONNECTION_STRING": "${DB_URL}"
      }
    },
    "jira-integration": {
      "command": "npx",
      "args": ["-y", "@company/jira-mcp-server"],
      "env": {
        "JIRA_BASE_URL": "${JIRA_URL}",
        "JIRA_TOKEN": "${JIRA_API_TOKEN}"
      }
    }
  }
}

Key patterns for MCP integration in plugins:

  • Use ${CLAUDE_PLUGIN_ROOT} for bundled servers. If your plugin ships an MCP server, reference it with the plugin root variable to keep paths portable.
  • Use environment variables for secrets. Never hardcode API keys, tokens, or connection strings in the .mcp.json file. Reference environment variables that the user sets in their shell profile or .env file.
  • Scope servers to the plugin's purpose. A plugin focused on database workflows should only declare database-related MCP servers, not bundle unrelated integrations.
  • Document required environment variables. Users need to know which variables to set before the plugin's MCP servers will function.

Plugin Settings Management

Plugins often need user-configurable settings: API endpoints, default behaviors, feature flags, or team-specific values. The .local.md pattern provides a clean approach to plugin settings using a Markdown file with YAML frontmatter.

# .claude/plugins/my-plugin/.local.md
---
settings:
  default_branch: main
  review_depth: thorough
  auto_format: true
  test_framework: vitest
  max_file_size_kb: 500
  excluded_paths:
    - node_modules
    - dist
    - .next
    - coverage
---

# Plugin Local Configuration

This file contains user-specific settings for the my-plugin plugin.
Settings in the YAML frontmatter above are loaded at plugin initialization
and available to all plugin components.

## How to Customize

Edit the `settings` block above to change plugin behavior:

- **default_branch**: The branch name used as the base for comparisons
- **review_depth**: "quick", "standard", or "thorough"
- **auto_format**: Whether to run formatters after file modifications
- **test_framework**: Testing framework used in this project
- **max_file_size_kb**: Skip files larger than this for analysis
- **excluded_paths**: Directories to ignore during scans

The .local.md file should be listed in .gitignore since it contains user-specific settings. Ship a .local.md.example template with your plugin so users know what settings are available.

Plugin skills and hooks reference these settings by reading the file at ${CLAUDE_PLUGIN_ROOT}/.local.md and parsing the YAML frontmatter. This keeps configuration separate from logic and makes plugins adaptable without modifying component files.

Inter-Plugin Communication

As your plugin ecosystem grows, you may need plugins to communicate with each other. Claude Code does not provide a direct inter-plugin messaging API, but there are effective patterns for achieving coordination:

Shared File Protocol

Plugins can communicate through a shared directory, writing and reading structured files that other plugins consume.

# Plugin A: Security Scanner writes findings
# ${CLAUDE_PLUGIN_ROOT}/../../shared/security-findings.json

# Plugin B: Report Generator reads findings and includes them
# Read from: ~/.claude/plugins/shared/security-findings.json

Convention-Based Coordination

Plugins can establish conventions where one plugin's output becomes another's input. For example, a code-analysis plugin might write findings in a standard format that a reporting plugin knows how to consume. The key is documenting the data contract between plugins.

---
name: analysis-report
description: "Generates reports from standardized analysis output files"
when-to-use: "When the user asks for a project report or analysis summary"
---

# Analysis Report Generator

## Data Sources

Check for analysis output files in the project root:
- `.claude-analysis/security.json` - from security-scanner plugin
- `.claude-analysis/deps.json` - from dep-analyzer plugin
- `.claude-analysis/coverage.json` - from test-coverage plugin

For each file that exists, incorporate its findings into the report.
Skip any missing files gracefully.

Hook-Based Coordination

A plugin can use hooks to trigger behavior that another plugin's skills pick up. For example, a PostToolUse hook in Plugin A could write a marker file that a skill in Plugin B detects and acts on during its next invocation.

Advanced Skill Design

Progressive Disclosure

Complex skills should not dump all their output at once. Design skills that start with a summary and progressively reveal detail on request.

---
name: architecture-review
description: "Multi-level architecture review of the codebase"
when-to-use: "When the user asks for an architecture review, system design review, or structural analysis"
---

# Architecture Review Skill

## Phase 1: High-Level Overview (always run first)

1. Identify the project type and primary framework
2. Map the top-level directory structure
3. Count files by type and identify the dominant language
4. Present a 5-bullet summary of the architecture

Ask the user: "Would you like me to deep-dive into any specific area?"

## Phase 2: Component Analysis (on request)

For each major directory/module:
1. Identify its responsibility
2. Map its dependencies (imports)
3. Assess coupling with other modules
4. Flag any circular dependencies

## Phase 3: Detailed Findings (on request)

For each flagged issue from Phase 2:
1. Provide specific file paths and line numbers
2. Explain the architectural concern
3. Suggest a concrete refactoring approach
4. Estimate the effort level (low/medium/high)

Multi-Step Workflows

Some skills need to execute a sequence of distinct steps, with each step building on the results of the previous one. Structure these as numbered phases with clear inputs and outputs.

---
name: database-migration
description: "End-to-end database migration workflow"
when-to-use: "When the user asks to create, plan, or execute a database migration"
---

# Database Migration Workflow

## Step 1: Schema Diff
Read the current schema from the ORM/migration files.
Compare against the requested changes.
Output: List of required schema changes.

## Step 2: Migration File Generation
Generate migration file(s) using the project's migration tool.
Include both UP and DOWN migrations.
Output: Migration file path(s).

## Step 3: Validation
Dry-run the migration if the tool supports it.
Check for data loss risks (column drops, type changes).
Output: Validation report with warnings.

## Step 4: Execution (requires explicit user confirmation)
STOP and ask the user to confirm before proceeding.
Only execute if the user explicitly says "run it" or "execute".
Output: Migration result and updated schema state.

IMPORTANT: Never proceed from Step 3 to Step 4 without explicit
user confirmation. Data migrations are irreversible.

Agent Development Best Practices

Triggering Conditions

Well-designed agents activate only when their specialization is genuinely needed. Define triggering conditions that are specific enough to avoid false activations but broad enough to catch legitimate use cases.

---
name: api-designer
description: "Specialized agent for RESTful API design and documentation"
system-prompt: |
  You are an API design specialist following REST best practices.
  You focus exclusively on:
  - Resource naming and URL structure
  - HTTP method selection
  - Request/response payload design
  - Status code usage
  - Pagination, filtering, and sorting patterns
  - OpenAPI/Swagger specification generation

  You do NOT implement the API. You design and document it.
  Hand off implementation to the main agent.
allowed-tools:
  - Read
  - Write
  - Grep
  - Glob
---

# API Designer Agent

## When to Spawn This Agent

Spawn when the user:
- Asks to design a new API or set of endpoints
- Wants to review existing API design for consistency
- Needs OpenAPI/Swagger documentation generated
- Asks about REST best practices for a specific use case

## When NOT to Spawn

Do NOT spawn for:
- Implementing API route handlers (that's coding, not design)
- Debugging existing API errors
- Database schema design (use the schema-designer agent instead)
- Frontend API client code

Tool Restrictions and Isolation

Agent tool restrictions serve two purposes: security (preventing unintended side effects) and focus (keeping the agent on task). Follow the principle of least privilege:

  • Read-only agents (analysis, review): Read, Grep, Glob only.
  • Write agents (generation, refactoring): Add Write, Edit.
  • Full agents (testing, deployment): Add Bash only when the agent genuinely needs to execute commands.
  • Never give agents tools they do not need. A documentation agent does not need Bash. A test runner does not need Write (it reads tests and runs them, it should not modify source code).

Subagent Patterns

Complex workflows can chain multiple agents. The main agent acts as an orchestrator, spawning specialized subagents for distinct phases of the work.

# Main skill orchestrates the workflow:

## Phase 1: Analysis
Spawn the `code-analyzer` agent to assess the current codebase.
Collect its findings.

## Phase 2: Design
Spawn the `api-designer` agent with the analyzer's findings.
Get the proposed API design.

## Phase 3: Implementation
Return to the main agent context with the design.
Implement the API routes according to the design document.

## Phase 4: Testing
Spawn the `test-writer` agent with the implemented routes.
Generate comprehensive tests.

Plugin Distribution and Versioning

Versioning Strategy

Follow semantic versioning strictly for plugins:

  • MAJOR (2.0.0) — Breaking changes to skill behavior, command arguments, or hook contracts. Users must review and potentially update their workflows.
  • MINOR (1.1.0) — New skills, commands, or agents added. Existing components unchanged. Safe to update.
  • PATCH (1.0.1) — Bug fixes, improved when-to-use descriptions, typo corrections. Always safe to update.

Distribution Channels

# Git-based distribution (recommended)
# Users install:
git clone https://github.com/org/plugin-name.git ~/.claude/plugins/plugin-name

# Update:
cd ~/.claude/plugins/plugin-name && git pull

# Pin to a specific version:
cd ~/.claude/plugins/plugin-name && git checkout v1.2.0

Plugin README Template

Every distributed plugin should include a README with these sections:

  • Overview — What the plugin does and who it is for.
  • Installation — Exact commands to install the plugin.
  • Requirements — Environment variables, MCP servers, or dependencies needed.
  • Components — List of skills, commands, agents, and hooks with brief descriptions.
  • Configuration — How to customize via .local.md or environment variables.
  • Changelog — Version history with breaking change notices.

Testing Before Release

Before distributing a new plugin version, run through this checklist:

  1. Fresh install: Clone the plugin into a clean ~/.claude/plugins/ directory and verify it loads.
  2. Component test: Invoke every skill, command, and agent to verify functionality.
  3. Hook test: Trigger every hook event and verify the expected behavior.
  4. Missing config: Test with no .local.md file to verify graceful defaults.
  5. MCP servers: If the plugin bundles MCP servers, verify they start and respond correctly.
  6. Conflict test: Install alongside other common plugins and verify no name collisions.

Production Plugin Architecture

Putting it all together, here is a production-grade plugin structure that incorporates all the advanced patterns covered in this module:

~/.claude/plugins/enterprise-toolkit/
  plugin.json                    # Manifest with all components
  .mcp.json                      # MCP server declarations
  .local.md.example              # Settings template
  .local.md                      # User settings (gitignored)
  README.md                      # Installation and usage docs
  CHANGELOG.md                   # Version history

  skills/
    architecture-review.md       # Progressive disclosure pattern
    database-migration.md        # Multi-step workflow pattern
    dependency-audit.md          # Standard analysis skill

  commands/
    deploy.md                    # Deployment command with args
    report.md                    # Report generation command

  agents/
    api-designer.md              # Read-only design agent
    test-writer.md               # Write-capable test agent
    security-scanner.md          # Read-only security agent

  hooks/
    security-guard.md            # PreToolUse blocking hook
    audit-logger.md              # PostToolUse logging hook
    context-loader.md            # SessionStart context injection

  mcp-servers/
    db-explorer/
      index.js                   # Bundled MCP server
      package.json

  templates/
    report-template.md           # Templates referenced by skills
    migration-template.sql

Key Takeaways

  • Bundle MCP servers in plugins via .mcp.json with ${CLAUDE_PLUGIN_ROOT} for portable paths.
  • Use .local.md with YAML frontmatter for user-configurable plugin settings.
  • Inter-plugin communication uses shared file protocols, convention-based data contracts, or hook-based coordination.
  • Design skills with progressive disclosure for complex analyses and explicit confirmation gates for destructive operations.
  • Restrict agent tools to the minimum required set following the principle of least privilege.
  • Version plugins semantically and distribute via Git with tagged releases.
  • Test every component path before releasing a new version.