spacehub

surshar / claude-code

Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster by executing routine tasks, explaining complex code, and handling git workflows - all through natural language commands.

Built by Anthropic · github.com/anthropics

claude-code / plugins / plugin-dev / skills / mcp-integration / references / tool-usage.md
538 lines · 11.4 KBPreviewCodeRaw
1# Using MCP Tools in Commands and Agents
2
3Complete guide to using MCP tools effectively in Claude Code plugin commands and agents.
4
5## Overview
6
7Once an MCP server is configured, its tools become available with the prefix `mcp__plugin_<plugin-name>_<server-name>__<tool-name>`. Use these tools in commands and agents just like built-in Claude Code tools.
8
9## Tool Naming Convention
10
11### Format
12
13```
14mcp__plugin_<plugin-name>_<server-name>__<tool-name>
15```
16
17### Examples
18
19**Asana plugin with asana server:**
20- `mcp__plugin_asana_asana__asana_create_task`
21- `mcp__plugin_asana_asana__asana_search_tasks`
22- `mcp__plugin_asana_asana__asana_get_project`
23
24**Custom plugin with database server:**
25- `mcp__plugin_myplug_database__query`
26- `mcp__plugin_myplug_database__execute`
27- `mcp__plugin_myplug_database__list_tables`
28
29### Discovering Tool Names
30
31**Use `/mcp` command:**
32```bash
33/mcp
34```
35
36This shows:
37- All available MCP servers
38- Tools provided by each server
39- Tool schemas and descriptions
40- Full tool names for use in configuration
41
42## Using Tools in Commands
43
44### Pre-Allowing Tools
45
46Specify MCP tools in command frontmatter:
47
48```markdown
49---
50description: Create a new Asana task
51allowed-tools: [
52 "mcp__plugin_asana_asana__asana_create_task"
53]
54---
55
56# Create Task Command
57
58To create a task:
591. Gather task details from user
602. Use mcp__plugin_asana_asana__asana_create_task with the details
613. Confirm creation to user
62```
63
64### Multiple Tools
65
66```markdown
67---
68allowed-tools: [
69 "mcp__plugin_asana_asana__asana_create_task",
70 "mcp__plugin_asana_asana__asana_search_tasks",
71 "mcp__plugin_asana_asana__asana_get_project"
72]
73---
74```
75
76### Wildcard (Use Sparingly)
77
78```markdown
79---
80allowed-tools: ["mcp__plugin_asana_asana__*"]
81---
82```
83
84**Caution:** Only use wildcards if the command truly needs access to all tools from a server.
85
86### Tool Usage in Command Instructions
87
88**Example command:**
89```markdown
90---
91description: Search and create Asana tasks
92allowed-tools: [
93 "mcp__plugin_asana_asana__asana_search_tasks",
94 "mcp__plugin_asana_asana__asana_create_task"
95]
96---
97
98# Asana Task Management
99
100## Searching Tasks
101
102To search for tasks:
1031. Use mcp__plugin_asana_asana__asana_search_tasks
1042. Provide search filters (assignee, project, etc.)
1053. Display results to user
106
107## Creating Tasks
108
109To create a task:
1101. Gather task details:
111 - Title (required)
112 - Description
113 - Project
114 - Assignee
115 - Due date
1162. Use mcp__plugin_asana_asana__asana_create_task
1173. Show confirmation with task link
118```
119
120## Using Tools in Agents
121
122### Agent Configuration
123
124Agents can use MCP tools autonomously without pre-allowing them:
125
126```markdown
127---
128name: asana-status-updater
129description: This agent should be used when the user asks to "update Asana status", "generate project report", or "sync Asana tasks"
130model: inherit
131color: blue
132---
133
134## Role
135
136Autonomous agent for generating Asana project status reports.
137
138## Process
139
1401. **Query tasks**: Use mcp__plugin_asana_asana__asana_search_tasks to get all tasks
1412. **Analyze progress**: Calculate completion rates and identify blockers
1423. **Generate report**: Create formatted status update
1434. **Update Asana**: Use mcp__plugin_asana_asana__asana_create_comment to post report
144
145## Available Tools
146
147The agent has access to all Asana MCP tools without pre-approval.
148```
149
150### Agent Tool Access
151
152Agents have broader tool access than commands:
153- Can use any tool Claude determines is necessary
154- Don't need pre-allowed lists
155- Should document which tools they typically use
156
157## Tool Call Patterns
158
159### Pattern 1: Simple Tool Call
160
161Single tool call with validation:
162
163```markdown
164Steps:
1651. Validate user provided required fields
1662. Call mcp__plugin_api_server__create_item with validated data
1673. Check for errors
1684. Display confirmation
169```
170
171### Pattern 2: Sequential Tools
172
173Chain multiple tool calls:
174
175```markdown
176Steps:
1771. Search for existing items: mcp__plugin_api_server__search
1782. If not found, create new: mcp__plugin_api_server__create
1793. Add metadata: mcp__plugin_api_server__update_metadata
1804. Return final item ID
181```
182
183### Pattern 3: Batch Operations
184
185Multiple calls with same tool:
186
187```markdown
188Steps:
1891. Get list of items to process
1902. For each item:
191 - Call mcp__plugin_api_server__update_item
192 - Track success/failure
1933. Report results summary
194```
195
196### Pattern 4: Error Handling
197
198Graceful error handling:
199
200```markdown
201Steps:
2021. Try to call mcp__plugin_api_server__get_data
2032. If error (rate limit, network, etc.):
204 - Wait and retry (max 3 attempts)
205 - If still failing, inform user
206 - Suggest checking configuration
2073. On success, process data
208```
209
210## Tool Parameters
211
212### Understanding Tool Schemas
213
214Each MCP tool has a schema defining its parameters. View with `/mcp`.
215
216**Example schema:**
217```json
218{
219 "name": "asana_create_task",
220 "description": "Create a new Asana task",
221 "inputSchema": {
222 "type": "object",
223 "properties": {
224 "name": {
225 "type": "string",
226 "description": "Task title"
227 },
228 "notes": {
229 "type": "string",
230 "description": "Task description"
231 },
232 "workspace": {
233 "type": "string",
234 "description": "Workspace GID"
235 }
236 },
237 "required": ["name", "workspace"]
238 }
239}
240```
241
242### Calling Tools with Parameters
243
244Claude automatically structures tool calls based on schema:
245
246```typescript
247// Claude generates this internally
248{
249 toolName: "mcp__plugin_asana_asana__asana_create_task",
250 input: {
251 name: "Review PR #123",
252 notes: "Code review for new feature",
253 workspace: "12345",
254 assignee: "67890",
255 due_on: "2025-01-15"
256 }
257}
258```
259
260### Parameter Validation
261
262**In commands, validate before calling:**
263
264```markdown
265Steps:
2661. Check required parameters:
267 - Title is not empty
268 - Workspace ID is provided
269 - Due date is valid format (YYYY-MM-DD)
2702. If validation fails, ask user to provide missing data
2713. If validation passes, call MCP tool
2724. Handle tool errors gracefully
273```
274
275## Response Handling
276
277### Success Responses
278
279```markdown
280Steps:
2811. Call MCP tool
2822. On success:
283 - Extract relevant data from response
284 - Format for user display
285 - Provide confirmation message
286 - Include relevant links or IDs
287```
288
289### Error Responses
290
291```markdown
292Steps:
2931. Call MCP tool
2942. On error:
295 - Check error type (auth, rate limit, validation, etc.)
296 - Provide helpful error message
297 - Suggest remediation steps
298 - Don't expose internal error details to user
299```
300
301### Partial Success
302
303```markdown
304Steps:
3051. Batch operation with multiple MCP calls
3062. Track successes and failures separately
3073. Report summary:
308 - "Successfully processed 8 of 10 items"
309 - "Failed items: [item1, item2] due to [reason]"
310 - Suggest retry or manual intervention
311```
312
313## Performance Optimization
314
315### Batching Requests
316
317**Good: Single query with filters**
318```markdown
319Steps:
3201. Call mcp__plugin_api_server__search with filters:
321 - project_id: "123"
322 - status: "active"
323 - limit: 100
3242. Process all results
325```
326
327**Avoid: Many individual queries**
328```markdown
329Steps:
3301. For each item ID:
331 - Call mcp__plugin_api_server__get_item
332 - Process item
333```
334
335### Caching Results
336
337```markdown
338Steps:
3391. Call expensive MCP operation: mcp__plugin_api_server__analyze
3402. Store results in variable for reuse
3413. Use cached results for subsequent operations
3424. Only re-fetch if data changes
343```
344
345### Parallel Tool Calls
346
347When tools don't depend on each other, call in parallel:
348
349```markdown
350Steps:
3511. Make parallel calls (Claude handles this automatically):
352 - mcp__plugin_api_server__get_project
353 - mcp__plugin_api_server__get_users
354 - mcp__plugin_api_server__get_tags
3552. Wait for all to complete
3563. Combine results
357```
358
359## Integration Best Practices
360
361### User Experience
362
363**Provide feedback:**
364```markdown
365Steps:
3661. Inform user: "Searching Asana tasks..."
3672. Call mcp__plugin_asana_asana__asana_search_tasks
3683. Show progress: "Found 15 tasks, analyzing..."
3694. Present results
370```
371
372**Handle long operations:**
373```markdown
374Steps:
3751. Warn user: "This may take a minute..."
3762. Break into smaller steps with updates
3773. Show incremental progress
3784. Final summary when complete
379```
380
381### Error Messages
382
383**Good error messages:**
384```
385❌ "Could not create task. Please check:
386 1. You're logged into Asana
387 2. You have access to workspace 'Engineering'
388 3. The project 'Q1 Goals' exists"
389```
390
391**Poor error messages:**
392```
393❌ "Error: MCP tool returned 403"
394```
395
396### Documentation
397
398**Document MCP tool usage in command:**
399```markdown
400## MCP Tools Used
401
402This command uses the following Asana MCP tools:
403- **asana_search_tasks**: Search for tasks matching criteria
404- **asana_create_task**: Create new task with details
405- **asana_update_task**: Update existing task properties
406
407Ensure you're authenticated to Asana before running this command.
408```
409
410## Testing Tool Usage
411
412### Local Testing
413
4141. **Configure MCP server** in `.mcp.json`
4152. **Install plugin locally** in `.claude-plugin/`
4163. **Verify tools available** with `/mcp`
4174. **Test command** that uses tools
4185. **Check debug output**: `claude --debug`
419
420### Test Scenarios
421
422**Test successful calls:**
423```markdown
424Steps:
4251. Create test data in external service
4262. Run command that queries this data
4273. Verify correct results returned
428```
429
430**Test error cases:**
431```markdown
432Steps:
4331. Test with missing authentication
4342. Test with invalid parameters
4353. Test with non-existent resources
4364. Verify graceful error handling
437```
438
439**Test edge cases:**
440```markdown
441Steps:
4421. Test with empty results
4432. Test with maximum results
4443. Test with special characters
4454. Test with concurrent access
446```
447
448## Common Patterns
449
450### Pattern: CRUD Operations
451
452```markdown
453---
454allowed-tools: [
455 "mcp__plugin_api_server__create_item",
456 "mcp__plugin_api_server__read_item",
457 "mcp__plugin_api_server__update_item",
458 "mcp__plugin_api_server__delete_item"
459]
460---
461
462# Item Management
463
464## Create
465Use create_item with required fields...
466
467## Read
468Use read_item with item ID...
469
470## Update
471Use update_item with item ID and changes...
472
473## Delete
474Use delete_item with item ID (ask for confirmation first)...
475```
476
477### Pattern: Search and Process
478
479```markdown
480Steps:
4811. **Search**: mcp__plugin_api_server__search with filters
4822. **Filter**: Apply additional local filtering if needed
4833. **Transform**: Process each result
4844. **Present**: Format and display to user
485```
486
487### Pattern: Multi-Step Workflow
488
489```markdown
490Steps:
4911. **Setup**: Gather all required information
4922. **Validate**: Check data completeness
4933. **Execute**: Chain of MCP tool calls:
494 - Create parent resource
495 - Create child resources
496 - Link resources together
497 - Add metadata
4984. **Verify**: Confirm all steps succeeded
4995. **Report**: Provide summary to user
500```
501
502## Troubleshooting
503
504### Tools Not Available
505
506**Check:**
507- MCP server configured correctly
508- Server connected (check `/mcp`)
509- Tool names match exactly (case-sensitive)
510- Restart Claude Code after config changes
511
512### Tool Calls Failing
513
514**Check:**
515- Authentication is valid
516- Parameters match tool schema
517- Required parameters provided
518- Check `claude --debug` logs
519
520### Performance Issues
521
522**Check:**
523- Batching queries instead of individual calls
524- Caching results when appropriate
525- Not making unnecessary tool calls
526- Parallel calls when possible
527
528## Conclusion
529
530Effective MCP tool usage requires:
5311. **Understanding tool schemas** via `/mcp`
5322. **Pre-allowing tools** in commands appropriately
5333. **Handling errors gracefully**
5344. **Optimizing performance** with batching and caching
5355. **Providing good UX** with feedback and clear errors
5366. **Testing thoroughly** before deployment
537
538Follow these patterns for robust MCP tool integration in your plugin commands and agents.