Articles in this section
Category / Section

How to Add MCP Tools in FlowMattic MCP Server

12 mins read
Updated:

MCP (Model Context Protocol) tools are the building blocks that enable AI assistants to interact with your WordPress site and external services. This comprehensive guide will walk you through creating different types of tools in your FlowMattic MCP server.

Overview

FlowMattic MCP Server supports five main types of tools, each designed for specific use cases:

  • PHP Function Tools: Execute custom WordPress functions via the admin interface
  • Workflow Tools: Trigger FlowMattic workflows
  • API Endpoint Tools: Make HTTP requests to external services
  • Database Query Tools: Run SQL queries against your database
  • Developer Tools: Programmatically added by plugins and themes

Getting Started

Prerequisites

Before creating MCP tools, ensure:

  • FlowMattic plugin is installed and activated
  • Your MCP server is active (green status indicator)
  • You have the necessary permissions to manage MCP tools
  • For developer tools: Basic PHP knowledge and plugin/theme development experience

Accessing the Tool Creation Interface

  1. Navigate to FlowMattic > MCP Server in your WordPress admin
  2. Click the “Add New Tool” button in the header or tools section
  3. The tool creation modal will open

MCP Server ‹ FlowMattic — WordPress 2025-07-27 at 5.21.07 AM.png

Creating PHP Function Tools

PHP Function tools execute custom WordPress functions when called by MCP clients through the admin interface.

When to Use PHP Functions

  • Custom business logic that doesn’t require a full plugin
  • WordPress data retrieval for specific use cases
  • User management operations
  • Custom calculations or processing
  • Quick prototyping of functionality

Step-by-Step Creation

  1. Set Basic Information
    • Enter a descriptive Tool Name (e.g., “Get User Details”, “Calculate Tax”)
    • Select “PHP Function” as the execution method
    • Add a clear Description explaining the function’s purpose and expected output

MCP Server ‹ FlowMattic — WordPress 2025-07-27 at 5.22.53 AM.png

  1. Configure PHP Function Settings

    • Function Name: Enter the exact name of your PHP function (must be callable)
    • Parameters Request Type: Choose how parameters are passed:
      • Individual Parameters: Each parameter passed separately to function
      • Array: All parameters passed as a single associative array
  2. Define Input Parameters

    • Click “Add Parameter” to define each input the function expects
    • Use lowercase with underscores (e.g., user_id, search_term, start_date)
    • Parameter names are automatically formatted as you type
    • Add all parameters your function requires
  3. Save the Tool

    • Click “Save Tool” to create your PHP function tool
    • The tool will appear in your tools list immediately
    • Test the tool to ensure it works correctly

PHP Function Example

// Example function that gets user data
function get_user_details_by_id($user_id) {
    // Validate input
    if (empty($user_id) || !is_numeric($user_id)) {
        return array('error' => 'Invalid user ID provided');
    }
    
    $user = get_userdata($user_id);
    
    if (!$user) {
        return array('error' => 'User not found');
    }
    
    return array(
        'success' => true,
        'data' => array(
            'id' => $user->ID,
            'username' => $user->user_login,
            'email' => $user->user_email,
            'display_name' => $user->display_name,
            'role' => $user->roles[0] ?? 'subscriber'
        )
    );
}

// Array-based function example
function process_user_data($input_array) {
    $user_id = $input_array['user_id'] ?? '';
    $action = $input_array['action'] ?? '';
    
    // Process based on action
    switch ($action) {
        case 'get_posts':
            return get_user_posts($user_id);
        case 'get_meta':
            return get_user_metadata($user_id);
        default:
            return array('error' => 'Invalid action specified');
    }
}

Parameter Handling

Individual Parameters (default):

  • Function receives: get_user_details_by_id("123")
  • Use when function expects separate arguments
  • Most common for simple functions

Array Parameters:

  • Function receives: get_user_details_by_id(array("user_id" => "123"))
  • Use when function expects a single array parameter
  • Better for complex functions with many optional parameters

Function Requirements

  • Function must be globally accessible (defined in active theme or plugin)
  • Should include proper error handling and validation
  • Must return data (arrays are automatically JSON-encoded)
  • Should follow WordPress coding standards

Creating Workflow Tools

Workflow tools execute FlowMattic workflows when triggered by MCP clients.

When to Use Workflows

  • Complex automation sequences
  • Multi-step processes involving multiple services
  • Integration with external platforms
  • Email notifications and alerts
  • Data synchronization tasks

Step-by-Step Creation

  1. Set Basic Information
    • Enter a descriptive Tool Name (e.g., “Send Notification Email”, “Sync Customer Data”)
    • Select “Workflow” as the execution method
    • Describe what the workflow accomplishes and expected outcomes

MCP Server ‹ FlowMattic — WordPress 2025-07-27 at 5.24.46 AM.png

  1. Select Target Workflow

    • Choose from the “Workflow to Execute” dropdown
    • Only published and active workflows appear in the list
    • Workflows must be properly configured and tested beforehand
  2. Configure Parameters

    • Add parameters that will be passed to the workflow as trigger data
    • Parameters are available in the workflow using dynamic data tags
    • Use descriptive parameter names that match workflow expectations
  3. Save the Tool

    • Click “Save Tool” to create the workflow tool
    • Test the tool to ensure the workflow executes correctly
    • Monitor workflow execution logs for any issues

Workflow Best Practices

  • Pre-test Workflows: Ensure workflows are fully functional before creating MCP tools
  • Error Handling: Include error steps in workflows for graceful failure handling
  • Clear Documentation: Document workflow purpose and expected parameters
  • Version Control: Keep track of workflow changes that might affect MCP tools
  • Performance: Optimize workflows for quick execution when called via MCP

Creating API Endpoint Tools

API Endpoint tools make HTTP requests to external services, perfect for integrating with third-party APIs.

When to Use API Endpoints

  • Third-party service integration (CRM, marketing tools, etc.)
  • External data retrieval (weather, stock prices, etc.)
  • Webhook notifications to external systems
  • REST API interactions
  • Microservice communication

Step-by-Step Creation

  1. Set Basic Information
    • Enter a descriptive Tool Name (e.g., “Get Weather Data”, “Create CRM Contact”)
    • Select “API Endpoint” as the execution method
    • Describe the API’s purpose, expected response, and any limitations

Zight 2025-07-27 at 5.25.40 AM.png

  1. Configure API Settings

    • API Endpoint: Enter the complete URL (e.g., https://api.example.com/v1/weather)
    • HTTP Method: Select GET, POST, PUT, or DELETE based on API requirements
    • Choose Connect: Select authentication method
    • Headers: Add JSON-formatted headers if required by the API
    • Webhook URL: Optional FlowMattic webhook URL for async processing
  2. Authentication Setup

    • None: No authentication required (public APIs)
    • FlowMattic Connect: Use pre-configured authentication
      • Select from existing connects (OAuth2, API keys, Basic Auth, etc.)
      • FlowMattic handles token management and refresh automatically
      • Ideal for APIs requiring complex authentication
  3. Configure Headers (Optional)

    {
      "Authorization": "Bearer your-static-token-here",
      "Content-Type": "application/json",
      "User-Agent": "FlowMattic-MCP/1.0",
      "Accept": "application/json"
    }
    
  4. Add Input Parameters

    • Define parameters that will be sent with the API request
    • Parameters can be included in URL path, query string, or request body
    • Use parameter names that match API documentation
    • Consider optional vs required parameters
  5. Save the Tool

    • Click “Save Tool” to create the API endpoint tool
    • Test with your MCP client to verify functionality
    • Monitor API response times and error rates

API Tool Examples

GET Request Example: Weather API

Endpoint: https://api.openweathermap.org/data/2.5/weather
Method: GET
Parameters: city, api_key, units
Headers: None required

POST Request Example: Create User in CRM

Endpoint: https://api.crm.com/v1/contacts
Method: POST
Parameters: name, email, phone, company
Headers: {"Authorization": "Bearer token", "Content-Type": "application/json"}

PUT Request Example: Update Product

Endpoint: https://api.ecommerce.com/products/{product_id}
Method: PUT
Parameters: product_id, name, price, description
Authentication: FlowMattic Connect (OAuth2)

API Best Practices

  • Rate Limiting: Be aware of API rate limits and implement appropriate delays
  • Error Handling: Handle API errors gracefully and return meaningful messages
  • Data Validation: Validate parameters before sending to external APIs
  • Security: Never expose API keys in tool descriptions or names
  • Documentation: Keep API documentation handy for troubleshooting

Creating Database Query Tools

Database Query tools execute SQL queries directly against your WordPress database.

When to Use Database Queries

  • Complex data retrieval that WP_Query can’t handle efficiently
  • Reporting and analytics requiring JOIN operations
  • Custom search functionality across multiple tables
  • Data aggregation and statistical analysis
  • Performance-critical queries

⚠️ Security Warning: Database queries can be powerful but potentially dangerous. Use with extreme caution and proper validation.

Step-by-Step Creation

  1. Set Basic Information
    • Enter a descriptive Tool Name (e.g., “Search Posts by Content”, “User Activity Report”)
    • Select “Database Query” as the execution method
    • Clearly describe what data the query retrieves and any limitations

MCP Server ‹ FlowMattic — WordPress 2025-07-27 at 5.27.04 AM.png

  1. Write Your SQL Query

    • Enter your SQL query in the provided text area
    • Use parameterized queries for security (required)
    • Test queries in phpMyAdmin or similar tool first
    • Include appropriate LIMIT clauses
  2. Use Dynamic Parameters

    • Use :parameter_name syntax for dynamic values
    • Example: SELECT * FROM wp_posts WHERE post_content LIKE '%:search_term%'
    • Parameters are automatically sanitized and replaced at runtime
    • Never concatenate user input directly into queries
  3. Define Input Parameters

    • Add parameters that correspond to your query placeholders
    • Ensure parameter names match exactly (without the colon)
    • Provide clear descriptions for each parameter
  4. Save the Tool

    • Click “Save Tool” to create the database query tool
    • Test thoroughly with safe queries first
    • Monitor query performance and execution time

Database Query Examples

Basic Search Query:

SELECT ID, post_title, post_excerpt, post_date 
FROM wp_posts 
WHERE post_status = 'publish' 
  AND post_type = 'post'
  AND (post_title LIKE '%:search_term%' OR post_content LIKE '%:search_term%')
ORDER BY post_date DESC
LIMIT 20

User Posts with Meta Query:

SELECT p.ID, p.post_title, p.post_date, u.display_name,
       GROUP_CONCAT(pm.meta_value) as tags
FROM wp_posts p
JOIN wp_users u ON p.post_author = u.ID
LEFT JOIN wp_postmeta pm ON p.ID = pm.post_id AND pm.meta_key = 'tags'
WHERE p.post_author = :user_id
  AND p.post_status = 'publish'
  AND p.post_date >= ':start_date'
GROUP BY p.ID
ORDER BY p.post_date DESC
LIMIT :limit_count

Analytics Query:

SELECT 
    DATE(post_date) as publish_date,
    COUNT(*) as posts_count,
    AVG(CHAR_LENGTH(post_content)) as avg_content_length
FROM wp_posts 
WHERE post_status = 'publish' 
  AND post_type = 'post'
  AND post_date >= ':start_date'
  AND post_date <= ':end_date'
GROUP BY DATE(post_date)
ORDER BY publish_date DESC

Database Security Best Practices

  • Always Use Parameters: Never concatenate user input into queries
  • Limit Scope: Use WHERE clauses to restrict data access
  • Avoid SELECT *: Specify only needed columns
  • Use LIMIT: Prevent large result sets that could impact performance
  • Read-Only Access: Avoid UPDATE, DELETE, or INSERT operations
  • Test Safely: Test all queries in development environment first
  • Monitor Performance: Track query execution time and optimize slow queries

Understanding Developer Tools (Plugin/Theme Integration)

Developer tools are programmatically added by WordPress plugins and themes, rather than created through the admin interface. These tools appear automatically in your MCP server when plugins register them using FlowMattic’s developer API.

How Developer Tools Appear in Admin

Visual Identification: Developer tools are distinguished in the admin interface by:

  • Plugin Badge: Shows the source plugin/theme name
  • Read-Only Status: Cannot be edited or deleted through admin interface
  • Source Attribution: Clearly marked as originating from external code

MCP Server ‹ FlowMattic — WordPress 2025-07-27 at 5.27.48 AM.png

Available Actions: For developer tools, you can only:

  • View Tool History: See execution logs and performance metrics
  • Monitor Usage: Track how often the tool is called
  • Review Configuration: See tool details (but cannot modify)

How Developer Tools Work

  • Tools are registered using PHP code in plugins/themes
  • No admin interface interaction required for creation
  • Tools appear automatically when plugins are activated
  • Managed entirely through the originating plugin/theme code
  • Support both simple and complex functionality

Tool Management

  • Updates: Tool modifications must be made in the plugin/theme code
  • Removal: Tools are removed when the plugin is deactivated/removed
  • Debugging: Use tool history to monitor performance and errors

When Plugins Use Developer Tools

  • Expose plugin-specific functionality to AI assistants
  • Provide theme-related automation capabilities
  • Integrate complex business logic with MCP clients
  • Enable advanced WordPress operations through AI

For Developers

If you’re a plugin or theme developer interested in adding MCP tools to your code, see the comprehensive FlowMattic MCP Server: Developer Integration Guide for complete implementation details, code examples, and best practices.

Parameter Configuration

Parameter Naming Rules

  • Use lowercase letters, numbers, and underscores only
  • Start with a letter, not a number
  • Be descriptive but concise
  • Use consistent naming across related tools
  • Examples: user_id, search_term, start_date, limit_count

Parameter Validation

  • Client-side: Basic validation happens automatically in MCP clients
  • Server-side: Always validate and sanitize in your functions/workflows
  • Required vs Optional: Clearly document which parameters are required
function validate_parameters( $params ) {
    $errors = array();
    
    // Required parameter check
    if ( empty( $params['user_id'] ) ) {
        $errors[] = 'user_id is required';
    }
    
    // Type validation
    if ( isset( $params['limit'] ) && ! is_numeric( $params['limit'] ) ) {
        $errors[] = 'limit must be a number';
    }
    
    // Range validation
    if ( isset( $params['page'] ) && ( $params['page'] < 1 || $params['page'] > 100 ) ) {
        $errors[] = 'page must be between 1 and 100';
    }
    
    return $errors;
}

Testing Your Tools

Pre-Deployment Testing

  1. Function Testing: Test PHP functions independently
// Test in WordPress admin or via WP-CLI
$result = your_function_name( 'test_value' );
var_dump( $result );
  1. Parameter Testing: Verify parameter handling
// Test different parameter combinations
$test_cases = array(
    array( 'user_id' => '1' ),
    array( 'user_id' => 'invalid' ),
    array(), // Missing parameters
);

foreach ( $test_cases as $params ) {
    $result = your_function( $params );
    echo "Input: " . json_encode( $params ) . "\n";
    echo "Output: " . json_encode( $result ) . "\n\n";
}
  1. Error Handling Testing: Test edge cases and error conditions

MCP Client Testing

  1. Connect MCP Client: Use Claude Desktop, VS Code, or another client
  2. Tool Discovery: Verify tools appear in the client
  3. Execution Testing: Test tools with various inputs
  4. Performance Testing: Monitor response times
  5. Error Testing: Test with invalid inputs

Common Testing Scenarios

Valid Input Test:

Ask Claude: "Use the Get User Details tool to get information for user ID 1"
Expected: Valid user data returned

Invalid Input Test:

Ask Claude: "Use the Get User Details tool with user ID 'invalid'"
Expected: Clear error message about invalid user ID

Missing Parameter Test:

Ask Claude: "Use the Get User Details tool without providing a user ID"
Expected: Error message about missing required parameter

Performance Test:

Ask Claude: "Get details for users 1, 2, 3, 4, and 5 using the user details tool"
Expected: Reasonable response time for multiple calls

Debugging Common Issues

Tool Not Appearing in Client:

  • ✅ Verify server is active (green status)
  • ✅ Check tool was saved successfully
  • ✅ Refresh MCP client connection
  • ✅ Check for JavaScript console errors

Function Not Found Errors:

  • ✅ Ensure PHP function exists and is accessible
  • ✅ Check function name spelling exactly
  • ✅ Verify function is defined in active theme/plugin
  • ✅ Test function independently in WordPress

Parameter Errors:

  • ✅ Verify parameter names match exactly
  • ✅ Check parameter formatting (lowercase_underscore)
  • ✅ Ensure required parameters are provided
  • ✅ Test parameter type conversion

Performance Issues:

  • ✅ Monitor execution time in tool history
  • ✅ Optimize database queries with EXPLAIN
  • ✅ Add caching where appropriate
  • ✅ Limit result set sizes

Authentication Errors (API tools):

  • ✅ Verify API credentials are correct
  • ✅ Check FlowMattic Connect configuration
  • ✅ Test API endpoint independently
  • ✅ Review API rate limits

Tool Management

Editing Existing Tools

  1. Locate the tool in your tools list
  2. Click the three-dot menu on the tool card
  3. Select “Edit Tool”
  4. Modify settings as needed
  5. Click “Update Tool” to save changes

Note: Plugin/theme tools cannot be edited through the admin interface - they must be modified in code.

Duplicating Tools

  • Use the “Duplicate” option to create similar tools quickly
  • Modify the duplicate as needed
  • Useful for creating variations with different parameters
  • Great for testing new configurations

Monitoring Tool Usage

  • Click “Tool History” to view execution logs
  • Monitor success rates and performance metrics
  • Identify frequently used tools for optimization
  • Track error patterns for debugging

Tool Organization

  • Use consistent naming conventions
  • Group related tools with similar prefixes
  • Document tool purposes in descriptions
  • Archive unused tools to reduce clutter

Advanced Features

Error Handling Best Practices

Structured Error Responses:

// Good error response structure
return array(
    'success' => false,
    'error' => 'User not found',
    'error_code' => 'USER_NOT_FOUND',
    'details' => array(
        'user_id' => $user_id,
        'timestamp' => current_time( 'mysql' )
    )
);

Success Response Structure:

// Consistent success response
return array(
    'success' => true,
    'data' => $result_data,
    'message' => 'Operation completed successfully',
    'meta' => array(
        'execution_time' => $execution_time,
        'timestamp' => current_time( 'mysql' )
    )
);

Async Processing (API Tools)

For long-running operations, use webhook URLs:

// In your API endpoint configuration
$webhook_url = 'https://yoursite.com/wp-json/flowmattic/v1/webhook/your-endpoint';

// The API tool will:
// 1. Return immediate acknowledgment
// 2. Process data asynchronously  
// 3. Send results to webhook when complete

Best Practices Summary

Tool Design

  • Single Responsibility: Each tool should have one clear purpose
  • Descriptive Names: Use action-oriented, clear names
  • Comprehensive Descriptions: Help AI understand when and how to use tools
  • Consistent Parameters: Use standard naming across related tools
  • Error Messages: Provide clear, actionable error messages

Development

  • Input Validation: Always validate and sanitize inputs in your functions
  • Error Handling: Return structured error responses with helpful messages
  • Testing: Test tools thoroughly before deploying to production
  • Documentation: Keep clear documentation of tool purposes and parameters

Maintenance

  • Monitor Usage: Regular review of execution history and performance
  • Keep Updated: Maintain tools as requirements change
  • Optimize Performance: Review and optimize slow-running tools
  • Version Control: Track changes to tool configurations

Troubleshooting Guide

Server Issues

Problem: MCP Server not responding

  • Check server status (should be green/active)
  • Verify WordPress site is accessible
  • Check for plugin conflicts
  • Review server error logs

Problem: Tools not appearing in clients

  • Refresh MCP client connection
  • Verify tools are saved correctly
  • Check server URL configuration
  • Ensure server is active

Tool Execution Issues

Problem: PHP function not found

  • Verify function exists in active theme/plugin
  • Check function name spelling
  • Ensure function is globally accessible
  • Test function independently

Problem: Database query errors

  • Validate SQL syntax
  • Check parameter placeholders
  • Verify table names and structure
  • Test query in database management tool

Problem: API endpoint failures

  • Verify endpoint URL is correct
  • Check authentication credentials
  • Review API rate limits
  • Test endpoint independently

Performance Problems

Problem: Slow tool execution

  • Review database query efficiency
  • Check for unnecessary data processing
  • Implement caching where appropriate
  • Monitor server resource usage

Problem: Timeouts

  • Optimize long-running operations
  • Implement async processing for heavy tasks
  • Increase server timeout limits if necessary
  • Break large operations into smaller chunks

Next Steps

After creating and configuring your MCP tools:

  1. Test Thoroughly: Verify all tools work as expected with various inputs
  2. Document Usage: Create internal documentation for tool purposes and parameters
  3. Monitor Performance: Regular review of execution history and performance metrics
  4. User Training: Educate team members on available tools and their capabilities
  5. Iterate and Improve: Refine tools based on usage patterns and feedback
  6. Security Review: Regular security audits of tool configurations and permissions

Related Resources

With these tools properly configured and tested, your MCP server becomes a powerful automation hub that bridges AI assistants with your WordPress site and external services, enabling sophisticated workflow automation and integration capabilities.

Was this article useful?
Like
Dislike
Help us improve this page
Please provide feedback or comments
Access denied
Access denied