How to define tools in MCP server
Quick answer
In an
MCP server, define tools by creating Python classes that implement the Tool interface with a run method. Register these tool instances with the Server to expose them to AI agents for invocation during conversations.PREREQUISITES
Python 3.8+pip install mcpBasic knowledge of Python classes and async programming
Setup
Install the official mcp Python package and prepare your environment variables if needed. The mcp package provides the server and tool interfaces for defining and running tools.
pip install mcp Step by step
Define a tool by subclassing mcp.server.Tool and implementing the run method. Then create an mcp.server.Server instance, register your tool, and start the server using stdio_server for standard input/output communication.
import asyncio
from mcp.server import Server, Tool
from mcp.server.stdio import stdio_server
class EchoTool(Tool):
async def run(self, input: str) -> str:
# Simply returns the input text
return f"Echo: {input}"
async def main():
server = Server()
# Register the tool with a name
server.register_tool("echo", EchoTool())
# Start the MCP server using stdio transport
await stdio_server(server)
if __name__ == "__main__":
asyncio.run(main()) Common variations
You can define multiple tools by creating additional subclasses of Tool and registering them with different names. Tools can perform synchronous or asynchronous operations. The server supports other transports besides stdio, such as SSE or TCP, depending on your deployment needs.
class AddTool(Tool):
async def run(self, input: str) -> str:
# Expect input as 'num1 num2'
parts = input.split()
if len(parts) != 2:
return "Error: Provide two numbers separated by space"
try:
num1, num2 = map(float, parts)
return str(num1 + num2)
except ValueError:
return "Error: Invalid numbers"
# Register multiple tools
server = Server()
server.register_tool("echo", EchoTool())
server.register_tool("add", AddTool()) Troubleshooting
- If the server does not respond, ensure you are running it with
asyncio.run(main())and that your environment supports stdio communication. - If tools are not found, verify you registered them with the correct names before starting the server.
- For debugging, add logging inside your
runmethods to trace input and output.
Key Takeaways
- Define tools by subclassing
Tooland implementing the asyncrunmethod. - Register tools with the
Serverinstance before starting the MCP server. - Use
stdio_serverfor simple local testing and communication. - Multiple tools can be registered and invoked by name from AI agents.
- Add error handling and logging inside tools for robust integration.