Skip to content

MCP Tools

MCP (Model Context Protocol) is ByteBuddy's extension mechanism that allows connecting to external MCP servers to obtain additional tools, resources, and prompt functionality.

How MCP Works

In ByteBuddy, MCP works through the following methods:

  1. Connect External Servers: Connect to MCP servers via stdio, HTTP, or WebSocket
  2. Discover Available Features: Automatically discover tools, resources, and prompts provided by servers
  3. AI Assistant Invocation: AI assistants can call these MCP features during conversations
  4. Permission Control: Each connection is independently configured to ensure secure usage

Configuration File Location

MCP server configuration is located in your ByteBuddy configuration file:

yaml
# config.yaml
name: My ByteBuddy Config
version: 0.0.1
schema: v1

mcpServers:
  # MCP server configuration goes here

Connection Types

ByteBuddy supports multiple MCP server connection methods:

yaml
mcpServers:
  - name: browser-automation
    command: npx
    args:
      - "@playwright/mcp@latest"
    env:
      NODE_ENV: production

2. HTTP/SSE Connection

yaml
mcpServers:
  - name: remote-api-server
    url: https://api.example.com/mcp
    type: sse
    apiKey: ${API_KEY}
    requestOptions:
      timeout: 30000
      headers:
        User-Agent: ByteBuddy/1.0

3. WebSocket Connection

yaml
mcpServers:
  - name: realtime-service
    url: wss://service.example.com/ws
    type: websocket
    apiKey: ${WEBSOCKET_KEY}

Common MCP Server Examples

1. Browser Automation Tools

yaml
mcpServers:
  - name: browser-search
    command: npx
    args:
      - "@playwright/mcp@latest"

2. File System Enhancement

yaml
mcpServers:
  - name: filesystem-tools
    command: node
    args:
      - "./mcp-servers/filesystem-server.js"
    cwd: ${PROJECT_ROOT}

3. Database Connection

yaml
mcpServers:
  - name: database-tools
    command: python
    args:
      - "-m"
      - "mcp_database_server"
    env:
      DB_URL: postgresql://user:pass@localhost/mydb

How to Use in Conversations

Once configured, MCP server features are automatically available in conversations:

Example Conversation 1: Using Browser Tools

User:

Help me open Baidu homepage and take a screenshot

AI Assistant (automatically calls MCP tools):

  1. Launch browser and visit Baidu homepage
  2. Take page screenshot
  3. Save to specified location

Example Conversation 2: Using Database Tools

User:

Query how many active users are in the user table

AI Assistant (automatically calls MCP database tools):

  1. Connect to database
  2. Execute query: SELECT COUNT(*) FROM users WHERE status = 'active'
  3. Return result: Currently 523 active users

Security Configuration

1. Environment Variable Management

yaml
mcpServers:
  - name: secure-api
    url: https://api.example.com/mcp
    type: sse
    apiKey: ${API_SECRET_KEY} # Read from environment variable
    env:
      DEBUG: false

2. Connection Timeout Configuration

yaml
mcpServers:
  - name: timeout-example
    url: https://slow-api.example.com/mcp
    type: sse
    connectionTimeout: 60000 # 60-second connection timeout
    requestOptions:
      timeout: 120000 # 120-second request timeout

3. Working Directory Restrictions

yaml
mcpServers:
  - name: local-file-tools
    command: node
    args:
      - "./tools/file-server.js"
    cwd: /safe/workspace # Restrict working directory
    env:
      ALLOWED_PATHS: /safe/workspace

Custom MCP Servers

1. Create Node.js MCP Server

javascript
// custom-mcp-server.js
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

const server = new Server(
  {
    name: "custom-tools",
    version: "1.0.0",
  },
  {
    capabilities: {
      tools: {},
    },
  },
);

// Define tools
server.setRequestHandler("tools/list", async () => ({
  tools: [
    {
      name: "get_weather",
      description: "Get weather information for specified city",
      inputSchema: {
        type: "object",
        properties: {
          city: {
            type: "string",
            description: "City name",
          },
        },
        required: ["city"],
      },
    },
  ],
}));

// Handle tool calls
server.setRequestHandler("tools/call", async (request) => {
  if (request.params.name === "get_weather") {
    const { city } = request.params.arguments;
    // Implement weather API call logic here
    return {
      content: [
        {
          type: "text",
          text: `Current weather in ${city}: 22°C, sunny`,
        },
      ],
    };
  }
});

// Start server
const transport = new StdioServerTransport();
await server.connect(transport);

2. Create Python MCP Server

python
# custom_mcp_server.py
import asyncio
from mcp.server import Server
from mcp.server.stdio import stdio_server

app = Server("custom-python-server")

@app.list_tools()
async def handle_list_tools():
    return [
        {
            "name": "calculate",
            "description": "Perform mathematical calculations",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "expression": {
                        "type": "string",
                        "description": "Mathematical expression to calculate",
                    },
                },
                "required": ["expression"],
            },
        }
    ]

@app.call_tool()
async def handle_call_tool(name: str, arguments: dict):
    if name == "calculate":
        expression = arguments["expression"]
        try:
            result = eval(expression)  # Note: Use safe evaluation in production
            return {
                "content": [
                    {
                        "type": "text",
                        "text": f"Result: {result}",
                    }
                ]
            }
        except Exception as e:
            return {
                "content": [
                    {
                        "type": "text",
                        "text": f"Error: {str(e)}",
                    }
                ]
            }

async def main():
    async with stdio_server() as (read_stream, write_stream):
        await app.run(read_stream, write_stream)

if __name__ == "__main__":
    asyncio.run(main())

Advanced Configuration

1. Multiple Server Instances

yaml
mcpServers:
  - name: browser-automation
    command: npx
    args:
      - "@playwright/mcp@latest"
    env:
      BROWSER: chrome

  - name: filesystem-operations
    command: node
    args:
      - "./tools/filesystem-mcp.js"
    cwd: ${PROJECT_ROOT}

  - name: remote-api-gateway
    url: https://api.gateway.com/mcp
    type: sse
    apiKey: ${GATEWAY_API_KEY}

2. Conditional Server Loading

yaml
mcpServers:
  - name: development-tools
    command: node
    args:
      - "./tools/dev-server.js"
    env:
      NODE_ENV: development
    # Only enable in development environment
    disabled: ${ENVIRONMENT} === "production"

3. Server Health Checks

yaml
mcpServers:
  - name: critical-service
    url: https://critical.service.com/mcp
    type: sse
    apiKey: ${CRITICAL_API_KEY}
    healthCheck:
      enabled: true
      interval: 30000 # Check every 30 seconds
      timeout: 5000 # 5-second timeout
      endpoint: /health

Best Practices

1. Security Considerations

  • Use environment variables for sensitive information
  • Restrict working directory for file system access
  • Implement proper authentication and authorization
  • Regularly update MCP server packages

2. Performance Optimization

  • Set appropriate timeouts for network connections
  • Use connection pooling for frequently accessed services
  • Monitor server resource usage
  • Cache frequently used data when appropriate

3. Error Handling

  • Implement graceful error recovery
  • Provide meaningful error messages
  • Log errors for debugging purposes
  • Set up monitoring and alerting

Troubleshooting

Common Issues

Connection Failed

  1. Check if the MCP server is running
  2. Verify connection parameters (URL, API key, etc.)
  3. Check network connectivity
  4. Review server logs for error messages

Tools Not Available

  1. Ensure the server implements the tools/list handler
  2. Check if tools are properly registered
  3. Verify server capabilities configuration
  4. Restart ByteBuddy after configuration changes

Performance Issues

  1. Check server resource usage
  2. Optimize network requests
  3. Consider caching strategies
  4. Review timeout configurations

Debug Mode

Enable debug mode for troubleshooting:

yaml
mcpServers:
  - name: debug-server
    command: node
    args:
      - "./tools/debug-server.js"
      - "--debug"
      - "--log-level=verbose"
    env:
      DEBUG: mcp:*

Resources

Through proper MCP configuration, you can significantly extend ByteBuddy's capabilities and integrate various external services to create a more powerful AI assistant.