🧰 MCP Code Templates
Ready-to-copy MCP server and tool templates. Just paste, customize, and deploy!
📦 Basic MCP SDK Server Template
Perfect starting point for any MCP server
A minimal, production-ready MCP server with proper error handling and logging.
Features:
- TypeScript support
- Stdio and SSE transports
- Error handling
- Example tool included
server.ts
#!/usr/bin/env node
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
interface ToolArguments {
[key: string]: unknown;
}
// Define your tools
const TOOLS = [
{
name: "example_tool",
description: "An example tool that echoes input",
inputSchema: {
type: "object",
properties: {
message: {
type: "string",
description: "Message to echo back"
}
},
required: ["message"]
}
}
];
// Create server instance
const server = new Server(
{
name: "my-mcp-server",
version: "1.0.0",
},
{
capabilities: {
tools: {},
},
}
);
// List available tools
server.setRequestHandler(ListToolsRequestSchema, async () => {
return { tools: TOOLS };
});
// Execute tool calls
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
try {
switch (name) {
case "example_tool": {
const { message } = args as ToolArguments;
return {
content: [
{
type: "text",
text: `Echo: ${message}`
}
]
};
}
default:
throw new Error(`Unknown tool: ${name}`);
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return {
content: [
{
type: "text",
text: `Error: ${errorMessage}`
}
],
isError: true
};
}
});
// Start server
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("MCP Server running on stdio");
}
main().catch((error) => {
console.error("Fatal error:", error);
process.exit(1);
});
package.json
{
"name": "my-mcp-server",
"version": "1.0.0",
"type": "module",
"bin": {
"my-mcp-server": "./build/server.js"
},
"scripts": {
"build": "tsc",
"start": "node build/server.js",
"dev": "tsx watch server.ts"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^0.5.0"
},
"devDependencies": {
"@types/node": "^20.0.0",
"typescript": "^5.0.0",
"tsx": "^4.0.0"
}
}
📊 Log Analyzer MCP Tool
Analyze logs and extract insights with AI
import fs from 'fs/promises';
import path from 'path';
// Add to your TOOLS array
{
name: "analyze_logs",
description: "Analyze log files for errors, patterns, and insights",
inputSchema: {
type: "object",
properties: {
logPath: {
type: "string",
description: "Path to the log file"
},
pattern: {
type: "string",
description: "Optional regex pattern to search for"
},
maxLines: {
type: "number",
description: "Maximum number of lines to analyze",
default: 1000
}
},
required: ["logPath"]
}
}
// Add to your tool handler
case "analyze_logs": {
const { logPath, pattern, maxLines = 1000 } = args;
// Read log file
const content = await fs.readFile(logPath, 'utf-8');
const lines = content.split('\n').slice(0, maxLines);
// Analyze logs
const results = {
totalLines: lines.length,
errors: lines.filter(line => /error|exception|fail/i.test(line)).length,
warnings: lines.filter(line => /warn|warning/i.test(line)).length,
matched: pattern ? lines.filter(line => new RegExp(pattern).test(line)) : []
};
return {
content: [
{
type: "text",
text: JSON.stringify(results, null, 2)
}
]
};
}
🐙 GitHub Automation MCP Tool
Create issues, PRs, and manage repositories
import { Octokit } from '@octokit/rest';
// Initialize GitHub client
const octokit = new Octokit({
auth: process.env.GITHUB_TOKEN
});
// Add to your TOOLS array
{
name: "create_github_issue",
description: "Create a new GitHub issue",
inputSchema: {
type: "object",
properties: {
owner: {
type: "string",
description: "Repository owner"
},
repo: {
type: "string",
description: "Repository name"
},
title: {
type: "string",
description: "Issue title"
},
body: {
type: "string",
description: "Issue body/description"
},
labels: {
type: "array",
items: { type: "string" },
description: "Array of label names"
}
},
required: ["owner", "repo", "title"]
}
}
// Add to your tool handler
case "create_github_issue": {
const { owner, repo, title, body, labels } = args;
const issue = await octokit.rest.issues.create({
owner,
repo,
title,
body: body || '',
labels: labels || []
});
return {
content: [
{
type: "text",
text: `Created issue #${issue.data.number}: ${issue.data.html_url}`
}
]
};
}
💡 Setup Required: Install
@octokit/rest and set
GITHUB_TOKEN environment variable.
💬 Slack Alert MCP Tool
Send notifications and messages to Slack
import { WebClient } from '@slack/web-api';
// Initialize Slack client
const slack = new WebClient(process.env.SLACK_TOKEN);
// Add to your TOOLS array
{
name: "send_slack_message",
description: "Send a message to a Slack channel",
inputSchema: {
type: "object",
properties: {
channel: {
type: "string",
description: "Channel ID or name (e.g., #general)"
},
message: {
type: "string",
description: "Message text"
},
priority: {
type: "string",
enum: ["info", "warning", "error"],
description: "Message priority level"
},
mention: {
type: "string",
description: "Optional user to mention (e.g., @channel, @here)"
}
},
required: ["channel", "message"]
}
}
// Add to your tool handler
case "send_slack_message": {
const { channel, message, priority = 'info', mention } = args;
const emojiMap = {
info: ':information_source:',
warning: ':warning:',
error: ':rotating_light:'
};
const formattedMessage = `${emojiMap[priority]} ${mention ? mention + ' ' : ''}${message}`;
const result = await slack.chat.postMessage({
channel,
text: formattedMessage
});
return {
content: [
{
type: "text",
text: `Message sent to ${channel} (ts: ${result.ts})`
}
]
};
}
💡 Setup Required: Install
@slack/web-api and set
SLACK_TOKEN environment variable.
🗄️ Database Query MCP Tool
Safe read-only database queries
import { createPool } from '@vercel/postgres';
// Initialize database connection
const db = createPool({
connectionString: process.env.DATABASE_URL
});
// Add to your TOOLS array
{
name: "query_database",
description: "Execute a read-only SQL query",
inputSchema: {
type: "object",
properties: {
query: {
type: "string",
description: "SQL query to execute (SELECT only)"
},
limit: {
type: "number",
description: "Maximum rows to return",
default: 100
}
},
required: ["query"]
}
}
// Add to your tool handler
case "query_database": {
const { query, limit = 100 } = args;
// Safety: Only allow SELECT queries
if (!query.trim().toLowerCase().startsWith('select')) {
throw new Error('Only SELECT queries are allowed');
}
// Add LIMIT if not present
const safeQuery = query.includes('LIMIT')
? query
: `${query} LIMIT ${limit}`;
const result = await db.query(safeQuery);
return {
content: [
{
type: "text",
text: JSON.stringify({
rows: result.rows,
count: result.rowCount
}, null, 2)
}
]
};
}
⚠️ Security: This template only allows SELECT
queries. Always validate and sanitize user input!
🚀 Quick Start with Templates
1. Copy the template code above
2. Install required dependencies
3. Customize for your use case
4. Test locally
5. Deploy to production!