Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Guidance for integrating MCP (Model Context Protocol) servers into Claude Code plugins.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
SKILL.md
1---2name: MCP Integration3description: 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.05---67# MCP Integration for Claude Code Plugins89## Overview1011Model 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.1213**Key capabilities:**14- Connect to external services (databases, APIs, file systems)15- Provide 10+ related tools from a single service16- Handle OAuth and complex authentication flows17- Bundle MCP servers with plugins for automatic setup1819## MCP Server Configuration Methods2021Plugins can bundle MCP servers in two ways:2223### Method 1: Dedicated .mcp.json (Recommended)2425Create `.mcp.json` at plugin root:2627```json28{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```3839**Benefits:**40- Clear separation of concerns41- Easier to maintain42- Better for multiple servers4344### Method 2: Inline in plugin.json4546Add `mcpServers` field to plugin.json:4748```json49{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```6061**Benefits:**62- Single configuration file63- Good for simple single-server plugins6465## MCP Server Types6667### stdio (Local Process)6869Execute local MCP servers as child processes. Best for local tools and custom servers.7071**Configuration:**72```json73{74"filesystem": {75"command": "npx",76"args": ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"],77"env": {78"LOG_LEVEL": "debug"79}80}81}82```8384**Use cases:**85- File system access86- Local database connections87- Custom MCP servers88- NPM-packaged MCP servers8990**Process management:**91- Claude Code spawns and manages the process92- Communicates via stdin/stdout93- Terminates when Claude Code exits9495### SSE (Server-Sent Events)9697Connect to hosted MCP servers with OAuth support. Best for cloud services.9899**Configuration:**100```json101{102"asana": {103"type": "sse",104"url": "https://mcp.asana.com/sse"105}106}107```108109**Use cases:**110- Official hosted MCP servers (Asana, GitHub, etc.)111- Cloud services with MCP endpoints112- OAuth-based authentication113- No local installation needed114115**Authentication:**116- OAuth flows handled automatically117- User prompted on first use118- Tokens managed by Claude Code119120### HTTP (REST API)121122Connect to RESTful MCP servers with token authentication.123124**Configuration:**125```json126{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```137138**Use cases:**139- REST API-based MCP servers140- Token-based authentication141- Custom API backends142- Stateless interactions143144### WebSocket (Real-time)145146Connect to WebSocket MCP servers for real-time bidirectional communication.147148**Configuration:**149```json150{151"realtime-service": {152"type": "ws",153"url": "wss://mcp.example.com/ws",154"headers": {155"Authorization": "Bearer ${TOKEN}"156}157}158}159```160161**Use cases:**162- Real-time data streaming163- Persistent connections164- Push notifications from server165- Low-latency requirements166167## Environment Variable Expansion168169All MCP configurations support environment variable substitution:170171**${CLAUDE_PLUGIN_ROOT}** - Plugin directory (always use for portability):172```json173{174"command": "${CLAUDE_PLUGIN_ROOT}/servers/my-server"175}176```177178**User environment variables** - From user's shell:179```json180{181"env": {182"API_KEY": "${MY_API_KEY}",183"DATABASE_URL": "${DB_URL}"184}185}186```187188**Best practice:** Document all required environment variables in plugin README.189190## MCP Tool Naming191192When MCP servers provide tools, they're automatically prefixed:193194**Format:** `mcp__plugin_<plugin-name>_<server-name>__<tool-name>`195196**Example:**197- Plugin: `asana`198- Server: `asana`199- Tool: `create_task`200- **Full name:** `mcp__plugin_asana_asana__asana_create_task`201202### Using MCP Tools in Commands203204Pre-allow specific MCP tools in command frontmatter:205206```markdown207---208allowed-tools: [209"mcp__plugin_asana_asana__asana_create_task",210"mcp__plugin_asana_asana__asana_search_tasks"211]212---213```214215**Wildcard (use sparingly):**216```markdown217---218allowed-tools: ["mcp__plugin_asana_asana__*"]219---220```221222**Best practice:** Pre-allow specific tools, not wildcards, for security.223224## Lifecycle Management225226**Automatic startup:**227- MCP servers start when plugin enables228- Connection established before first tool use229- Restart required for configuration changes230231**Lifecycle:**2321. Plugin loads2332. MCP configuration parsed2343. Server process started (stdio) or connection established (SSE/HTTP/WS)2354. Tools discovered and registered2365. Tools available as `mcp__plugin_...__...`237238**Viewing servers:**239Use `/mcp` command to see all servers including plugin-provided ones.240241## Authentication Patterns242243### OAuth (SSE/HTTP)244245OAuth handled automatically by Claude Code:246247```json248{249"type": "sse",250"url": "https://mcp.example.com/sse"251}252```253254User authenticates in browser on first use. No additional configuration needed.255256### Token-Based (Headers)257258Static or environment variable tokens:259260```json261{262"type": "http",263"url": "https://api.example.com",264"headers": {265"Authorization": "Bearer ${API_TOKEN}"266}267}268```269270Document required environment variables in README.271272### Environment Variables (stdio)273274Pass configuration to MCP server:275276```json277{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```287288## Integration Patterns289290### Pattern 1: Simple Tool Wrapper291292Commands use MCP tools with user interaction:293294```markdown295# Command: create-item.md296---297allowed-tools: ["mcp__plugin_name_server__create_item"]298---299300Steps:3011. Gather item details from user3022. Use mcp__plugin_name_server__create_item3033. Confirm creation304```305306**Use for:** Adding validation or preprocessing before MCP calls.307308### Pattern 2: Autonomous Agent309310Agents use MCP tools autonomously:311312```markdown313# Agent: data-analyzer.md314315Analysis Process:3161. Query data via mcp__plugin_db_server__query3172. Process and analyze results3183. Generate insights report319```320321**Use for:** Multi-step MCP workflows without user interaction.322323### Pattern 3: Multi-Server Plugin324325Integrate multiple MCP servers:326327```json328{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```339340**Use for:** Workflows spanning multiple services.341342## Security Best Practices343344### Use HTTPS/WSS345346Always use secure connections:347348```json349✅ "url": "https://mcp.example.com/sse"350❌ "url": "http://mcp.example.com/sse"351```352353### Token Management354355**DO:**356- ✅ Use environment variables for tokens357- ✅ Document required env vars in README358- ✅ Let OAuth flow handle authentication359360**DON'T:**361- ❌ Hardcode tokens in configuration362- ❌ Commit tokens to git363- ❌ Share tokens in documentation364365### Permission Scoping366367Pre-allow only necessary MCP tools:368369```markdown370✅ allowed-tools: [371"mcp__plugin_api_server__read_data",372"mcp__plugin_api_server__create_item"373]374375❌ allowed-tools: ["mcp__plugin_api_server__*"]376```377378## Error Handling379380### Connection Failures381382Handle MCP server unavailability:383- Provide fallback behavior in commands384- Inform user of connection issues385- Check server URL and configuration386387### Tool Call Errors388389Handle failed MCP operations:390- Validate inputs before calling MCP tools391- Provide clear error messages392- Check rate limiting and quotas393394### Configuration Errors395396Validate MCP configuration:397- Test server connectivity during development398- Validate JSON syntax399- Check required environment variables400401## Performance Considerations402403### Lazy Loading404405MCP servers connect on-demand:406- Not all servers connect at startup407- First tool use triggers connection408- Connection pooling managed automatically409410### Batching411412Batch similar requests when possible:413414```415# Good: Single query with filters416tasks = search_tasks(project="X", assignee="me", limit=50)417418# Avoid: Many individual queries419for id in task_ids:420task = get_task(id)421```422423## Testing MCP Integration424425### Local Testing4264271. Configure MCP server in `.mcp.json`4282. Install plugin locally (`.claude-plugin/`)4293. Run `/mcp` to verify server appears4304. Test tool calls in commands4315. Check `claude --debug` logs for connection issues432433### Validation Checklist434435- [ ] MCP configuration is valid JSON436- [ ] Server URL is correct and accessible437- [ ] Required environment variables documented438- [ ] Tools appear in `/mcp` output439- [ ] Authentication works (OAuth or tokens)440- [ ] Tool calls succeed from commands441- [ ] Error cases handled gracefully442443## Debugging444445### Enable Debug Logging446447```bash448claude --debug449```450451Look for:452- MCP server connection attempts453- Tool discovery logs454- Authentication flows455- Tool call errors456457### Common Issues458459**Server not connecting:**460- Check URL is correct461- Verify server is running (stdio)462- Check network connectivity463- Review authentication configuration464465**Tools not available:**466- Verify server connected successfully467- Check tool names match exactly468- Run `/mcp` to see available tools469- Restart Claude Code after config changes470471**Authentication failing:**472- Clear cached auth tokens473- Re-authenticate474- Check token scopes and permissions475- Verify environment variables set476477## Quick Reference478479### MCP Server Types480481| 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 |487488### Configuration Checklist489490- [ ] Server type specified (stdio/SSE/HTTP/ws)491- [ ] Type-specific fields complete (command or url)492- [ ] Authentication configured493- [ ] Environment variables documented494- [ ] HTTPS/WSS used (not HTTP/WS)495- [ ] ${CLAUDE_PLUGIN_ROOT} used for paths496497### Best Practices498499**DO:**500- ✅ Use ${CLAUDE_PLUGIN_ROOT} for portable paths501- ✅ Document required environment variables502- ✅ Use secure connections (HTTPS/WSS)503- ✅ Pre-allow specific MCP tools in commands504- ✅ Test MCP integration before publishing505- ✅ Handle connection and tool errors gracefully506507**DON'T:**508- ❌ Hardcode absolute paths509- ❌ Commit credentials to git510- ❌ Use HTTP instead of HTTPS511- ❌ Pre-allow all tools with wildcards512- ❌ Skip error handling513- ❌ Forget to document setup514515## Additional Resources516517### Reference Files518519For detailed information, consult:520521- **`references/server-types.md`** - Deep dive on each server type522- **`references/authentication.md`** - Authentication patterns and OAuth523- **`references/tool-usage.md`** - Using MCP tools in commands and agents524525### Example Configurations526527Working examples in `examples/`:528529- **`stdio-server.json`** - Local stdio MCP server530- **`sse-server.json`** - Hosted SSE server with OAuth531- **`http-server.json`** - REST API with token auth532533### External Resources534535- **Official MCP Docs**: https://modelcontextprotocol.io/536- **Claude Code MCP Docs**: https://docs.claude.com/en/docs/claude-code/mcp537- **MCP SDK**: @modelcontextprotocol/sdk538- **Testing**: Use `claude --debug` and `/mcp` command539540## Implementation Workflow541542To add MCP integration to a plugin:5435441. Choose MCP server type (stdio, SSE, HTTP, ws)5452. Create `.mcp.json` at plugin root with configuration5463. Use ${CLAUDE_PLUGIN_ROOT} for all file references5474. Document required environment variables in README5485. Test locally with `/mcp` command5496. Pre-allow MCP tools in relevant commands5507. Handle authentication (OAuth or tokens)5518. Test error cases (connection failures, auth errors)5529. Document MCP integration in plugin README553554Focus on stdio for custom/local servers, SSE for hosted services with OAuth.555