How to Build Custom MCP Servers for OpenClaw
Custom MCP servers let OpenClaw agents use your internal APIs and data. This guide shows you how to scaffold, build, and connect a Model Context Protocol server. You will learn to expose tools, resources, and prompts that give your AI agents safe access to your business's critical systems.
Why Build a Custom MCP Server?
OpenClaw agents work well alone, but they do more when connected to your data. A custom Model Context Protocol (MCP) server turns your internal APIs into tools an AI agent can use.
Fast.io already gives you access to 251 pre-built MCP tools for standard tasks like file management and web searching. However, unique business logic often needs a custom approach. According to Postman, only 24% of developers design APIs for AI agents. This gives you a chance to build tools that fit your needs.
A custom server lets you control what data the agent sees and how it uses it. You might build a custom server to:
- Query an internal SQL database without exposing it to the public internet
- Trigger CI/CD pipelines with chat commands in Slack or Discord
- Manage proprietary file formats in Fast.io Workspaces
- Work with legacy systems that have no public APIs
Wrapping these systems in an MCP server creates a standard interface. Any OpenClaw agent, whether local or hosted, can then understand and use them safely.
Planning Your MCP Server
Estimate the scope of your project before writing code. Development time depends on complexity.
- Basic Prototypes: Simple servers with basic tools (like a calculator or status checker) can be built in minutes.
- Internal Integrations: Wrapping an existing internal API typically takes time to handle authentication and error mapping.
- Production Systems: Full-scale servers with detailed logging, OAuth, and high concurrency can take weeks to harden.
Start small. Build a "Hello World" tool first, then add complexity. This helps you debug connection issues with OpenClaw early.
Host Your Agent's Data on Fast.io
Give your OpenClaw agents a secure, high-performance workspace with built-in RAG and 251 pre-built MCP tools.
Prerequisites and Tech Stack
Set up your environment before you code. You can build MCP servers in most languages, but Python and TypeScript have the best SDK support.
We will use Python and the fastmcp library for this guide. It is the fastest way to get a prototype running. You need:
- Python 3.10+ installed on your local machine
- uv (recommended) or pip for package management
- OpenClaw installed locally or access to a remote instance
- Basic async programming knowledge
If you prefer TypeScript, use the @modelcontextprotocol/sdk package. The concepts (Tools, Resources, and Prompts) are identical across languages. Choose the language that matches your existing codebase to make maintenance easier.
Step 1: Scaffold Your Project
Create a new directory for your MCP server. Keep it separate from your main app so you can deploy it on its own.
Initialize a Python project and install dependencies. We recommend uv because it is faster than pip, but standard tools work fine.
# Create project directory
mkdir my-custom-mcp
cd my-custom-mcp
# Create virtual environment and install fastmcp
uv venv
source .venv/bin/activate
uv pip install fastmcp
Create a file named server.py. This is your server entry point. fastmcp manages the JSON-RPC protocol details like capabilities, ping/pong, and error handling. You can focus on your tool logic.
Step 2: Define Your Tools
In MCP, a "tool" is a function the AI calls. You define tools with decorators. The docstring tells the AI when and how to use the tool.
Here is an example with a simple status check and a data fetcher.
from fastmcp import FastMCP
from typing import Optional
# Initialize the server
mcp = FastMCP("MyInternalTools")
@mcp.tool()
def check_system_status(system_id: str) -> str:
"""Checks the health status of an internal system."""
# Mock response
return "Online"
@mcp.tool()
def get_customer_data(customer_id: str, include_history: bool = False) -> str:
"""
Retrieves summary data for a customer by ID.
Use this before taking action on a customer account.
Args:
customer_id: The unique ID starting with 'cust_'
include_history: Whether to include recent transaction logs
"""
if not customer_id.startswith("cust_"):
return "Error: Invalid ID format. Must start with 'cust_'."
data = f"Customer {customer_id}: Plan=Enterprise, Status=Active"
if include_history:
data += " | History: [Login, View, Purchase]"
return data
if __name__ == "__main__":
mcp.run()
OpenClaw uses the type hints to validate arguments before running your code. This stops common errors before they reach your internal API. If you need stricter validation, Pydantic models are fully supported for complex arguments.
Step 3: Add Resources and Prompts
MCP works with more than just tools. You can also expose Resources (read-only data) and Prompts (reusable context).
Resources allow agents to read files or data streams like they are local files. This works well for logs or config files.
@mcp.resource("internal://logs/{date}")
def get_logs(date: str) -> str:
"""Reads system logs for a specific date."""
# In a real app, read from a file or DB
return f"Logs for {date}: No critical errors found."
Prompts help users get started with complex tasks. They act as templates for agent interactions.
@mcp.prompt()
def debug_system(system_id: str) -> str:
"""Helps the user debug a specific system."""
return f"Analyze the logs for system {system_id} and look for errors."
Adding these features makes your server a complete "agent skill" instead of just a list of functions. It gives the agent context (Resources) and guidance (Prompts) alongside capability (Tools).
Step 4: Testing with MCP Inspector
Test your server in isolation before connecting it to OpenClaw. The MCP Inspector is a web debugger. It lets you manually call your tools and view JSON-RPC traffic.
To run the inspector:
npx @modelcontextprotocol/inspector uv run server.py
This command launches a local web interface. From there, you can:
- List Tools: Verify that
check_system_statusandget_customer_dataappear. - Execute Calls: Manually input arguments like
customer_id="cust_123"and see the output. - Check Errors: Test invalid inputs to ensure your error messages are clear.
Debugging here is faster than inside the full OpenClaw agent loop. Once it works in the Inspector, it will work in OpenClaw.
Step 5: Security Best Practices
Exposing internal tools to an AI agent requires security. Treat the agent like a user with limits.
- Read-Only by Default: Start with tools that only read data (
get_status,fetch_logs). Add write capabilities (restart_server,update_record) only when necessary. - Input Validation: Never trust the LLM's output blindly. Validate all arguments. If a tool expects a file path, make sure it doesn't traverse directories (
../). - Human-in-the-Loop: Require human confirmation for sensitive actions. OpenClaw supports this natively, but you can also build it into your tool logic by returning a "Confirmation required" string first.
If you deploy your server to the public internet (e.g., for remote agents), make sure you use transport-layer security (HTTPS) and implement authentication headers to prevent unauthorized access.
Step 6: Performance and Latency
Where you run your server matters. Latency between the agent and your server affects how "snappy" the experience feels.
- Local Servers (Stdio): When OpenClaw runs a server locally via stdio, latency is negligible (often under 10ms). This works best for development and high-frequency tools.
- Remote Servers (SSE): Deploying over HTTP Server-Sent Events adds network round-trip time.
- Serverless Cold Starts: If you deploy to a serverless platform, cold starts can add 500ms to 2 seconds of latency to the first request.
For production, use persistent containers (like Docker) instead of serverless functions. This avoids cold start delays for interactive agents.
Step 7: Connect and Deploy
To test locally, add your server to the OpenClaw config file (typically openclaw.config.yaml or claude_desktop_config.json if using Claude Desktop).
{
"mcpServers": {
"my-custom-server": {
"command": "uv",
"args": ["run", "server.py"]
}
}
}
Wrap your server in a Docker container for production. This keeps dependencies consistent. You can then host this container on your internal infrastructure or a cloud provider. OpenClaw agents hosted on Fast.io Storage for Agents can connect to these remote servers securely via SSE.
Once deployed, share your server with your team or publish it to the OpenClaw Registry.
Frequently Asked Questions
What is the difference between stdio and SSE for MCP?
Stdio is used for local connections where the agent spawns the server process directly. SSE (Server-Sent Events) is used for remote connections where the agent connects to a running web server over HTTP.
Can I use Node.js instead of Python?
Yes, you can use the official Node.js SDK to build MCP servers. The concepts are identical, but you will use TypeScript or JavaScript for the implementation.
How do I handle authentication in my custom server?
Handle authentication within your tool logic. You can load API keys from environment variables in your server code and use them to make authenticated requests to your backend.
Is it safe to expose my database via MCP?
Yes, if you define read-only tools or strict input validation. Never create a generic 'execute_sql' tool; instead, create specific tools like 'get_user_by_email' that run parameterized queries.
How long does it take to build a basic MCP server?
Most developers can prototype a basic integration in under an hour. Simple servers with basic tools often take very little time to get running locally.
Do I need to pay for OpenClaw to use custom servers?
No, OpenClaw is open-source. You can run it locally with your custom servers for free. Fast.io offers managed hosting if you need persistent, shared agents.
How do I debug my MCP server?
Use the MCP Inspector tool (`npx @modelcontextprotocol/inspector`) to run your server in isolation. This lets you manually trigger tools and see the JSON-RPC responses before connecting it to an agent.
Related Resources
Host Your Agent's Data on Fast.io
Give your OpenClaw agents a secure, high-performance workspace with built-in RAG and 251 pre-built MCP tools.