Real-World Use Cases
1. Database Query Server
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
import sqlite3
server = Server("database-server")
DB_PATH = "/path/to/company.db"
@server.list_tools()
async def list_tools():
return [
Tool(
name="query_database",
description="Execute a read-only SQL query against the company database. "
"Tables: customers(id, name, email, plan), "
"orders(id, customer_id, amount, date, status), "
"products(id, name, price, category)",
inputSchema={
"type": "object",
"properties": {
"sql": {"type": "string", "description": "SQL SELECT query"}
},
"required": ["sql"]
}
),
Tool(
name="list_tables",
description="List all tables and their schemas in the database",
inputSchema={"type": "object", "properties": {}}
)
]
@server.call_tool()
async def call_tool(name: str, arguments: dict):
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
if name == "list_tables":
cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
tables = cursor.fetchall()
result = []
for table in tables:
cursor.execute(f"PRAGMA table_info({table[0]})")
cols = cursor.fetchall()
result.append(f"{table[0]}: {', '.join(c[1] for c in cols)}")
conn.close()
return [TextContent(type="text", text="\n".join(result))]
elif name == "query_database":
sql = arguments["sql"].strip()
# Safety: only allow SELECT
if not sql.upper().startswith("SELECT"):
return [TextContent(type="text", text="Error: Only SELECT queries allowed")]
cursor.execute(sql)
columns = [desc[0] for desc in cursor.description]
rows = cursor.fetchall()
conn.close()
# Format as table
header = " | ".join(columns)
data = "\n".join(" | ".join(str(v) for v in row) for row in rows[:50])
return [TextContent(type="text", text=f"{header}\n{'─'*len(header)}\n{data}")]
conn.close()
async def main():
async with stdio_server() as (read_stream, write_stream):
await server.run(read_stream, write_stream)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
2. GitHub Integration Server
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
import httpx
import os
server = Server("github-server")
GITHUB_TOKEN = os.environ["GITHUB_TOKEN"]
HEADERS = {"Authorization": f"token {GITHUB_TOKEN}", "Accept": "application/vnd.github.v3+json"}
@server.list_tools()
async def list_tools():
return [
Tool(
name="list_repos",
description="List repositories for a GitHub user or organization",
inputSchema={
"type": "object",
"properties": {
"owner": {"type": "string", "description": "GitHub username or org"}
},
"required": ["owner"]
}
),
Tool(
name="get_pull_requests",
description="List open pull requests for a repository",
inputSchema={
"type": "object",
"properties": {
"owner": {"type": "string"},
"repo": {"type": "string"}
},
"required": ["owner", "repo"]
}
),
Tool(
name="create_issue",
description="Create a new issue in a repository",
inputSchema={
"type": "object",
"properties": {
"owner": {"type": "string"},
"repo": {"type": "string"},
"title": {"type": "string"},
"body": {"type": "string"}
},
"required": ["owner", "repo", "title"]
}
)
]
@server.call_tool()
async def call_tool(name: str, arguments: dict):
async with httpx.AsyncClient() as client:
if name == "list_repos":
resp = await client.get(
f"https://api.github.com/users/{arguments['owner']}/repos",
headers=HEADERS
)
repos = resp.json()
result = "\n".join(f"• {r['name']} - {r.get('description', 'No description')}"
for r in repos[:10])
return [TextContent(type="text", text=result)]
elif name == "get_pull_requests":
resp = await client.get(
f"https://api.github.com/repos/{arguments['owner']}/{arguments['repo']}/pulls",
headers=HEADERS
)
prs = resp.json()
result = "\n".join(f"#{pr['number']} {pr['title']} by {pr['user']['login']}"
for pr in prs[:10])
return [TextContent(type="text", text=result or "No open PRs")]
elif name == "create_issue":
resp = await client.post(
f"https://api.github.com/repos/{arguments['owner']}/{arguments['repo']}/issues",
headers=HEADERS,
json={"title": arguments["title"], "body": arguments.get("body", "")}
)
issue = resp.json()
return [TextContent(type="text", text=f"Created issue #{issue['number']}: {issue['html_url']}")]
async def main():
async with stdio_server() as (read_stream, write_stream):
await server.run(read_stream, write_stream)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
3. Kubernetes Cluster Management
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
from kubernetes import client, config
server = Server("k8s-server")
config.load_kube_config()
v1 = client.CoreV1Api()
apps_v1 = client.AppsV1Api()
@server.list_tools()
async def list_tools():
return [
Tool(
name="list_pods",
description="List pods in a namespace",
inputSchema={
"type": "object",
"properties": {
"namespace": {"type": "string", "default": "default"}
}
}
),
Tool(
name="get_pod_logs",
description="Get recent logs from a pod",
inputSchema={
"type": "object",
"properties": {
"pod_name": {"type": "string"},
"namespace": {"type": "string", "default": "default"},
"lines": {"type": "integer", "default": 50}
},
"required": ["pod_name"]
}
),
Tool(
name="scale_deployment",
description="Scale a deployment to a specified number of replicas",
inputSchema={
"type": "object",
"properties": {
"deployment": {"type": "string"},
"replicas": {"type": "integer"},
"namespace": {"type": "string", "default": "default"}
},
"required": ["deployment", "replicas"]
}
)
]
@server.call_tool()
async def call_tool(name: str, arguments: dict):
ns = arguments.get("namespace", "default")
if name == "list_pods":
pods = v1.list_namespaced_pod(ns)
result = "\n".join(
f"{p.metadata.name} | {p.status.phase} | {p.spec.containers[0].image}"
for p in pods.items
)
return [TextContent(type="text", text=result or "No pods found")]
elif name == "get_pod_logs":
logs = v1.read_namespaced_pod_log(
arguments["pod_name"], ns, tail_lines=arguments.get("lines", 50)
)
return [TextContent(type="text", text=logs)]
elif name == "scale_deployment":
body = {"spec": {"replicas": arguments["replicas"]}}
apps_v1.patch_namespaced_deployment_scale(
arguments["deployment"], ns, body
)
return [TextContent(type="text",
text=f"Scaled {arguments['deployment']} to {arguments['replicas']} replicas")]
async def main():
async with stdio_server() as (read_stream, write_stream):
await server.run(read_stream, write_stream)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
4. Slack Notification Server
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
import httpx
import os
server = Server("slack-server")
SLACK_TOKEN = os.environ["SLACK_BOT_TOKEN"]
@server.list_tools()
async def list_tools():
return [
Tool(
name="send_message",
description="Send a message to a Slack channel",
inputSchema={
"type": "object",
"properties": {
"channel": {"type": "string", "description": "Channel name (e.g., #general)"},
"message": {"type": "string", "description": "Message text"}
},
"required": ["channel", "message"]
}
),
Tool(
name="list_channels",
description="List available Slack channels",
inputSchema={"type": "object", "properties": {}}
)
]
@server.call_tool()
async def call_tool(name: str, arguments: dict):
async with httpx.AsyncClient() as client:
if name == "list_channels":
resp = await client.get(
"https://slack.com/api/conversations.list",
headers={"Authorization": f"Bearer {SLACK_TOKEN}"}
)
channels = resp.json()["channels"]
result = "\n".join(f"#{c['name']} - {c.get('purpose', {}).get('value', '')}"
for c in channels[:20])
return [TextContent(type="text", text=result)]
elif name == "send_message":
resp = await client.post(
"https://slack.com/api/chat.postMessage",
headers={"Authorization": f"Bearer {SLACK_TOKEN}"},
json={"channel": arguments["channel"], "text": arguments["message"]}
)
if resp.json().get("ok"):
return [TextContent(type="text", text=f"Message sent to {arguments['channel']}")]
return [TextContent(type="text", text=f"Error: {resp.json().get('error')}")]
async def main():
async with stdio_server() as (read_stream, write_stream):
await server.run(read_stream, write_stream)
if __name__ == "__main__":
import asyncio
asyncio.run(main())