MCP Examples
Practical examples and use cases for Model Context Protocol servers
Examples
Real-world usage examples and tutorials
📁File System Operations
Read, write, and manage files using the File System MCP server
Reading Files
Use the filesystem server to read file contents and get file information.
// Example: Read a configuration file
const result = await mcpClient.callTool("read_file", {
path: "/path/to/config.json"
});
console.log(result.content);
// Output: {"api_key": "abc123", "endpoint": "https://api.example.com"}
Writing Files
Create or update files with new content using the filesystem server.
// Example: Write a log file
await mcpClient.callTool("write_file", {
path: "/logs/app.log",
content: "Application started at " + new Date().toISOString()
});
// Example: Create a new configuration
await mcpClient.callTool("write_file", {
path: "/config/settings.json",
content: JSON.stringify({
theme: "dark",
language: "en",
notifications: true
}, null, 2)
});
Directory Operations
List directory contents and navigate the file system.
// Example: List directory contents
const listing = await mcpClient.callTool("list_directory", {
path: "/projects"
});
console.log(listing.entries);
// Output: [
// { name: "web-app", type: "directory" },
// { name: "api-server", type: "directory" },
// { name: "README.md", type: "file" }
// ]
🔍Web Search Integration
Search the web and retrieve real-time information
Basic Web Search
Search for information and get relevant results from the web.
// Example: Search for current weather
const weatherResults = await mcpClient.callTool("web_search", {
query: "current weather in San Francisco",
max_results: 5
});
console.log(weatherResults.results);
// Output: Array of search results with titles, URLs, and snippets
News Search
Get the latest news and updates on specific topics.
// Example: Search for latest tech news
const newsResults = await mcpClient.callTool("news_search", {
query: "artificial intelligence latest developments",
time_period: "24h",
max_results: 10
});
// Process and display news articles
newsResults.results.forEach(article => {
console.log(`${article.title} - ${article.source}`);
});
🗄️Database Operations
Connect to databases and perform SQL operations
Database Connection
Connect to various database types and execute queries.
// Example: Connect to PostgreSQL
const connection = await mcpClient.callTool("connect_database", {
type: "postgresql",
host: "localhost",
port: 5432,
database: "myapp",
username: "user",
password: "password"
});
// Example: Execute a query
const results = await mcpClient.callTool("execute_query", {
connection_id: connection.id,
query: "SELECT * FROM users WHERE active = true"
});
console.log(results.rows);
Data Analysis
Perform complex data analysis and generate reports.
// Example: Generate sales report
const salesReport = await mcpClient.callTool("execute_query", {
connection_id: connection.id,
query: `
SELECT
DATE(created_at) as date,
COUNT(*) as orders,
SUM(total_amount) as revenue
FROM orders
WHERE created_at >= NOW() - INTERVAL '30 days'
GROUP BY DATE(created_at)
ORDER BY date DESC
`
});
// Process results for visualization
const chartData = salesReport.rows.map(row => ({
date: row.date,
orders: parseInt(row.orders),
revenue: parseFloat(row.revenue)
}));
💻Code Generation and Analysis
Generate, analyze, and refactor code across multiple languages
Code Generation
Generate code snippets and complete functions based on requirements.
// Example: Generate a React component
const componentCode = await mcpClient.callTool("generate_code", {
language: "typescript",
framework: "react",
description: "Create a user profile component with avatar, name, and email",
requirements: [
"Use TypeScript",
"Include proper prop types",
"Add hover effects",
"Make it responsive"
]
});
// Write the generated code to a file
await mcpClient.callTool("write_file", {
path: "/src/components/UserProfile.tsx",
content: componentCode.code
});
Code Analysis
Analyze existing code for improvements and potential issues.
// Example: Analyze code quality
const analysis = await mcpClient.callTool("analyze_code", {
file_path: "/src/components/UserProfile.tsx",
analysis_type: "quality",
include_suggestions: true
});
console.log("Code Quality Score:", analysis.score);
console.log("Suggestions:", analysis.suggestions);
// Example: Find potential bugs
const bugReport = await mcpClient.callTool("analyze_code", {
file_path: "/src/utils/api.ts",
analysis_type: "security",
include_fixes: true
});
console.log("Security Issues:", bugReport.issues);
🔗Multi-Server Integration
Combine multiple MCP servers for complex workflows
Data Pipeline Example
Create a complete data pipeline using multiple MCP servers.
// Example: Complete data analysis pipeline
async function analyzeUserData() {
// 1. Search for user data online
const searchResults = await mcpClient.callTool("web_search", {
query: "user behavior analytics trends 2024"
});
// 2. Save search results to file
await mcpClient.callTool("write_file", {
path: "/data/search_results.json",
content: JSON.stringify(searchResults, null, 2)
});
// 3. Query database for user metrics
const userMetrics = await mcpClient.callTool("execute_query", {
connection_id: dbConnection.id,
query: "SELECT * FROM user_metrics WHERE date >= '2024-01-01'"
});
// 4. Generate analysis report
const reportCode = await mcpClient.callTool("generate_code", {
language: "python",
description: "Create a data visualization script for user metrics",
requirements: ["Use matplotlib", "Include trend analysis", "Export to PDF"]
});
// 5. Save and execute the report
await mcpClient.callTool("write_file", {
path: "/reports/user_analysis.py",
content: reportCode.code
});
console.log("Data analysis pipeline completed!");
}
🎯Next Steps
Continue exploring MCP capabilities