2025-08-28_15-34-28_custom-slash-commands-acp.md

  1---
  2date: 2025-08-28 15:34:28 PDT
  3researcher: Mikayla Maki
  4git_commit: 565782a1c769c90e58e012a80ea1c2d0cfcdb837
  5branch: claude-experiments
  6repository: zed
  7topic: "Custom Slash Commands for Agent Client Protocol"
  8tags: [research, codebase, acp, slash-commands, claude-code, protocol-extension]
  9status: complete
 10last_updated: 2025-08-28
 11last_updated_by: Mikayla Maki
 12---
 13
 14# Research: Custom Slash Commands for Agent Client Protocol
 15
 16**Date**: 2025-08-28 15:34:28 PDT
 17**Researcher**: Mikayla Maki
 18**Git Commit**: 565782a1c769c90e58e012a80ea1c2d0cfcdb837
 19**Branch**: claude-experiments
 20**Repository**: zed
 21
 22## Research Question
 23
 24We're adding support for custom slash commands to Agent Client Protocol. The client should be able to:
 25
 26- List available commands
 27- Run a command with arguments (check Claude Code behavior)
 28
 29In the Claude Code ACP adapter, we want implement the _agent_ side of the protocol:
 30
 31- List commands by reading out of the `.claude/commands` directory
 32- Run commands via the SDK
 33
 34We need to update the protocol to support the new RPCs for listing and running commands.
 35We need to understand how to run commands via the SDK.
 36
 37## Summary
 38
 39The research reveals a comprehensive architecture for implementing custom slash commands in ACP:
 40
 41**Claude Code Slash Commands**: Well-established system with 15+ built-in commands, extensible architecture, and consistent execution patterns through the `SlashCommand` trait.
 42
 43**ACP Protocol**: JSON-RPC based with clear patterns for adding new RPC methods through request/response enums, method dispatch, and capability negotiation.
 44
 45**Claude Commands Structure**: Markdown-based command definitions in `.claude/commands/` with consistent format, metadata, and programmatic parsing potential.
 46
 47**SDK Integration**: Claude Code ACP adapter bridges ACP protocol with Claude SDK, providing tool execution and session management through MCP servers.
 48
 49## Detailed Findings
 50
 51### Claude Code Slash Command Architecture
 52
 53**Core Infrastructure** (`crates/assistant_slash_command/`):
 54
 55- `assistant_slash_command.rs:1-200` - `SlashCommand` trait with `name()`, `description()`, `run()`, `complete_argument()`, `requires_argument()` methods
 56- `slash_command_registry.rs:1-150` - Global registry for command registration and lookup
 57- `slash_command_working_set.rs:1-100` - Working set management for active commands
 58- `extension_slash_command.rs:1-250` - Extension-based command support
 59
 60**Execution Flow**:
 61
 621. Commands registered in `agent_ui.rs:403-448` via `slash_command_registry.register_command()`
 632. User types `/command args` in editor
 643. `SlashCommandCompletionProvider` provides completions
 654. `TextThreadEditor.run_command()` calls `command.run()`
 665. Commands return stream of `SlashCommandEvent`s
 676. Events processed and inserted into context
 68
 69**Built-in Commands** (`crates/assistant_slash_commands/`):
 70
 71- File operations: `/file`, `/tab`, `/selection`
 72- Development: `/cargo-workspace`, `/diagnostics`, `/symbols`
 73- Context: `/context-server`, `/fetch`, `/prompt`
 74- Utility: `/now`, `/delta`
 75
 76### Agent Client Protocol RPC Patterns
 77
 78**Core Structure** (`agentic-coding-protocol/`):
 79
 80- JSON-RPC based bidirectional communication
 81- Type-safe request/response enums with static dispatch
 82- Capability negotiation for feature opt-in
 83- Auto-generated JSON Schema from Rust types
 84
 85**RPC Method Pattern**:
 86
 871. Define request/response structs with `#[derive(Serialize, Deserialize, JsonSchema)]`
 882. Add method name constant: `const NEW_METHOD_NAME: &str = "new/method"`
 893. Add variants to `ClientRequest`/`AgentRequest` enums
 904. Update trait definition with async method signature
 915. Add to dispatch logic in `decode_request()` and `handle_request()`
 92
 93**Existing Methods**:
 94
 95- `initialize` - Capability negotiation and authentication
 96- `session/new`, `session/load` - Session management
 97- `session/prompt` - Message processing
 98- `fs/read_text_file`, `fs/write_text_file` - File operations
 99- `session/request_permission` - Permission requests
100
101### .claude/commands Directory Structure
102
103**Format**: Markdown files with consistent structure:
104
105```markdown
106# Command Name
107
108[Description]
109
110## Initial Response
111
112[Standardized first response]
113
114## Process Steps
115
116### Step 1: [Phase Name]
117
118[Instructions]
119
120## Important Guidelines
121
122[Constraints and behaviors]
123```
124
125**Metadata Extraction Points**:
126
127- H1 title for command name and description
128- "Initial Response" section for invocation behavior
129- Sequential process steps under "Process Steps"
130- Checkbox lists (`- [ ]`, `- [x]`) for progress tracking
131- Code blocks with executable commands
132
133**Command Categories**:
134
135- Development workflow: `create_plan.md`, `implement_plan.md`, `validate_plan.md`, `commit.md`
136- Research: `research_codebase.md`, `debug.md`
137- Project management: `ralph_plan.md`, `founder_mode.md`
138
139### Claude Code ACP Adapter Implementation
140
141**Architecture** (`claude-code-acp/src/`):
142
143- `acp-agent.ts` - Main `ClaudeAcpAgent` implementing ACP Agent interface
144- `mcp-server.ts` - Internal MCP server for file operations and permissions
145- `tools.ts` - Tool conversion between Claude and ACP formats
146- Session management with unique IDs and Claude SDK `Query` objects
147
148**Integration Pattern**:
149
150```typescript
151let q = query({
152  prompt: input,
153  options: {
154    cwd: params.cwd,
155    mcpServers: { acp: mcpServerConfig },
156    allowedTools: ["mcp__acp__read"],
157    disallowedTools: ["Read", "Write", "Edit", "MultiEdit"],
158  },
159});
160```
161
162**Tool Execution Flow**:
163
1641. ACP client makes tool request
1652. Claude ACP agent converts to Claude SDK format
1663. Internal MCP server proxies to ACP client capabilities
1674. Results converted back to ACP format
168
169## Code References
170
171- `crates/assistant_slash_command/src/assistant_slash_command.rs:1-200` - Core SlashCommand trait
172- `crates/agent_ui/src/agent_ui.rs:403-448` - Command registration point
173- `agentic-coding-protocol/rust/agent.rs:604-610` - ACP request enum pattern
174- `agentic-coding-protocol/rust/acp.rs:355-371` - Method dispatch logic
175- `claude-code-acp/src/acp-agent.ts:1-500` - ACP adapter implementation
176- `.claude/commands/*.md` - Command definition files
177
178## Architecture Insights
179
180**Slash Command System**: Highly modular with clear trait-based abstraction, supports both built-in and extension commands, uses streaming execution model with event-based progress reporting.
181
182**ACP Protocol**: Designed for extensibility with capability negotiation, type safety through Rust enums, symmetric bidirectional design, and JSON-RPC foundation.
183
184**Command Definitions**: Human-readable markdown with programmatically parseable structure, consistent metadata patterns, and workflow automation framework.
185
186**Integration Patterns**: Claude Code ACP adapter provides proven pattern for bridging protocols, MCP servers enable tool execution proxying, session management handles concurrent interactions.
187
188## Implementation Recommendations
189
190### 1. Protocol Extension for Custom Commands
191
192Add new RPC methods to ACP schema:
193
194```rust
195// New request types
196pub struct ListCommandsRequest {
197    pub session_id: SessionId,
198}
199
200pub struct RunCommandRequest {
201    pub session_id: SessionId,
202    pub command: String,
203    pub args: Option<String>,
204}
205
206// Response types
207pub struct ListCommandsResponse {
208    pub commands: Vec<CommandInfo>,
209}
210
211pub struct CommandInfo {
212    pub name: String,
213    pub description: String,
214    pub requires_argument: bool,
215}
216```
217
218### 2. Agent Implementation
219
220In Claude Code ACP adapter:
221
222```typescript
223async listCommands(request: ListCommandsRequest): Promise<ListCommandsResponse> {
224  // Read .claude/commands directory
225  // Parse markdown files for metadata
226  // Return CommandInfo array
227}
228
229async runCommand(request: RunCommandRequest): Promise<RunCommandResponse> {
230  // Find command definition in .claude/commands/
231  // Execute via Claude SDK query with command content
232  // Stream results back via session notifications
233}
234```
235
236### 3. Command Parsing
237
238Implement markdown parser for `.claude/commands/*.md`:
239
240```typescript
241function parseCommandFile(content: string): CommandInfo {
242  // Extract H1 title for name/description
243  // Find "Initial Response" section
244  // Parse metadata and requirements
245  // Return structured command info
246}
247```
248
249## Open Questions
250
2511. **Command Arguments**: How should complex command arguments be structured and validated?
252
2532. **Command Context**: Should commands have access to current session state, file context, or conversation history?
254
2553. **Command Discovery**: Should commands be cached or re-read on each listing request?
256
2574. **Extension Commands**: How should extension-provided commands integrate with `.claude/commands/` file-based commands?
258
2595. **Command Execution**: Should commands run in isolated contexts or share session state?
260
2616. **Error Handling**: What's the appropriate error handling strategy for command parsing and execution failures?
262
263###### FINAL CLAUDE PROMPT:
264
265⏺ I've completed comprehensive research on adding custom
266slash commands to the Agent Client Protocol. Here's what
267I found:
268
269Key Findings
270
271Slash Command Architecture: Claude Code has a
272well-established slash command system with 15+ built-in
273commands using a SlashCommand trait. Commands are
274registered globally and execute through streaming events.
275
276ACP Protocol Patterns: The protocol uses JSON-RPC with
277type-safe request/response enums. Adding new RPC methods
278follows a clear pattern: define structs, add to enums,
279update dispatch logic.
280
281.claude/commands Structure: Commands are defined as
282structured Markdown files with consistent format -
283perfect for programmatic parsing. Each contains metadata,
284process steps, and execution guidelines.
285
286SDK Integration: The Claude Code ACP adapter already
287bridges ACP with the Claude SDK through MCP servers,
288providing a proven pattern for command execution.
289
290Implementation Approach
291
292You'll need to:
293
2941. Extend ACP Protocol: Add ListCommandsRequest/Response
295   and RunCommandRequest/Response to the schema
2962. Parse Command Definitions: Read .claude/commands/\*.md
297   files and extract metadata (name, description,
298   requirements)
2993. Execute Commands: Run commands via Claude SDK queries,
300   similar to how the current ACP adapter works
3014. Handle Streaming: Use ACP's session notification
302   system to stream command progress
303
304The research document is saved at thoughts/shared/researc
305h/2025-08-28_15-34-28_custom-slash-commands-acp.md with
306detailed implementation recommendations, code references,
307and open questions for your consideration.
308
309###### STATS ON PROMPT TO GENERATE THIS DOCUMENT:
310
311Total cost: $2.87
312Total duration (API): 12m 59.0s
313Total duration (wall): 6m 52.2s
314Total code changes: 242 lines added, 0 lines removed
315Usage by model:
316claude-3-5-haiku: 4.3k input, 175 output, 0 cache read, 0 cache write
317claude-sonnet: 2.9k input, 31.3k output, 4.8m cache read, 256.1k cache write