/ examples / mcp_server / custom_tools_server.py
custom_tools_server.py
 1  #!/usr/bin/env python3
 2  """
 3  Custom Tools MCP Server Example
 4  
 5  Register custom tools and expose them via MCP server.
 6  
 7  Usage:
 8      python custom_tools_server.py
 9  """
10  
11  
12  def main():
13      """Run MCP server with custom tools."""
14      from praisonai.mcp_server.server import MCPServer
15      from praisonai.mcp_server.registry import register_tool, get_tool_registry
16      
17      # Register custom tools
18      @register_tool("custom.greet")
19      def greet(name: str) -> str:
20          """Greet a person by name."""
21          return f"Hello, {name}! Welcome to PraisonAI."
22      
23      @register_tool("custom.calculate")
24      def calculate(expression: str) -> str:
25          """Safely evaluate a mathematical expression."""
26          try:
27              # Only allow safe math operations
28              allowed = set("0123456789+-*/.(). ")
29              if not all(c in allowed for c in expression):
30                  return "Error: Invalid characters in expression"
31              result = eval(expression)  # Safe due to character filtering
32              return f"Result: {result}"
33          except Exception as e:
34              return f"Error: {e}"
35      
36      @register_tool("custom.reverse")
37      def reverse_text(text: str) -> str:
38          """Reverse a text string."""
39          return text[::-1]
40      
41      @register_tool("custom.word_count")
42      def word_count(text: str) -> str:
43          """Count words in text."""
44          words = text.split()
45          return f"Word count: {len(words)}"
46      
47      # Show registered tools
48      registry = get_tool_registry()
49      tools = registry.list_all()
50      print(f"Registered {len(tools)} custom tools:")
51      for tool in tools:
52          print(f"  - {tool.name}: {tool.description}")
53      print()
54      
55      # Create and run server
56      server = MCPServer(
57          name="praisonai-custom",
58          version="1.0.0",
59          instructions="Custom tools MCP server example.",
60      )
61      
62      print("Starting MCP server on http://127.0.0.1:8080/mcp")
63      server.run(
64          transport="http-stream",
65          host="127.0.0.1",
66          port=8080,
67      )
68  
69  
70  if __name__ == "__main__":
71      main()