# Diplomatic Networks: MCP, Hooks, Plugins, and Skills

Claude Code's extension ecosystem is built from four complementary mechanisms—MCP (standardized tool integration), Hooks (lifecycle event interception), the plugin system (third-party feature packs), and Skills (AI-autonomously triggered capabilities). This chapter analyzes the design boundaries, security models, and collaboration patterns of these four mechanisms from an architectural perspective, and examines the core tension between extensibility and security.

> **Source locations**: `src/services/mcp/` (23 files), `src/utils/hooks.ts` + `src/utils/hooks/` (event system), `src/utils/plugins/` (44 files), `src/skills/` (skill loading)

---

## 🌍 Industry Context: The Extension Ecosystem Is the Most Fiercely Contested Battleground for AI Agents

The extension ecosystem—enabling AI Agents to connect with external tools, respond to lifecycle events, and load third-party capabilities—is currently the most white-hot competitive arena in AI programming tools. To understand Claude Code's extension design, one must first see the full industry picture:

**MCP is not a Claude Code invention, but an open standard launched by Anthropic.** Anthropic released MCP (Model Context Protocol) in November 2024, with the goal of becoming the "USB standard" for AI Agents connecting to external tools. Key fact: MCP is not used exclusively by Claude Code—Cursor, Windsurf, Zed, Cline, Continue, and other mainstream AI coding tools have all announced MCP support. This means tools in the MCP ecosystem can be reused across products; write an MCP Server once, and every MCP-supported client can use it.

**VS Code Extension API vs. Claude Code Hooks: two fundamentally different philosophies of extension.** VS Code's Extension API is "GUI-first"—extensions can add panels, menus, decorators, and language services. Claude Code's Hooks system is "AI pipeline-first"—extensions intercept internal AI Agent events such as pre/post tool use, permission checks, and context compression. This Hook design oriented around the Agent lifecycle is almost unique to Claude Code in the industry.

**LangChain Tool abstraction vs. MCP standardized approach.** LangChain proposed the Tool abstraction (function signature + description) early on, but it is a framework-level solution—tied to the LangChain runtime. MCP's ambition is larger: it is a protocol-level solution—defining an inter-process communication standard (JSON-RPC over stdio/HTTP), not tied to any framework or language. This is the fundamental difference between "library vs. protocol."

**Within the scope of this research, Claude Code's leading extension capabilities:**
- **27 Hook events + exit code 2 blocking semantics**—among the AI coding tools surveyed, no equivalent fine-grained Agent lifecycle interception mechanism exists
- **Skill's `whenToUse` autonomous scheduling**—the AI itself judges when to trigger a capability, rather than the user explicitly invoking it
- **Four-mechanism combined architecture** (MCP + Hooks + Plugins + Skills)—most competing products only implement one or two of these
- **Channel Permission Relay remote approval**—a cross-device permission confirmation flow

### MCP Ecosystem Competitor Comparison

| Product | MCP Support | Proprietary Extension Mechanism | Lifecycle Hooks | AI-Autonomous Triggering | Remote Approval |
|------|---------|------------|-------------|--------------|---------|
| **Claude Code** | ✅ Launch support, multi-transport | Hooks + Plugins + Skills | ✅ 27 events | ✅ Skills (whenToUse) | ✅ Channel Relay |
| **Cursor** | ✅ Deep support | .cursor/rules/ (.mdc conditional rule engine) | ❌ | ❌ | ❌ |
| **Windsurf** | ✅ Deep support | Cascade Engine (cascading continuous observation) | ❌ | Partial (within Flows) | ❌ |
| **Zed** | ✅ MCP support | Extension API (WASM) | ❌ | ❌ | ❌ |
| **Cline** | ✅ Deep support | Custom instructions + native subagents (v3.58+) | ❌ | ❌ | ❌ |
| **Continue** | ✅ Deep support | Compliance approval workflow + CI/CD gate enforcement | Partial | ❌ | ❌ |
| **GitHub Copilot** | ✅ Native GitHub registry | VS Code Extension API + Agent Mode GA | Via VS Code events | Explore/Plan/Task agents | ❌ |
| **CodeX (OpenAI)** | ✅ Deep (SSE/Stdio) | Open-source skill library (Figma/Linear native integrations) | ❌ | ❌ | ❌ |
| **OpenCode** | ✅ Declarative extensions | YAML deep customization + 75+ model providers | ❌ | ❌ | ❌ |
| **GLM (Z.ai)** | Open platform API | Z Code platform (localized knowledge-base engine) | ❌ | ❌ | ❌ |

> **Key takeaways from the table**: MCP has become a de facto standard (most products support it), but Claude Code's three-layer stack on top of MCP (Hooks + Plugins + Skills) is distinctive. In particular, the Hook system's exit code 2 blocking semantics and Skill's AI-autonomous scheduling have no equivalent designs among competitors.

---

## Prelude: Embassies, Customs, and Free-Trade Zones

For a nation to interact with the outside world, it needs three things: **embassies** (standard diplomatic channels), **customs** (import/export controls), and **free-trade zones** (where selected external entities can operate inside the country).

Claude Code's extension ecosystem is exactly these three things:
- **MCP** (Model Context Protocol) = the embassy—a standardized protocol for external tool access
- **Hooks** = customs—inspecting and controlling data at key ingress/egress points
- **Plugins + Skills** = the free-trade zone—where third-party capabilities run inside the system

> **🔑 OS Analogy:** MCP = your phone's Bluetooth/USB port (the standard way to connect external devices), Hooks = your phone's "automated shortcuts" (triggering preset actions at specific moments), Plugins = apps downloaded from the App Store (feature packs developed by others), Skills = screen-recorded macros you made yourself (custom automation scripts).
>
> 💡 **Plain English**: The extension ecosystem is like installing apps on your phone—MCP is the **USB adapter** (letting Claude connect to all kinds of external devices and services); Hooks are the **SMS notifications from your package locker** (the system automatically triggers your preset actions at critical moments); Plugins are **App Store app packages** (one-click installation of a whole feature set); Skills are **shortcuts on your phone** (the AI itself decides which one to use and when).

---

## 1. MCP: The Standardized External Tool Protocol

### 1.1 What Is MCP

MCP (Model Context Protocol) is an **open protocol standard** released by Anthropic in November 2024 (not a Claude Code exclusive). It allows any external server to register tools with an MCP-supported client. Claude Code is one of the launch client implementations, but Cursor, Windsurf, Zed, and other products support it too. Just as the USB protocol lets devices from any manufacturer plug into any computer—MCP's goal is to become the USB standard of the AI Agent world.

> 📚 **Course Connection**: MCP = **operating system device-driver interface / USB standard**. An OS uses standard driver interfaces (like USB) to let printers, keyboards, and cameras plug and play; MCP uses a standard protocol to let databases, APIs, and filesystems plug and play into an AI Agent. Write the driver once (MCP Server), and every OS (MCP client) can use it.

### 1.2 Scale

`src/services/mcp/`: 23 files. The source `TransportSchema` defines **6 transport protocols**, plus 2 internal-only configuration types:

**User-configurable transport protocols (4 core types):**

| Transport | Description |
|---------|------|
| `stdio` | Local subprocess communication (most common) 📚 = Unix pipe |
| `sse` | HTTP Server-Sent Events, server push |
| `http` | HTTP Streamable streaming transport |
| `ws` | WebSocket bidirectional real-time communication |

**Internal-only types (not directly configured by users):**

| Type | Description |
|------|------|
| `sse-ide` | SSE connection for IDE extensions |
| `ws-ide` | WebSocket connection for IDE extensions |
| `sdk` | Internal SDK communication |
| `claudeai-proxy` | Claude.ai proxy server (appears only in status responses) |

> **Common confusion**: `npx`, `uvx`, and `docker` are not transport protocols—they are **launch methods** for an MCP Server, and all use `stdio` underneath. For example, `"command": "npx", "args": ["-y", "@some/mcp-server"]` merely specifies starting the server process with npx; communication still goes through a stdio pipe.

### 1.3 The Status of MCP Tools in the System

MCP tools appear in the tool list as `mcp__serverName__toolName`. From `queryLoop`'s perspective, they travel the exact same pipeline as built-in tools—input validation, permission checks, execution, and result serialization.

**But there is one critical difference**: MCP tool execution happens in an external process/server. This means:
- Execution time is unpredictable (network latency)
- Result content is uncontrollable (may contain malicious content)
- The server may disconnect at any time

### 1.4 Channel Permission Relay

This is the most interesting security mechanism in the MCP system. When Claude Code runs remotely (via Bridge), permission confirmations must be relayed back to the user. Channel Permission Relay sends approval requests over Telegram/iMessage, and the user approves or denies from their phone.

Approval codes use a **5-letter ID** (25-letter alphabet + profanity filter)—ensuring the ID cannot spell an offensive word.

---

## 2. Hooks: Custom Logic at 27 Critical Nodes

### 2.1 What Is a Hook

A Hook is a mechanism for executing user-defined logic at specific moments in the system lifecycle. A Hook is not just a Shell command—it can also be an LLM prompt, an HTTP request, or a standalone Agent validator (see section 2.4). Unlike tools, **the AI does not call Hooks; the system triggers them automatically**.

> 📚 **Course Connection**: Hooks = **operating-system interrupt service routines (ISR)**. While the CPU executes the main program, a hardware interrupt (keypress, disk read complete) pauses the current flow, jumps to the pre-registered interrupt handler, and returns when done. Claude Code's Hook mechanism works exactly the same: as the AI Agent executes its main flow (tool use, permission checks), the system automatically jumps to the user-registered handler (Shell command, LLM prompt, HTTP request, or Agent validator) at 27 predefined interrupt points, then returns to the main flow. Exit code 2 is equivalent to the interrupt handler returning "deny service"—directly blocking the main flow from continuing.

### 2.2 The 27 Events

The source `HOOK_EVENTS` array (`src/entrypoints/sdk/coreSchemas.ts`) defines all 27 events, categorized by lifecycle as follows:

| Lifecycle | Event | Timing |
|---------|------|------|
| Tool use | `PreToolUse` | Before tool invocation |
| | `PostToolUse` | After tool invocation (success) |
| | `PostToolUseFailure` | After tool invocation (failure) |
| Conversation flow | `Stop` | AI finishes the current turn |
| | `StopFailure` | AI response terminates abnormally |
| | `UserPromptSubmit` | When the user submits a prompt |
| | `Notification` | System notification |
| Permissions | `PermissionRequest` | When a permission request occurs |
| | `PermissionDenied` | When permission is denied |
| Context | `PreCompact` | Before context compression |
| | `PostCompact` | After context compression |
| Session lifecycle | `SessionStart` | Session starts |
| | `SessionEnd` | Session ends |
| | `Setup` | Initialization setup |
| Subagent | `SubagentStart` | Subagent starts |
| | `SubagentStop` | Subagent stops |
| Tasks | `TaskCreated` | Task created |
| | `TaskCompleted` | Task completed |
| | `TeammateIdle` | Teammate idle |
| Config & environment | `ConfigChange` | Configuration changed |
| | `CwdChanged` | Working directory changed |
| | `FileChanged` | File changed |
| | `InstructionsLoaded` | Instructions loaded |
| Worktree | `WorktreeCreate` | Worktree created |
| | `WorktreeRemove` | Worktree removed |
| Interaction | `Elicitation` | Information elicitation request |
| | `ElicitationResult` | Information elicitation result |

### 2.3 Dual-Track Exit Codes

Hook exit codes carry special semantics:

| Exit Code | Meaning |
|--------|------|
| 0 | Success, continue |
| 2 | **Block**—stop the current operation |
| Other non-zero | Failure, but do not block (log only) |

The special meaning of exit code 2 is a key design choice—it allows Hooks to **intercept** operations, not merely observe them. For example, a `PreToolUse` Hook can inspect whether a Bash command contains dangerous operations and return 2 to block execution.

### 2.4 Four Hook Types

Hooks are not limited to Shell commands. The source distinguishes four Hook types via a `type` field (`HookCommandSchema` in `src/schemas/hooks.ts`), which is a genuine innovation:

| Type | `type` value | Behavior | Key Fields |
|------|----------|------|---------|
| **Shell command** | `command` | Execute a Shell command (most common) | `command` (command string) |
| **LLM prompt** | `prompt` | Invoke an LLM to evaluate a prompt, using AI to judge | `prompt` (prompt text), `model` (optional model) |
| **HTTP request** | `http` | Send a POST request to a specified URL | `url`, `headers`, `allowedEnvVars` |
| **Agent validator** | `agent` | Launch a subagent to perform validation | `prompt` (validation goal description), `model` |

> **Why does this matter?** Most Hook systems only support Shell commands. Claude Code's `prompt` type lets a Hook **invoke an LLM for judgment** (e.g., "does this change conform to code style guidelines?"), and the `agent` type goes further—launching a full validation Agent to review the operation. This means Hook judgment is not limited to script logic; it can harness AI reasoning.

Asynchronous control is achieved via two boolean fields, `async` (run in the background, non-blocking) and `asyncRewake` (run in the background, but wake the model on exit code 2), rather than via separate execution types.

---

## 3. Plugin System: Third-Party Feature Packs

### 3.1 What Plugins Can Do

A plugin can contain:
- New tools
- New Skills
- New Hooks
- New MCP server configurations
- New commands

### 3.2 Security Safeguards

The plugin system has three layers of security:
1. **Whitelist**: Only approved plugins may be installed
2. **Regex validation**: Plugin names and source URLs must match safe patterns
3. **Homoglyph protection**: Prevents using visually similar Unicode characters to spoof plugin names (e.g., Cyrillic `а` masquerading as Latin `a`)

> 📚 **Course Connection**: Plugin trust chain = **PKI certificate chain (Public Key Infrastructure)**. A browser trusts an HTTPS website through a certificate chain: root CA → intermediate CA → site certificate. Claude Code trusts a plugin through a similar chain: Anthropic official whitelist → plugin name regex validation → homoglyph detection. If any link breaks (unapproved, name mismatch, spoofed character detected), the trust chain is broken and the plugin is rejected. Like PKI, this is a zero-trust model of "deny by default, validate at every step."

### 3.3 `strictPluginOnlyCustomization`

Enterprise admins can enable this setting: only enterprise-policy-specified plugins are allowed. Users cannot install or configure plugins on their own.

---

## 4. Skills: Capabilities the AI Can Trigger Autonomously

### 4.1 Skill vs. Command

| | Command | Skill |
|--|--------|------|
| **Trigger method** | User types `/xxx` | AI decides autonomously to invoke |
| **Triggerer** | Only the user | Can be the AI |
| **Key field** | — | `whenToUse`: describes when this Skill should be used |
| **Source** | Built into the system | Built-in + user-defined + plugin-provided |

### 4.2 The `whenToUse` Field

This is the most essential difference between a Skill and a Command. A Skill has a `whenToUse` description, placed in the system prompt:

```
Skill: commit
whenToUse: "When the user asks you to create a git commit"
```

When the AI generates a response and sees this description, it invokes the Skill proactively if the current scenario matches. **The AI becomes the Skill scheduler**—no explicit user trigger is required.

---

## 5. How the Four Extension Mechanisms Collaborate

These four mechanisms are not isolated—they collaborate to form a complete extension ecosystem:

```
User scenario: "I want Claude Code to automatically run lint before every commit"

Combined solution:
  1. MCP server → provides the lint tool
  2. Hook (PreToolUse on Bash(git commit *)) → triggers before commit
  3. Skill (lint) → AI can autonomously decide when to run lint
  4. Plugin → packages all of the above into an installable bundle
```

```
User scenario: "My enterprise requires all code changes to pass security scanning"

Combined solution:
  1. Enterprise policy → mandates installation of the security-scanning plugin
  2. Hook (PostToolUse on Edit/Write) → automatically scans after modifications
  3. MCP server → connects to the enterprise security-scanning service
  4. strictPluginOnlyCustomization → users cannot disable these
```

---

## 6. Design Trade-Offs

### Strengths

1. **Embracing the MCP open standard** (rather than inventing a proprietary protocol) lets Claude Code directly reuse tools from the entire MCP ecosystem—Anthropic drives the standard, Claude Code benefits first, but the ecosystem dividends spill over to all MCP clients
2. **Hook exit code 2 blocking semantics** let user-defined security checks intercept operations—not just log them
3. **Skill's `whenToUse` makes the AI the scheduler**—shifting from "the user tells the AI what to do" to "the AI knows when to do what"
4. **Homoglyph protection** shows the team seriously considered supply-chain attacks—not a theoretical threat, as Unicode homoglyph attacks have been exploited in the npm ecosystem
5. **The four mechanisms can be combined**—they are not mutually exclusive, but complementary

### Costs and Limitations

1. **MCP's multiple transport protocols and launch methods** increase connection-debugging complexity—a "why won't it connect" issue may require distinguishing between transport layer (stdio/sse/http/ws) and launch method (npx/docker/uvx) problems
2. **27 Hook events** carry high documentation-maintenance costs—users need to know which event to tap into to achieve their goal. Injecting into the wrong event can cause unexpected failures
3. **Hook execution of user-defined logic** (Shell commands, LLM prompts, HTTP requests, Agents) carries security risks—a malicious Hook can read all conversation content. This is the core trade-off between extensibility and security
4. **The plugin whitelist model** limits openness—unapproved plugins cannot be used, but this is an intentional choice under security boundary conditions
5. **Skill autonomous triggering** can lead to unexpected behavior—the AI may invoke a Skill at an inappropriate time, so one must be wary of overly broad `whenToUse` descriptions

---

## Code Landmarks

- `src/services/mcp/MCPConnectionManager.tsx`: MCP connection manager—the unified abstraction layer over multiple transport protocols
- `src/services/mcp/types.ts`: `TransportSchema` definitions—stdio, sse, http, ws, and other transport protocol types
- `src/utils/hooks.ts`: Hook event system core—execution entry points for all 27 events such as `executePreToolHooks()`, `executeStopHooks()`
- `src/schemas/hooks.ts`: Hook type definitions—`HookCommandSchema` discriminated union of the four types (command/prompt/http/agent)
- `src/utils/plugins/schemas.ts`: Official Marketplace name whitelist and spoofing-detection regexes
- `src/skills/loadSkillsDir.ts`: Skill loader—parses the `whenToUse` field from `.md` files
