mcp-server-builder
Build Model Context Protocol servers for Claude Code integration
What this skill does
# MCP Server Builder Skill
> Build new MCP servers following established patterns for consistency and reliability.
## Overview
This skill provides a template and guidelines for building new MCP servers that integrate with the agentic workspace. All servers follow the same patterns for:
- Configuration via environment variables
- Error handling and logging
- Tool registration
- Testing
- Documentation
## Prerequisites
```bash
pip install mcp>=1.0.0
```
## Server Template
### Step 1: Create Directory Structure
```bash
mcp/servers/{server-name}/
├── server.py # Main server implementation
├── requirements.txt # Python dependencies
├── test_{name}.py # Test suite
├── README.md # Server documentation
└── config.example.env # Example configuration
```
### Step 2: Server Implementation Template
**File: `mcp/servers/{server-name}/server.py`**
```python
#!/usr/bin/env python3
"""
{Server Name} MCP Server - {Brief description}.
"""
import asyncio
import json
import logging
import os
from typing import Optional
from mcp.server import Server
from mcp.server.stdio import stdio_server
# =============================================================================
# Configuration
# =============================================================================
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO")
# Add server-specific config here
# EXAMPLE_API_KEY = os.getenv("EXAMPLE_API_KEY")
# EXAMPLE_TIMEOUT = int(os.getenv("EXAMPLE_TIMEOUT", "30"))
# Setup logging
logging.basicConfig(
level=getattr(logging, LOG_LEVEL),
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
# =============================================================================
# Server Implementation
# =============================================================================
class {ServerName}Server:
"""
{Description of what this server does}.
Tools provided:
- tool_one: Description
- tool_two: Description
"""
def __init__(self):
self.server = Server("{server-name}")
self._validate_config()
self._setup_tools()
logger.info("{ServerName} server initialized")
def _validate_config(self):
"""Validate required configuration."""
# Example validation:
# if not EXAMPLE_API_KEY:
# raise ValueError("EXAMPLE_API_KEY environment variable required")
pass
def _setup_tools(self):
"""Register MCP tools."""
@self.server.tool()
async def example_tool(
param1: str,
param2: Optional[int] = 10
) -> str:
"""
Brief description of what this tool does.
Args:
param1: Description of param1
param2: Description of param2 (default: 10)
Returns:
JSON string with result
"""
try:
logger.debug(f"example_tool called: param1={param1}, param2={param2}")
# Implementation here
result = {
"status": "success",
"param1": param1,
"param2": param2
}
return json.dumps(result)
except Exception as e:
logger.error(f"example_tool failed: {e}")
return json.dumps({
"status": "error",
"error": str(e)
})
@self.server.tool()
async def another_tool(query: str) -> str:
"""
Another tool description.
Args:
query: The query to process
"""
try:
# Implementation
return json.dumps({"result": query})
except Exception as e:
logger.error(f"another_tool failed: {e}")
return json.dumps({"status": "error", "error": str(e)})
async def run(self):
"""Run the MCP server."""
logger.info("Starting {server-name} server...")
async with stdio_server() as (read_stream, write_stream):
await self.server.run(read_stream, write_stream)
# =============================================================================
# Entry Point
# =============================================================================
def main():
server = {ServerName}Server()
asyncio.run(server.run())
if __name__ == "__main__":
main()
```
### Step 3: Requirements Template
**File: `mcp/servers/{server-name}/requirements.txt`**
```
mcp>=1.0.0
# Add server-specific dependencies below
# requests>=2.28.0
# aiohttp>=3.8.0
```
### Step 4: Test Template
**File: `mcp/servers/{server-name}/test_{name}.py`**
```python
#!/usr/bin/env python3
"""Tests for {server-name} MCP server."""
import json
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(__file__))
from server import {ServerName}Server
class Test{ServerName}Server:
"""Test suite for {ServerName}Server."""
@pytest.fixture
def server(self):
"""Create server instance for testing."""
return {ServerName}Server()
def test_server_initialization(self, server):
"""Test server initializes correctly."""
assert server.server is not None
assert server.server.name == "{server-name}"
def test_config_validation(self):
"""Test configuration validation."""
# Test with missing required config
# with pytest.raises(ValueError):
# os.environ.pop("REQUIRED_VAR", None)
# {ServerName}Server()
pass
@pytest.mark.asyncio
async def test_example_tool(self, server):
"""Test example_tool function."""
# Get the tool function
tools = server.server._tools
example_tool = tools.get("example_tool")
# Call it
result = await example_tool("test_value", 20)
data = json.loads(result)
assert data["status"] == "success"
assert data["param1"] == "test_value"
assert data["param2"] == 20
@pytest.mark.asyncio
async def test_example_tool_defaults(self, server):
"""Test example_tool with default values."""
tools = server.server._tools
example_tool = tools.get("example_tool")
result = await example_tool("test")
data = json.loads(result)
assert data["param2"] == 10 # default value
@pytest.mark.asyncio
async def test_error_handling(self, server):
"""Test error handling returns proper format."""
# Trigger an error condition and verify response format
pass
def test_imports():
"""Test all imports work."""
from server import {ServerName}Server, main
print("✅ Imports working")
def test_quick():
"""Quick smoke test."""
server = {ServerName}Server()
assert server is not None
print("✅ Quick test passed")
if __name__ == "__main__":
test_imports()
test_quick()
print("
✅ All basic tests passed!")
print("Run 'pytest test_{name}.py -v' for full test suite")
```
### Step 5: README Template
**File: `mcp/servers/{server-name}/README.md`**
```markdown
# {Server Name} MCP Server
{Brief description of what this server does and why it exists.}
## Tools
| Tool | Description |
|------|-------------|
| `example_tool` | Does X with Y |
| `another_tool` | Does A with B |
## Configuration
| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `LOG_LEVEL` | No | `INFO` | Logging level |
| `EXAMPLE_API_KEY` | Yes | - | API key for service |
## Installation
```bash
cd mcp/servers/{server-name}
pip install -r requirements.txt
```
## Usage
### As MCP Server
Add to `.claude.json`:
```json
{
"mcpServers": {
"{server-name}": {
"command": "python",
"args": ["mcp/servers/{server-name}/server.py"],
"env": {
"EXAMPLE_API_KEY": "${EXARelated in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.