To seamlessly integrate a collection of asynchronous Python functions (each accepting an input dictionary and returning a tuple of (result, error)) into an MCP server using FastMCP, you can follow these steps:
Steps to Integrate Functions into FastMCP
-
Organize Your Functions:
- Ensure all your asynchronous functions are in separate Python files or modules.
- Each function should follow the signature:
async def function_name(input_dict: dict) -> tuple.
-
Create the MCP Server:
- Use the
FastMCP class to initialize the server.
- Dynamically load and register your functions as MCP tools.
-
Register Functions Dynamically:
- Use Python's
importlib to dynamically import your functions from the files.
- Decorate each function with
@mcp.tool() to expose it as an MCP tool.
-
Handle Input and Output:
- Wrap each function to ensure it adheres to the MCP tool signature, handling the input dictionary and returning the result/error tuple.
Implementation Example
Below is an example implementation:
Directory Structure
project/
│
├── server.py # Main MCP server
├── tools/
│ ├── __init__.py # Empty or used for imports
│ ├── tool1.py # Contains async functions
│ ├── tool2.py # Contains async functions
Example Tool File (tools/tool1.py)
async def example_tool(input_dict: dict) -> tuple:
"""
Example tool function.
Args:
input_dict: Input dictionary.
Returns:
A tuple of (result, error).
"""
try:
result = {"message": f"Hello, {input_dict.get('name', 'World')}!"}
return result, None
except Exception as e:
return None, str(e)
MCP Server (server.py)
import importlib
import pkgutil
from mcp.server.fastmcp import FastMCP
# Initialize the MCP server
mcp = FastMCP("async-tools-server")
def register_tools_from_directory(directory: str):
"""
Dynamically load and register tools from a directory.
Args:
directory: The directory containing tool modules.
"""
package = directory.replace("/", ".") # Convert to package format
for _, module_name, _ in pkgutil.iter_modules([directory]):
module = importlib.import_module(f"{package}.{module_name}")
for attr_name in dir(module):
attr = getattr(module, attr_name)
if callable(attr) and hasattr(attr, "__annotations__") and "input_dict" in attr.__annotations__:
# Wrap the tool function to match MCP tool signature
@mcp.tool(name=attr_name)
async def tool_wrapper(input_dict: dict, func=attr):
result, error = await func(input_dict)
return {"result": result, "error": error}
# Register tools from the "tools" directory
register_tools_from_directory("tools")
# Run the server
if __name__ == "__main__":
mcp.run(transport="stdio")
How It Works
-
Dynamic Tool Registration:
- The
register_tools_from_directory function scans the specified directory for modules.
- It imports each module and checks for callable functions with the expected signature (
input_dict as a parameter).
-
Tool Wrapping:
- Each function is wrapped with a decorator to expose it as an MCP tool.
- The wrapper ensures the function's output is formatted as required by MCP (e.g., a dictionary with
result and error).
-
Server Execution:
- The MCP server is started using
mcp.run(transport="stdio").
Example Interaction
- Tool List:
The MCP client can query the server for available tools, which will include all dynamically registered tools.
- Tool Call:
A client can invoke a tool by sending an input dictionary. The server will execute the corresponding function and return the result/error tuple.
Advantages
- Scalability: Easily add new tools by creating new files in the
tools directory.
- Asynchronous Support: Fully supports async functions for non-blocking operations.
- Dynamic Loading: No need to manually register each tool; the server dynamically discovers and registers them.
This approach ensures seamless integration of your asynchronous functions into an MCP server while maintaining flexibility and scalability.