Module praisonaiagents.mcp

The MCP (Model Context Protocol) module provides integration with MCP servers, enabling AI agents to interact with external tools and services through standardized protocols with support for both STDIO and SSE transports.

Classes

MCP

The main class for connecting to and interacting with MCP servers.

Parameters

  • command: str - Command to execute or SSE endpoint URL
  • args: Optional[List[str]] = None - Arguments for the command
  • env: Optional[Dict[str, str]] = None - Environment variables
  • debug: bool = False - Enable debug logging
  • timeout: int = 60 - Timeout for server initialization

Properties

  • tools - Dictionary of available tools from the MCP server
  • tool_functions - Dictionary of callable wrapper functions

Methods

  • get_tools() - Get list of available tools with schemas
  • get_openai_tools_schema() - Get OpenAI function calling compatible schema
  • execute_tool(tool_name, arguments) - Execute a specific tool
  • shutdown() - Gracefully shutdown the MCP connection

SSEMCPClient

Client for Server-Sent Events (SSE) based MCP servers.

Parameters

  • url: str - SSE endpoint URL
  • debug: bool = False - Enable debug logging

Methods

  • connect() - Establish SSE connection
  • disconnect() - Close SSE connection
  • list_tools() - Get available tools
  • call_tool(name, arguments) - Execute a tool

Transport Mechanisms

STDIO Transport

For local MCP servers using subprocess communication.
# Python script
mcp = MCP("/usr/bin/python3", args=["mcp_server.py"])

# NPX package
mcp = MCP("npx", args=["@modelcontextprotocol/server-brave-search"])

# Direct command
mcp = MCP("/path/to/mcp-server")

SSE Transport

For remote MCP servers accessible via HTTP.
# HTTP endpoint
mcp = MCP("http://localhost:8080/sse")

# HTTPS endpoint
mcp = MCP("https://api.example.com/mcp/sse")

Usage Examples

Basic MCP Integration

from praisonaiagents import MCP

# Initialize MCP connection
mcp = MCP("npx", args=["@modelcontextprotocol/server-filesystem"])

# Get available tools
tools = mcp.get_tools()
print(f"Available tools: {list(tools.keys())}")

# Execute a tool
result = mcp.execute_tool("read_file", {
    "path": "/tmp/data.txt"
})
print(f"File content: {result}")

# Cleanup
mcp.shutdown()

Agent Integration

from praisonaiagents import Agent, MCP

# Create MCP instance
mcp_tools = MCP("npx", args=["@modelcontextprotocol/server-github"])

# Create agent with MCP tools
agent = Agent(
    name="GitHub Assistant",
    role="Repository manager",
    goal="Help with GitHub operations",
    tools=mcp_tools.tool_functions.values()
)

# Agent can now use MCP tools
response = agent.chat("List the open issues in the repository")

Custom Python MCP Server

# mcp_calculator.py
import asyncio
import json
import sys

async def handle_request(request):
    if request["method"] == "initialize":
        return {"protocolVersion": "0.1.0", "serverInfo": {"name": "calculator"}}
    
    elif request["method"] == "tools/list":
        return {
            "tools": [{
                "name": "calculate",
                "description": "Perform calculation",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "expression": {"type": "string"}
                    },
                    "required": ["expression"]
                }
            }]
        }
    
    elif request["method"] == "tools/call":
        expr = request["params"]["arguments"]["expression"]
        result = eval(expr)  # Simple example - use ast.literal_eval in production
        return {"result": str(result)}

# MCP server implementation...

# Use with:
mcp = MCP("/usr/bin/python3", args=["mcp_calculator.py"])

SSE-Based MCP Server

from praisonaiagents import MCP

# Connect to remote SSE server
mcp = MCP("http://localhost:8080/sse", debug=True)

# List available tools
tools = mcp.get_tools()
for name, schema in tools.items():
    print(f"Tool: {name}")
    print(f"Description: {schema.get('description', 'N/A')}")

# Execute remote tool
result = mcp.execute_tool("search", {
    "query": "AI agents",
    "limit": 10
})

Environment Variables

# Pass environment variables to MCP server
mcp = MCP(
    command="python",
    args=["api_server.py"],
    env={
        "API_KEY": "your-api-key",
        "API_URL": "https://api.example.com"
    }
)

Error Handling

from praisonaiagents import MCP

try:
    mcp = MCP("npx", args=["@modelcontextprotocol/server-example"])
    
    # Use tools
    result = mcp.execute_tool("unknown_tool", {})
    
except TimeoutError:
    print("MCP server initialization timed out")
except Exception as e:
    print(f"MCP error: {e}")
finally:
    if 'mcp' in locals():
        mcp.shutdown()

OpenAI Function Calling Integration

The MCP module automatically generates OpenAI-compatible function schemas:
# Get OpenAI tools schema
openai_schema = mcp.get_openai_tools_schema()

# Use with OpenAI client
response = openai_client.chat.completions.create(
    model="gpt-4",
    messages=messages,
    tools=openai_schema,
    tool_choice="auto"
)

Configuration Options

Debug Mode

# Enable detailed logging
mcp = MCP("command", debug=True)

Custom Timeout

# Increase timeout for slow-starting servers
mcp = MCP("command", timeout=120)  # 2 minutes

Working Directory

# The MCP server inherits the current working directory
import os
os.chdir("/path/to/project")
mcp = MCP("python", args=["server.py"])

Best Practices

  1. Resource Management - Always call shutdown() when done
  2. Error Handling - Wrap MCP operations in try-except blocks
  3. Timeout Configuration - Adjust timeout for slow servers
  4. Environment Isolation - Use env parameter for sensitive data
  5. Debug Logging - Enable debug mode during development
  6. Schema Validation - Validate tool schemas before use

Common MCP Servers

  • @modelcontextprotocol/server-filesystem - File system operations
  • @modelcontextprotocol/server-github - GitHub API integration
  • @modelcontextprotocol/server-postgres - PostgreSQL database access
  • @modelcontextprotocol/server-slack - Slack integration
  • @modelcontextprotocol/server-memory - Persistent memory storage