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 / SKILL.md
554 lines · 12.2 KBPreviewCodeRaw
1---
2name: MCP Integration
3description: This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context Protocol", "connect external service", mentions "${CLAUDE_PLUGIN_ROOT} with MCP", or discusses MCP server types (SSE, stdio, HTTP, WebSocket). Provides comprehensive guidance for integrating Model Context Protocol servers into Claude Code plugins for external tool and service integration.
4version: 0.1.0
5---
6
7# MCP Integration for Claude Code Plugins
8
9## Overview
10
11Model Context Protocol (MCP) enables Claude Code plugins to integrate with external services and APIs by providing structured tool access. Use MCP integration to expose external service capabilities as tools within Claude Code.
12
13**Key capabilities:**
14- Connect to external services (databases, APIs, file systems)
15- Provide 10+ related tools from a single service
16- Handle OAuth and complex authentication flows
17- Bundle MCP servers with plugins for automatic setup
18
19## MCP Server Configuration Methods
20
21Plugins can bundle MCP servers in two ways:
22
23### Method 1: Dedicated .mcp.json (Recommended)
24
25Create `.mcp.json` at plugin root:
26
27```json
28{
29 "database-tools": {
30 "command": "${CLAUDE_PLUGIN_ROOT}/servers/db-server",
31 "args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"],
32 "env": {
33 "DB_URL": "${DB_URL}"
34 }
35 }
36}
37```
38
39**Benefits:**
40- Clear separation of concerns
41- Easier to maintain
42- Better for multiple servers
43
44### Method 2: Inline in plugin.json
45
46Add `mcpServers` field to plugin.json:
47
48```json
49{
50 "name": "my-plugin",
51 "version": "1.0.0",
52 "mcpServers": {
53 "plugin-api": {
54 "command": "${CLAUDE_PLUGIN_ROOT}/servers/api-server",
55 "args": ["--port", "8080"]
56 }
57 }
58}
59```
60
61**Benefits:**
62- Single configuration file
63- Good for simple single-server plugins
64
65## MCP Server Types
66
67### stdio (Local Process)
68
69Execute local MCP servers as child processes. Best for local tools and custom servers.
70
71**Configuration:**
72```json
73{
74 "filesystem": {
75 "command": "npx",
76 "args": ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"],
77 "env": {
78 "LOG_LEVEL": "debug"
79 }
80 }
81}
82```
83
84**Use cases:**
85- File system access
86- Local database connections
87- Custom MCP servers
88- NPM-packaged MCP servers
89
90**Process management:**
91- Claude Code spawns and manages the process
92- Communicates via stdin/stdout
93- Terminates when Claude Code exits
94
95### SSE (Server-Sent Events)
96
97Connect to hosted MCP servers with OAuth support. Best for cloud services.
98
99**Configuration:**
100```json
101{
102 "asana": {
103 "type": "sse",
104 "url": "https://mcp.asana.com/sse"
105 }
106}
107```
108
109**Use cases:**
110- Official hosted MCP servers (Asana, GitHub, etc.)
111- Cloud services with MCP endpoints
112- OAuth-based authentication
113- No local installation needed
114
115**Authentication:**
116- OAuth flows handled automatically
117- User prompted on first use
118- Tokens managed by Claude Code
119
120### HTTP (REST API)
121
122Connect to RESTful MCP servers with token authentication.
123
124**Configuration:**
125```json
126{
127 "api-service": {
128 "type": "http",
129 "url": "https://api.example.com/mcp",
130 "headers": {
131 "Authorization": "Bearer ${API_TOKEN}",
132 "X-Custom-Header": "value"
133 }
134 }
135}
136```
137
138**Use cases:**
139- REST API-based MCP servers
140- Token-based authentication
141- Custom API backends
142- Stateless interactions
143
144### WebSocket (Real-time)
145
146Connect to WebSocket MCP servers for real-time bidirectional communication.
147
148**Configuration:**
149```json
150{
151 "realtime-service": {
152 "type": "ws",
153 "url": "wss://mcp.example.com/ws",
154 "headers": {
155 "Authorization": "Bearer ${TOKEN}"
156 }
157 }
158}
159```
160
161**Use cases:**
162- Real-time data streaming
163- Persistent connections
164- Push notifications from server
165- Low-latency requirements
166
167## Environment Variable Expansion
168
169All MCP configurations support environment variable substitution:
170
171**${CLAUDE_PLUGIN_ROOT}** - Plugin directory (always use for portability):
172```json
173{
174 "command": "${CLAUDE_PLUGIN_ROOT}/servers/my-server"
175}
176```
177
178**User environment variables** - From user's shell:
179```json
180{
181 "env": {
182 "API_KEY": "${MY_API_KEY}",
183 "DATABASE_URL": "${DB_URL}"
184 }
185}
186```
187
188**Best practice:** Document all required environment variables in plugin README.
189
190## MCP Tool Naming
191
192When MCP servers provide tools, they're automatically prefixed:
193
194**Format:** `mcp__plugin_<plugin-name>_<server-name>__<tool-name>`
195
196**Example:**
197- Plugin: `asana`
198- Server: `asana`
199- Tool: `create_task`
200- **Full name:** `mcp__plugin_asana_asana__asana_create_task`
201
202### Using MCP Tools in Commands
203
204Pre-allow specific MCP tools in command frontmatter:
205
206```markdown
207---
208allowed-tools: [
209 "mcp__plugin_asana_asana__asana_create_task",
210 "mcp__plugin_asana_asana__asana_search_tasks"
211]
212---
213```
214
215**Wildcard (use sparingly):**
216```markdown
217---
218allowed-tools: ["mcp__plugin_asana_asana__*"]
219---
220```
221
222**Best practice:** Pre-allow specific tools, not wildcards, for security.
223
224## Lifecycle Management
225
226**Automatic startup:**
227- MCP servers start when plugin enables
228- Connection established before first tool use
229- Restart required for configuration changes
230
231**Lifecycle:**
2321. Plugin loads
2332. MCP configuration parsed
2343. Server process started (stdio) or connection established (SSE/HTTP/WS)
2354. Tools discovered and registered
2365. Tools available as `mcp__plugin_...__...`
237
238**Viewing servers:**
239Use `/mcp` command to see all servers including plugin-provided ones.
240
241## Authentication Patterns
242
243### OAuth (SSE/HTTP)
244
245OAuth handled automatically by Claude Code:
246
247```json
248{
249 "type": "sse",
250 "url": "https://mcp.example.com/sse"
251}
252```
253
254User authenticates in browser on first use. No additional configuration needed.
255
256### Token-Based (Headers)
257
258Static or environment variable tokens:
259
260```json
261{
262 "type": "http",
263 "url": "https://api.example.com",
264 "headers": {
265 "Authorization": "Bearer ${API_TOKEN}"
266 }
267}
268```
269
270Document required environment variables in README.
271
272### Environment Variables (stdio)
273
274Pass configuration to MCP server:
275
276```json
277{
278 "command": "python",
279 "args": ["-m", "my_mcp_server"],
280 "env": {
281 "DATABASE_URL": "${DB_URL}",
282 "API_KEY": "${API_KEY}",
283 "LOG_LEVEL": "info"
284 }
285}
286```
287
288## Integration Patterns
289
290### Pattern 1: Simple Tool Wrapper
291
292Commands use MCP tools with user interaction:
293
294```markdown
295# Command: create-item.md
296---
297allowed-tools: ["mcp__plugin_name_server__create_item"]
298---
299
300Steps:
3011. Gather item details from user
3022. Use mcp__plugin_name_server__create_item
3033. Confirm creation
304```
305
306**Use for:** Adding validation or preprocessing before MCP calls.
307
308### Pattern 2: Autonomous Agent
309
310Agents use MCP tools autonomously:
311
312```markdown
313# Agent: data-analyzer.md
314
315Analysis Process:
3161. Query data via mcp__plugin_db_server__query
3172. Process and analyze results
3183. Generate insights report
319```
320
321**Use for:** Multi-step MCP workflows without user interaction.
322
323### Pattern 3: Multi-Server Plugin
324
325Integrate multiple MCP servers:
326
327```json
328{
329 "github": {
330 "type": "sse",
331 "url": "https://mcp.github.com/sse"
332 },
333 "jira": {
334 "type": "sse",
335 "url": "https://mcp.jira.com/sse"
336 }
337}
338```
339
340**Use for:** Workflows spanning multiple services.
341
342## Security Best Practices
343
344### Use HTTPS/WSS
345
346Always use secure connections:
347
348```json
349✅ "url": "https://mcp.example.com/sse"
350❌ "url": "http://mcp.example.com/sse"
351```
352
353### Token Management
354
355**DO:**
356- ✅ Use environment variables for tokens
357- ✅ Document required env vars in README
358- ✅ Let OAuth flow handle authentication
359
360**DON'T:**
361- ❌ Hardcode tokens in configuration
362- ❌ Commit tokens to git
363- ❌ Share tokens in documentation
364
365### Permission Scoping
366
367Pre-allow only necessary MCP tools:
368
369```markdown
370✅ allowed-tools: [
371 "mcp__plugin_api_server__read_data",
372 "mcp__plugin_api_server__create_item"
373]
374
375❌ allowed-tools: ["mcp__plugin_api_server__*"]
376```
377
378## Error Handling
379
380### Connection Failures
381
382Handle MCP server unavailability:
383- Provide fallback behavior in commands
384- Inform user of connection issues
385- Check server URL and configuration
386
387### Tool Call Errors
388
389Handle failed MCP operations:
390- Validate inputs before calling MCP tools
391- Provide clear error messages
392- Check rate limiting and quotas
393
394### Configuration Errors
395
396Validate MCP configuration:
397- Test server connectivity during development
398- Validate JSON syntax
399- Check required environment variables
400
401## Performance Considerations
402
403### Lazy Loading
404
405MCP servers connect on-demand:
406- Not all servers connect at startup
407- First tool use triggers connection
408- Connection pooling managed automatically
409
410### Batching
411
412Batch similar requests when possible:
413
414```
415# Good: Single query with filters
416tasks = search_tasks(project="X", assignee="me", limit=50)
417
418# Avoid: Many individual queries
419for id in task_ids:
420 task = get_task(id)
421```
422
423## Testing MCP Integration
424
425### Local Testing
426
4271. Configure MCP server in `.mcp.json`
4282. Install plugin locally (`.claude-plugin/`)
4293. Run `/mcp` to verify server appears
4304. Test tool calls in commands
4315. Check `claude --debug` logs for connection issues
432
433### Validation Checklist
434
435- [ ] MCP configuration is valid JSON
436- [ ] Server URL is correct and accessible
437- [ ] Required environment variables documented
438- [ ] Tools appear in `/mcp` output
439- [ ] Authentication works (OAuth or tokens)
440- [ ] Tool calls succeed from commands
441- [ ] Error cases handled gracefully
442
443## Debugging
444
445### Enable Debug Logging
446
447```bash
448claude --debug
449```
450
451Look for:
452- MCP server connection attempts
453- Tool discovery logs
454- Authentication flows
455- Tool call errors
456
457### Common Issues
458
459**Server not connecting:**
460- Check URL is correct
461- Verify server is running (stdio)
462- Check network connectivity
463- Review authentication configuration
464
465**Tools not available:**
466- Verify server connected successfully
467- Check tool names match exactly
468- Run `/mcp` to see available tools
469- Restart Claude Code after config changes
470
471**Authentication failing:**
472- Clear cached auth tokens
473- Re-authenticate
474- Check token scopes and permissions
475- Verify environment variables set
476
477## Quick Reference
478
479### MCP Server Types
480
481| Type | Transport | Best For | Auth |
482|------|-----------|----------|------|
483| stdio | Process | Local tools, custom servers | Env vars |
484| SSE | HTTP | Hosted services, cloud APIs | OAuth |
485| HTTP | REST | API backends, token auth | Tokens |
486| ws | WebSocket | Real-time, streaming | Tokens |
487
488### Configuration Checklist
489
490- [ ] Server type specified (stdio/SSE/HTTP/ws)
491- [ ] Type-specific fields complete (command or url)
492- [ ] Authentication configured
493- [ ] Environment variables documented
494- [ ] HTTPS/WSS used (not HTTP/WS)
495- [ ] ${CLAUDE_PLUGIN_ROOT} used for paths
496
497### Best Practices
498
499**DO:**
500- ✅ Use ${CLAUDE_PLUGIN_ROOT} for portable paths
501- ✅ Document required environment variables
502- ✅ Use secure connections (HTTPS/WSS)
503- ✅ Pre-allow specific MCP tools in commands
504- ✅ Test MCP integration before publishing
505- ✅ Handle connection and tool errors gracefully
506
507**DON'T:**
508- ❌ Hardcode absolute paths
509- ❌ Commit credentials to git
510- ❌ Use HTTP instead of HTTPS
511- ❌ Pre-allow all tools with wildcards
512- ❌ Skip error handling
513- ❌ Forget to document setup
514
515## Additional Resources
516
517### Reference Files
518
519For detailed information, consult:
520
521- **`references/server-types.md`** - Deep dive on each server type
522- **`references/authentication.md`** - Authentication patterns and OAuth
523- **`references/tool-usage.md`** - Using MCP tools in commands and agents
524
525### Example Configurations
526
527Working examples in `examples/`:
528
529- **`stdio-server.json`** - Local stdio MCP server
530- **`sse-server.json`** - Hosted SSE server with OAuth
531- **`http-server.json`** - REST API with token auth
532
533### External Resources
534
535- **Official MCP Docs**: https://modelcontextprotocol.io/
536- **Claude Code MCP Docs**: https://docs.claude.com/en/docs/claude-code/mcp
537- **MCP SDK**: @modelcontextprotocol/sdk
538- **Testing**: Use `claude --debug` and `/mcp` command
539
540## Implementation Workflow
541
542To add MCP integration to a plugin:
543
5441. Choose MCP server type (stdio, SSE, HTTP, ws)
5452. Create `.mcp.json` at plugin root with configuration
5463. Use ${CLAUDE_PLUGIN_ROOT} for all file references
5474. Document required environment variables in README
5485. Test locally with `/mcp` command
5496. Pre-allow MCP tools in relevant commands
5507. Handle authentication (OAuth or tokens)
5518. Test error cases (connection failures, auth errors)
5529. Document MCP integration in plugin README
553
554Focus on stdio for custom/local servers, SSE for hosted services with OAuth.