Get the FREE Ultimate OpenClaw Setup Guide →

mcp-patterns

npx machina-cli add skill aiskillstore/marketplace/mcp-patterns --openclaw
Files (1)
SKILL.md
4.5 KB

MCP Patterns

Model Context Protocol (MCP) server patterns for building integrations with Claude Code.

Basic MCP Server (Python)

from mcp.server import Server
from mcp.server.stdio import stdio_server

app = Server("my-server")

@app.list_tools()
async def list_tools():
    return [
        {
            "name": "my_tool",
            "description": "Does something useful",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "query": {"type": "string", "description": "Search query"}
                },
                "required": ["query"]
            }
        }
    ]

@app.call_tool()
async def call_tool(name: str, arguments: dict):
    if name == "my_tool":
        result = await do_something(arguments["query"])
        return {"content": [{"type": "text", "text": result}]}
    raise ValueError(f"Unknown tool: {name}")

async def main():
    async with stdio_server() as (read_stream, write_stream):
        await app.run(read_stream, write_stream, app.create_initialization_options())

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

Project Layout

my-mcp-server/
├── src/
│   └── my_server/
│       ├── __init__.py
│       ├── server.py       # Main server logic
│       ├── tools.py        # Tool handlers
│       └── resources.py    # Resource handlers
├── pyproject.toml
└── README.md

Claude Desktop Configuration

Basic Configuration

{
  "mcpServers": {
    "my-server": {
      "command": "python",
      "args": ["-m", "my_server"],
      "env": {
        "MY_API_KEY": "your-key-here"
      }
    }
  }
}

With uv (Recommended)

{
  "mcpServers": {
    "my-server": {
      "command": "uv",
      "args": ["run", "--directory", "/path/to/my-server", "python", "-m", "my_server"],
      "env": {
        "MY_API_KEY": "your-key-here"
      }
    }
  }
}

Quick Reference

PatternUse CaseReference
Tool validationInput sanitization with Pydantic./references/tool-patterns.md
Error handlingGraceful failure responses./references/tool-patterns.md
Multiple toolsCRUD-style tool registration./references/tool-patterns.md
Static resourcesConfig/settings exposure./references/resource-patterns.md
Dynamic resourcesDatabase-backed resources./references/resource-patterns.md
Environment authAPI key from env vars./references/auth-patterns.md
OAuth tokensToken refresh with TTL./references/auth-patterns.md
SQLite cachePersistent state storage./references/state-patterns.md
In-memory cacheTTL-based caching./references/state-patterns.md
Manual testingQuick validation script./references/testing-patterns.md
pytest asyncUnit tests for tools./references/testing-patterns.md

Common Issues

IssueSolution
Server not startingCheck command path, ensure dependencies installed
Tool not appearingVerify list_tools() returns valid schema
Auth failuresCheck env vars are set in config, not shell
Timeout errorsAdd timeout to httpx calls, use async properly
JSON parse errorsEnsure call_tool returns proper content structure

Official Documentation

Additional Resources

For detailed patterns, load:

  • ./references/tool-patterns.md - Validation, error handling, multi-tool registration
  • ./references/resource-patterns.md - Static and dynamic resource exposure
  • ./references/auth-patterns.md - Environment variables, OAuth token refresh
  • ./references/state-patterns.md - SQLite persistence, in-memory caching
  • ./references/testing-patterns.md - Manual test scripts, pytest async patterns

Source

git clone https://github.com/aiskillstore/marketplace/blob/main/skills/0xdarkmatter/mcp-patterns/SKILL.mdView on GitHub

Overview

Model Context Protocol (MCP) server patterns enable exposing tools, resources, and handlers to Claude Code. It provides a basic Python example, a clean project layout, and desktop config guidance to deploy and test MCP-based integrations.

How This Skill Works

Define a server with mcp.server, register tools via list_tools, implement tool logic in call_tool, and expose resources and handlers under a modular project layout. Run the server over stdio or uv and wire it to Claude Desktop using the mcpServers config.

When to Use It

  • Exposing a new tool to Claude Code through MCP.
  • Managing multiple tools with a consistent registration pattern.
  • Serving static and dynamic resources from an MCP server.
  • Configuring and deploying the MCP server via Claude Desktop.
  • Locally testing MCP flows with sample code and quick references.

Quick Start

  1. Step 1: Create a Python MCP server using Server and stdio_server.
  2. Step 2: Implement list_tools and call_tool with a sample tool.
  3. Step 3: Run locally and configure Claude Desktop to connect via mcpServers.

Best Practices

  • Define a clear tool schema with inputSchema and required fields.
  • Validate inputs early and handle errors gracefully in call_tool.
  • Keep tool, resource, and server code modular (tools.py, resources.py).
  • Store sensitive config in environment variables and wire them in the desktop config.
  • Iterate with manual tests and lightweight tests using the included quick reference patterns.

Example Use Cases

  • A basic tool named my_tool with a query string input and content type text.
  • Project layout example my-mcp-server with src/my_server/server.py, tools.py, and resources.py.
  • Claude Desktop basic configuration for a server using command python and an API key env var.
  • UV-based deployment configuration for faster startup.
  • Tool validation and error handling patterns demonstrated in the quick reference.

Frequently Asked Questions

Add this skill to your agents
Sponsor this space

Reach thousands of developers