Claude Code MCP Integration Strategy - Maximizing Extensibility¶
Key Points¶
External System Integration
Direct interaction with APIs and databases
Web Automation
Web scraping and testing with Puppeteer
Database Operations
SQL query execution and result analysis
Cloud Services
Integration with AWS, GCP, and Azure
📖 What is MCP (Model Context Protocol)?¶
MCP is an open communication protocol between Large Language Models and tools. It adds new capabilities to Claude Code and enables integration with external systems.
Basic MCP Architecture¶
graph LR
A[Claude Code] --> B[MCP Protocol]
B --> C[MCP Server 1]
B --> D[MCP Server 2]
B --> E[MCP Server N]
C --> F[External API]
D --> G[Database]
E --> H[File System]🔧 Configuration Methods¶
1. Project-specific Configuration¶
// .claude.json
{
"mcpServers": {
"filesystem": {
"type": "stdio",
"command": "npx",
"args": ["-y", "mcp-filesystem"],
"env": {
"ALLOWED_DIRECTORIES": "/home/user/projects"
}
},
"puppeteer": {
"type": "stdio",
"command": "npx",
"args": ["-y", "mcp-puppeteer"],
"env": {
"HEADLESS": "true"
}
}
}
}
2. System-wide Configuration¶
// ~/.claude/claude.json
{
"mcpServers": {
"github": {
"type": "stdio",
"command": "npx",
"args": ["-y", "mcp-github"],
"env": {
"GITHUB_TOKEN": "your-token-here"
}
},
"sequential-thinking": {
"type": "stdio",
"command": "npx",
"args": ["-y", "mcp-sequential-thinking"]
}
}
}
🚀 Popular MCP Servers¶
1. Filesystem MCP¶
# Installation
npm install -g mcp-filesystem
# Configuration example
{
"filesystem": {
"type": "stdio",
"command": "mcp-filesystem",
"args": ["--allowed-dir", "/home/user/projects", "--read-only"]
}
}
Use cases: - File search in large projects - Automatic configuration file generation - Log file analysis
2. Puppeteer MCP¶
# Installation
npm install -g mcp-puppeteer
# Configuration example
{
"puppeteer": {
"type": "stdio",
"command": "mcp-puppeteer",
"env": {
"HEADLESS": "true",
"VIEWPORT_WIDTH": "1920",
"VIEWPORT_HEIGHT": "1080"
}
}
}
Use cases: - Web scraping - E2E test automation - Screenshot capture
3. GitHub MCP¶
# Installation
npm install -g mcp-github
# Configuration example
{
"github": {
"type": "stdio",
"command": "mcp-github",
"env": {
"GITHUB_TOKEN": "ghp_xxxxxxxxxxxx",
"GITHUB_REPO": "owner/repo"
}
}
}
Use cases: - Automatic issue creation and updates - Automatic PR reviews - Project management automation
🛠️ Creating Custom MCP Servers¶
1. Basic MCP Server¶
# custom_mcp_server.py
import json
import sys
from typing import Dict, Any
class CustomMCPServer:
def __init__(self):
self.tools = {
"database_query": self.execute_query,
"send_email": self.send_notification,
"file_analysis": self.analyze_file
}
def execute_query(self, query: str) -> Dict[str, Any]:
"""Execute database query"""
# Actual implementation
return {"result": "query executed", "rows": []}
def send_notification(self, message: str, recipient: str) -> Dict[str, Any]:
"""Send email notification"""
# Actual implementation
return {"status": "sent", "message_id": "12345"}
def analyze_file(self, file_path: str) -> Dict[str, Any]:
"""Analyze file"""
# Actual implementation
return {"lines": 100, "complexity": "low"}
def handle_request(self, request: Dict[str, Any]) -> Dict[str, Any]:
"""Handle request"""
tool_name = request.get("method")
if tool_name in self.tools:
return self.tools[tool_name](**request.get("params", {}))
return {"error": "Unknown tool"}
if __name__ == "__main__":
server = CustomMCPServer()
for line in sys.stdin:
try:
request = json.loads(line)
response = server.handle_request(request)
print(json.dumps(response))
except Exception as e:
print(json.dumps({"error": str(e)}))
2. TypeScript Implementation¶
// custom-mcp-server.ts
import { MCPServer } from '@anthropic/mcp';
class CustomMCPServer extends MCPServer {
constructor() {
super({
name: 'custom-mcp-server',
version: '1.0.0'
});
this.addTool({
name: 'analyze_code',
description: 'Analyze code complexity and quality',
parameters: {
type: 'object',
properties: {
filePath: { type: 'string' },
language: { type: 'string' }
},
required: ['filePath']
}
}, this.analyzeCode.bind(this));
}
async analyzeCode(params: { filePath: string; language?: string }) {
// Code analysis implementation
const analysis = await this.performAnalysis(params.filePath);
return {
complexity: analysis.complexity,
maintainability: analysis.maintainability,
suggestions: analysis.suggestions
};
}
private async performAnalysis(filePath: string) {
// Actual analysis logic
return {
complexity: 'medium',
maintainability: 'high',
suggestions: ['Add more comments', 'Extract helper functions']
};
}
}
const server = new CustomMCPServer();
server.start();
🎯 Practical Use Cases¶
1. DevOps Automation¶
{
"mcpServers": {
"aws-cli": {
"type": "stdio",
"command": "python",
"args": ["aws_mcp_server.py"],
"env": {
"AWS_REGION": "us-west-2",
"AWS_PROFILE": "default"
}
},
"kubernetes": {
"type": "stdio",
"command": "python",
"args": ["k8s_mcp_server.py"],
"env": {
"KUBECONFIG": "/home/user/.kube/config"
}
}
}
}
Usage scenarios: - Automatic infrastructure monitoring - Deployment automation - Log analysis and alerting
2. Database Management¶
# database_mcp_server.py
import sqlite3
import json
import sys
from typing import Dict, Any, List
class DatabaseMCPServer:
def __init__(self, db_path: str):
self.db_path = db_path
self.tools = {
"execute_query": self.execute_query,
"get_schema": self.get_schema,
"optimize_query": self.optimize_query
}
def execute_query(self, query: str) -> Dict[str, Any]:
"""Execute SQL query"""
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(query)
if query.strip().upper().startswith('SELECT'):
results = cursor.fetchall()
columns = [desc[0] for desc in cursor.description]
return {
"success": True,
"data": results,
"columns": columns
}
else:
conn.commit()
return {
"success": True,
"affected_rows": cursor.rowcount
}
except Exception as e:
return {"success": False, "error": str(e)}
finally:
conn.close()
def get_schema(self) -> Dict[str, Any]:
"""Get database schema"""
query = """
SELECT name, sql FROM sqlite_master
WHERE type='table' AND name NOT LIKE 'sqlite_%'
"""
return self.execute_query(query)
def optimize_query(self, query: str) -> Dict[str, Any]:
"""Suggest query optimizations"""
# Actual optimization logic
suggestions = []
if "SELECT *" in query:
suggestions.append("Avoid SELECT *, specify columns explicitly")
if "WHERE" not in query.upper():
suggestions.append("Consider adding WHERE clause to limit results")
return {"suggestions": suggestions}
3. Web Scraping Automation¶
// web_scraper_mcp.js
const puppeteer = require('puppeteer');
class WebScraperMCP {
async scrapeWebsite(url, selectors) {
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
try {
await page.goto(url);
const results = {};
for (const [key, selector] of Object.entries(selectors)) {
const elements = await page.$$eval(selector, els =>
els.map(el => el.textContent.trim())
);
results[key] = elements;
}
return { success: true, data: results };
} catch (error) {
return { success: false, error: error.message };
} finally {
await browser.close();
}
}
async takeScreenshot(url, options = {}) {
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
try {
await page.goto(url);
const screenshot = await page.screenshot(options);
return { success: true, screenshot: screenshot.toString('base64') };
} catch (error) {
return { success: false, error: error.message };
} finally {
await browser.close();
}
}
}
// Run as MCP server
const server = new WebScraperMCP();
process.stdin.on('data', async (data) => {
try {
const request = JSON.parse(data.toString());
let result;
switch (request.method) {
case 'scrape':
result = await server.scrapeWebsite(request.params.url, request.params.selectors);
break;
case 'screenshot':
result = await server.takeScreenshot(request.params.url, request.params.options);
break;
default:
result = { success: false, error: 'Unknown method' };
}
console.log(JSON.stringify(result));
} catch (error) {
console.log(JSON.stringify({ success: false, error: error.message }));
}
});
🔍 Debugging and Troubleshooting¶
1. Check MCP Server Status¶
# List MCP servers
claude mcp list
# Details of a specific server
claude mcp status github
# Test connection
claude mcp test-connection filesystem
2. Check Logs¶
# MCP server logs
tail -f ~/.claude/mcp.log
# Logs for a specific server
tail -f ~/.claude/mcp/github.log
3. Common Issues and Solutions¶
| Issue | Cause | Solution |
|---|---|---|
| Connection error | Missing credentials | Check environment variables and tokens |
| Response delay | Server load | Adjust timeout settings |
| Permission error | Insufficient permissions | Check file and directory permissions |
🌟 Enterprise Adoption Case Studies¶
Large-scale Development Use¶
{
"mcpServers": {
"jira": {
"type": "stdio",
"command": "python",
"args": ["jira_mcp_server.py"],
"env": {
"JIRA_URL": "https://company.atlassian.net",
"JIRA_TOKEN": "your-api-token"
}
},
"confluence": {
"type": "stdio",
"command": "python",
"args": ["confluence_mcp_server.py"],
"env": {
"CONFLUENCE_URL": "https://company.atlassian.net/wiki",
"CONFLUENCE_TOKEN": "your-api-token"
}
}
}
}
Impact: - 70% improvement in development task automation - 85% achievement in documentation update automation - 60% improvement in project management efficiency