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.1.6 1.6.86 0.1.7 1.6.87 0.1.8 1.6.88 0.1.9 1.6.89 0.2.0 1.6.90
ai-engine / dev-notes.md
ai-engine Last commit date
app 1 year ago archives 1 year ago classes 1 year ago common 1 year ago constants 1 year ago images 1 year ago labs 1 year ago themes 1 year ago vendor 1 year ago ai-engine.php 1 year ago blueprint.json 2 years ago dev-notes.md 1 year ago readme.txt 1 year ago uninstall.php 1 year ago
dev-notes.md
1458 lines
1 # AI Engine - Developer Documentation
2
3 This documentation is for developers who want to extend AI Engine with custom functionality. AI Engine provides multiple extension points through filters and APIs that allow you to enhance chatbots, add custom AI tools, and integrate with WordPress in powerful ways.
4
5 ## Table of Contents
6 - [](#wordpress-hooks-referenceWordPress Hooks Reference](#wordpress-hooks-reference](#wordpress-hooks-reference) - Complete list of filters and actions
7 - [](#chatbot-actionsChatbot Actions](#chatbot-actions](#chatbot-actions) - Execute client-side functions from AI responses
8 - [](#chatbot-shortcutsChatbot Shortcuts](#chatbot-shortcuts](#chatbot-shortcuts) - Dynamic quick-action buttons in chatbots
9 - [](#chatbot-blocksChatbot Blocks](#chatbot-blocks](#chatbot-blocks) - Interactive HTML content in chat conversations
10 - [](#mcp-model-context-protocolMCP (Model Context Protocol)](#mcp-model-context-protocol](#mcp-model-context-protocol) - Enable AI agents to interact with WordPress
11 - [](#discussion-context-menuDiscussion Context Menu](#discussion-context-menu](#discussion-context-menu) - Customize the discussions interface
12
13 ---
14
15 # WordPress Hooks Reference
16
17 AI Engine provides numerous WordPress filters and actions that allow developers to customize and extend its functionality. This section documents the most useful hooks for developers.
18
19 ## Core AI Filters
20
21 ### Query and Reply Processing
22
23 ```php
24 // Modify AI query before it's sent
25 add_filter( 'mwai_ai_query', function( $query ) {
26 // Modify the query object
27 return $query;
28 });
29
30 // Modify AI reply after it's received
31 add_filter( 'mwai_ai_reply', function( $reply, $query ) {
32 // Process or modify the reply
33 return $reply;
34 }, 10, 2 );
35
36 // Control whether a query is allowed
37 add_filter( 'mwai_ai_allowed', function( $allowed, $query, $limits ) {
38 // Return true to allow, false to block, or a string error message
39 if ( /* some condition */ ) {
40 return 'Query blocked due to rate limits';
41 }
42 return $allowed;
43 }, 10, 3 );
44
45 // Modify AI instructions/context
46 add_filter( 'mwai_ai_instructions', function( $instructions, $query ) {
47 // Add or modify system instructions
48 $instructions .= "\nAlways be polite and helpful.";
49 return $instructions;
50 }, 10, 2 );
51 ```
52
53 ### Error Handling
54
55 ```php
56 // Customize error messages shown to users
57 add_filter( 'mwai_ai_exception', function( $message ) {
58 // Hide technical details from users
59 if ( strpos( $message, 'API' ) !== false ) {
60 return 'Service temporarily unavailable. Please try again.';
61 }
62 return $message;
63 });
64 ```
65
66 ## Chatbot Filters
67
68 ### Chatbot Parameters and Behavior
69
70 ```php
71 // Modify chatbot parameters
72 add_filter( 'mwai_chatbot_params', function( $params ) {
73 // Force specific settings
74 $params['temperature'] = 0.7;
75 $params['max_tokens'] = 500;
76 return $params;
77 });
78
79 // Takeover chatbot response (bypass AI)
80 add_filter( 'mwai_chatbot_takeover', function( $takeover, $query, $params ) {
81 // Check for specific triggers
82 if ( strpos( $query->get_message(), 'current time' ) !== false ) {
83 return 'The current time is ' . current_time( 'mysql' );
84 }
85 return $takeover;
86 }, 10, 3 );
87
88 // Modify chatbot query before processing
89 add_filter( 'mwai_chatbot_query', function( $query, $params ) {
90 // Add context or modify the query
91 return $query;
92 }, 10, 2 );
93
94 // Process chatbot reply before sending to user
95 add_filter( 'mwai_chatbot_reply', function( $reply, $query, $params, $extra ) {
96 // Add custom formatting or processing
97 return $reply;
98 }, 10, 4 );
99 ```
100
101 ### Dynamic UI Elements
102
103 ```php
104 // Add chatbot shortcuts dynamically
105 add_filter( 'mwai_chatbot_shortcuts', function( $shortcuts, $args ) {
106 $shortcuts[] = [
107 'type' => 'message',
108 'data' => [
109 'label' => 'Help',
110 'message' => 'I need help',
111 'variant' => 'info'
112 ]
113 ];
114 return $shortcuts;
115 }, 10, 2 );
116
117 // Add chatbot blocks (HTML content)
118 add_filter( 'mwai_chatbot_blocks', function( $blocks, $args ) {
119 $blocks[] = [
120 'type' => 'content',
121 'data' => [
122 'html' => '<div>Custom content</div>',
123 'script' => 'console.log("Block loaded");'
124 ]
125 ];
126 return $blocks;
127 }, 10, 2 );
128
129 // Add chatbot actions (function calls)
130 add_filter( 'mwai_chatbot_actions', function( $actions, $args ) {
131 $actions[] = [
132 'name' => 'custom_action',
133 'data' => ['param' => 'value']
134 ];
135 return $actions;
136 }, 10, 2 );
137 ```
138
139 ## Embeddings and Vector Database
140
141 ```php
142 // Add custom vector to database
143 add_filter( 'mwai_embeddings_add_vector', function( $success, $vector, $options ) {
144 // Implement custom vector storage
145 return $success;
146 }, 10, 3 );
147
148 // Query vectors from database
149 add_filter( 'mwai_embeddings_query_vectors', function( $results, $searchVectors, $options ) {
150 // Implement custom vector search
151 return $results;
152 }, 10, 3 );
153
154 // Delete vectors
155 add_filter( 'mwai_embeddings_delete_vectors', function( $vectorIds, $options ) {
156 // Handle vector deletion
157 return $vectorIds;
158 }, 10, 2 );
159
160 // Modify context search results
161 add_filter( 'mwai_context_search', function( $context, $query, $options ) {
162 // Add or modify context from embeddings
163 return $context;
164 }, 10, 3 );
165 ```
166
167 ## Content Processing
168
169 ```php
170 // Modify content before AI processing
171 add_filter( 'mwai_contentaware_content', function( $content, $post ) {
172 // Clean or enhance content
173 $content = strip_shortcodes( $content );
174 return $content;
175 }, 10, 2 );
176
177 // Customize prompt templates
178 add_filter( 'mwai_prompt_suggestTitles', function( $prompt, $args ) {
179 return "Generate 5 SEO-optimized titles for:\n\n";
180 }, 10, 2 );
181
182 add_filter( 'mwai_prompt_translateText', function( $prompt, $args ) {
183 return "Translate to {$args['language']} maintaining tone:\n\n";
184 }, 10, 2 );
185 ```
186
187 ## AI Forms
188
189 ```php
190 // Modify form parameters
191 add_filter( 'mwai_form_params', function( $params ) {
192 $params['submit_label'] = 'Generate Content';
193 return $params;
194 });
195
196 // Takeover form submission
197 add_filter( 'mwai_form_takeover', function( $takeover, $query, $params ) {
198 // Handle form submission custom logic
199 return $takeover;
200 }, 10, 3 );
201
202 // Process form reply
203 add_filter( 'mwai_form_reply', function( $reply, $query, $params, $extra ) {
204 // Format or process the reply
205 return $reply;
206 }, 10, 4 );
207
208 // Customize form field parameters
209 add_filter( 'mwai_forms_field_params', function( $params ) {
210 // Modify field settings
211 return $params;
212 });
213
214 // Add custom form styles
215 add_filter( 'mwai_forms_style', function( $styles, $formId ) {
216 $styles .= "\n.mwai-form-{$formId} { border: 2px solid blue; }";
217 return $styles;
218 }, 10, 2 );
219 ```
220
221 ## Function Calling
222
223 ```php
224 // Register custom functions for AI to call
225 add_filter( 'mwai_functions_list', function( $functions ) {
226 $functions[] = [
227 'name' => 'get_weather',
228 'description' => 'Get current weather',
229 'parameters' => [
230 'type' => 'object',
231 'properties' => [
232 'location' => [
233 'type' => 'string',
234 'description' => 'City name'
235 ]
236 ]
237 ]
238 ];
239 return $functions;
240 });
241
242 // Handle function execution
243 add_filter( 'mwai_ai_feedback', function( $result, $function, $args ) {
244 if ( $function['name'] === 'get_weather' ) {
245 // Execute function and return result
246 return "Sunny, 25°C in " . $args['location'];
247 }
248 return $result;
249 }, 10, 3 );
250 ```
251
252 ## Statistics and Usage
253
254 ```php
255 // Modify usage statistics
256 add_filter( 'mwai_stats_credits', function( $credits, $userId ) {
257 // Implement custom credit system
258 return $credits;
259 }, 10, 2 );
260
261 // Customize pricing calculations
262 add_filter( 'mwai_stats_coins', function( $price, $stats, $atts ) {
263 // Apply custom pricing logic
264 return $price;
265 }, 10, 3 );
266
267 // Access logs
268 add_filter( 'mwai_stats_logs_list', function( $logs, $offset, $limit, $filters, $sort ) {
269 // Filter or modify logs
270 return $logs;
271 }, 10, 5 );
272 ```
273
274 ## MCP (Model Context Protocol)
275
276 ```php
277 // Register MCP tools
278 add_filter( 'mwai_mcp_tools', function( $tools ) {
279 $tools[] = [
280 'name' => 'custom_tool',
281 'description' => 'My custom tool',
282 'inputSchema' => [/* ... */]
283 ];
284 return $tools;
285 });
286
287 // Handle MCP tool execution
288 add_filter( 'mwai_mcp_callback', function( $result, $tool, $args, $id ) {
289 if ( $tool === 'custom_tool' ) {
290 // Execute and return result
291 return ['success' => true, 'data' => 'result'];
292 }
293 return $result;
294 }, 10, 4 );
295
296 // Control MCP access
297 add_filter( 'mwai_allow_mcp', function( $allowed, $userId ) {
298 // Implement custom access control
299 return $allowed;
300 }, 10, 2 );
301 ```
302
303 ## Engine Configuration
304
305 ```php
306 // Customize AI engine initialization
307 add_filter( 'mwai_init_engine', function( $engine, $core, $env ) {
308 // Return custom engine implementation
309 return $engine;
310 }, 10, 3 );
311
312 // Modify model lists
313 add_filter( 'mwai_openai_models', function( $models ) {
314 // Add custom models
315 $models[] = 'custom-model-id';
316 return $models;
317 });
318
319 // Customize API endpoints
320 add_filter( 'mwai_openai_endpoint', function( $endpoint, $env ) {
321 // Use custom endpoint
322 return 'https://custom-api.example.com/v1';
323 }, 10, 2 );
324 ```
325
326 ## Actions
327
328 ```php
329 // Scheduled tasks
330 add_action( 'mwai_tasks_run', function() {
331 // Run scheduled maintenance tasks
332 // This runs on WP cron
333 });
334 ```
335
336 ## Best Practices
337
338 1. **Priority Matters**: Use appropriate priority values (default is 10) to control execution order
339 2. **Return Values**: Always return the filtered value, even if unchanged
340 3. **Error Handling**: Use try-catch blocks in your filters to prevent breaking the plugin
341 4. **Performance**: Keep filter callbacks lightweight, especially for frequently called filters
342 5. **Documentation**: Document your custom filters for other developers on your team
343
344 ---
345
346 # Chatbot Actions
347
348 Actions allow AI models to trigger client-side JavaScript functions during chat conversations. This enables dynamic interactions like form submissions, API calls, or UI updates directly from the AI's response.
349
350 ## How Actions Work
351
352 When the AI includes a specific action in its response, the chatbot automatically executes the corresponding JavaScript function on the client side. This is particularly useful for:
353 - Triggering form submissions
354 - Making API calls
355 - Updating UI elements
356 - Collecting user data
357 - Integrating with third-party services
358
359 ## Implementation
360
361 ### Step 1: Create a Callable Action in Code Engine
362
363 1. Go to **AI Engine → Code Engine**
364 2. Create a new snippet with:
365 - **Type**: Callable Action
366 - **Target**: JS
367 - **Name**: Your action name (e.g., `submit_form`)
368
369 ### Step 2: Write Your JavaScript Function
370
371 ```javascript
372 // This function will be called when the AI triggers the action
373 function submit_form(args) {
374 // Access chatbot context
375 const chatbot = args.chatbot;
376 const message = args.message;
377
378 // Your custom logic
379 const formData = {
380 name: args.name,
381 email: args.email,
382 message: args.userMessage
383 };
384
385 // Example: Submit to an API
386 fetch('/wp-json/custom/v1/submit', {
387 method: 'POST',
388 headers: { 'Content-Type': 'application/json' },
389 body: JSON.stringify(formData)
390 })
391 .then(response => response.json())
392 .then(data => {
393 // Send response back to chat
394 chatbot.addMessage({
395 role: 'assistant',
396 content: 'Form submitted successfully!'
397 });
398 });
399 }
400 ```
401
402 ### Step 3: Configure AI to Use the Action
403
404 In your AI assistant or system prompt, instruct the model to use the action:
405
406 ```
407 When the user wants to submit a contact form, use the submit_form action with their name, email, and message.
408
409 Example response format:
410 "I'll submit that form for you now."
411 [Action: submit_form, Args: {"name": "John", "email": "john@example.com", "userMessage": "Hello!"}]
412 ```
413
414 ## Action Response Format
415
416 The AI should include actions in this format:
417 ```json
418 {
419 "type": "function",
420 "data": {
421 "name": "action_name",
422 "args": {
423 "param1": "value1",
424 "param2": "value2"
425 }
426 }
427 }
428 ```
429
430 ## Complete Example: Calculator Action
431
432 ```javascript
433 // Code Engine Callable Action: "calculate"
434 function calculate(args) {
435 const { operation, a, b, chatbot } = args;
436 let result;
437
438 switch(operation) {
439 case 'add':
440 result = a + b;
441 break;
442 case 'multiply':
443 result = a * b;
444 break;
445 case 'divide':
446 result = b !== 0 ? a / b : 'Cannot divide by zero';
447 break;
448 }
449
450 // Display result in chat
451 chatbot.addMessage({
452 role: 'assistant',
453 content: `The result is: ${result}`
454 });
455 }
456 ```
457
458 AI Assistant instruction:
459 ```
460 When asked to perform calculations, use the calculate action.
461 Example: "What is 5 plus 3?"
462 Response: "Let me calculate that for you." [Action: calculate, Args: {"operation": "add", "a": 5, "b": 3}]
463 ```
464
465 ---
466
467 # Chatbot Shortcuts
468
469 Shortcuts are dynamic quick-action buttons that appear in the chatbot interface. They provide users with suggested actions or common questions, improving the chat experience by offering one-click interactions.
470
471 ## What Are Shortcuts?
472
473 Shortcuts appear as clickable buttons above the chat input. When clicked, they can:
474 - Send predefined messages to the chatbot
475 - Trigger specific conversations
476 - Guide users through common workflows
477 - Provide contextual suggestions based on the conversation
478
479 ## Adding Shortcuts via JavaScript
480
481 ### Basic Example
482
483 ```javascript
484 // Add shortcuts to all chatbots
485 MwaiAPI.chatbots.forEach(chatbot => {
486 chatbot.setShortcuts([
487 {
488 type: 'message',
489 data: {
490 label: 'Get Started',
491 message: 'Hello! What can you help me with?',
492 variant: 'success',
493 icon: '👋'
494 }
495 },
496 {
497 type: 'message',
498 data: {
499 label: 'Contact Support',
500 message: 'I need help with a technical issue',
501 variant: 'warning',
502 icon: '🛠️'
503 }
504 }
505 ]);
506 });
507 ```
508
509 ### Dynamic Shortcuts Based on Context
510
511 ```javascript
512 // Listen for messages and update shortcuts dynamically
513 MwaiAPI.chatbots.forEach(chatbot => {
514 chatbot.on('message', (message) => {
515 if (message.content.includes('products')) {
516 chatbot.setShortcuts([
517 {
518 type: 'message',
519 data: {
520 label: 'View Catalog',
521 message: 'Show me your product catalog',
522 variant: 'info'
523 }
524 },
525 {
526 type: 'message',
527 data: {
528 label: 'Best Sellers',
529 message: 'What are your best selling products?',
530 variant: 'success'
531 }
532 }
533 ]);
534 }
535 });
536 });
537 ```
538
539 ## Adding Shortcuts via PHP
540
541 ### Basic Implementation
542
543 ```php
544 add_filter( 'mwai_chatbot_shortcuts', function ( $shortcuts, $args ) {
545 // Add shortcuts for all chatbots
546 $shortcuts[] = [
547 'type' => 'message',
548 'data' => [
549 'label' => 'FAQ',
550 'message' => 'Show me frequently asked questions',
551 'variant' => 'info',
552 'icon' => ''
553 ]
554 ];
555
556 $shortcuts[] = [
557 'type' => 'message',
558 'data' => [
559 'label' => 'Pricing',
560 'message' => 'Tell me about your pricing plans',
561 'variant' => 'success',
562 'icon' => '💰'
563 ]
564 ];
565
566 return $shortcuts;
567 }, 10, 2);
568 ```
569
570 ### Conditional Shortcuts
571
572 ```php
573 add_filter( 'mwai_chatbot_shortcuts', function ( $shortcuts, $args ) {
574 // Show shortcuts based on conversation content
575 $hasQuery = isset($args['newMessage']) ? $args['newMessage'] : '';
576 $hasReply = isset($args['reply']) ? $args['reply'] : '';
577
578 // E-commerce shortcuts when products are mentioned
579 if (stripos($hasQuery . $hasReply, 'product') !== false) {
580 $shortcuts[] = [
581 'type' => 'message',
582 'data' => [
583 'label' => '🛒 Cart',
584 'message' => 'Show my shopping cart',
585 'variant' => 'info'
586 ]
587 ];
588
589 $shortcuts[] = [
590 'type' => 'message',
591 'data' => [
592 'label' => '📦 Track Order',
593 'message' => 'I want to track my order',
594 'variant' => 'warning'
595 ]
596 ];
597 }
598
599 // Support shortcuts when help is needed
600 if (stripos($hasQuery . $hasReply, 'help') !== false ||
601 stripos($hasQuery . $hasReply, 'support') !== false) {
602 $shortcuts[] = [
603 'type' => 'message',
604 'data' => [
605 'label' => '📧 Email Support',
606 'message' => 'I need to contact support via email',
607 'variant' => 'danger'
608 ]
609 ];
610
611 $shortcuts[] = [
612 'type' => 'message',
613 'data' => [
614 'label' => '📞 Call Us',
615 'message' => 'What is your support phone number?',
616 'variant' => 'success'
617 ]
618 ];
619 }
620
621 return $shortcuts;
622 }, 10, 2);
623 ```
624
625 ### User-Specific Shortcuts
626
627 ```php
628 add_filter( 'mwai_chatbot_shortcuts', function ( $shortcuts, $args ) {
629 // Show different shortcuts based on user role
630 if (is_user_logged_in()) {
631 $user = wp_get_current_user();
632
633 if (in_array('customer', $user->roles)) {
634 $shortcuts[] = [
635 'type' => 'message',
636 'data' => [
637 'label' => 'My Orders',
638 'message' => 'Show me my recent orders',
639 'variant' => 'info'
640 ]
641 ];
642 }
643
644 if (in_array('administrator', $user->roles)) {
645 $shortcuts[] = [
646 'type' => 'message',
647 'data' => [
648 'label' => 'Admin Stats',
649 'message' => 'Show me the site statistics',
650 'variant' => 'warning'
651 ]
652 ];
653 }
654 } else {
655 $shortcuts[] = [
656 'type' => 'message',
657 'data' => [
658 'label' => 'Sign Up',
659 'message' => 'How do I create an account?',
660 'variant' => 'success'
661 ]
662 ];
663 }
664
665 return $shortcuts;
666 }, 10, 2);
667 ```
668
669 ## Shortcut Properties
670
671 - **type**: Always 'message' for shortcuts
672 - **data.label**: Button text displayed to user
673 - **data.message**: Message sent when clicked
674 - **data.variant**: Button style ('success', 'warning', 'danger', 'info')
675 - **data.icon**: Optional emoji or icon
676
677 ---
678
679 # Chatbot Blocks
680
681 Blocks allow you to inject interactive HTML content directly into chat conversations. Unlike simple text responses, blocks can contain forms, buttons, custom UI elements, and even executable JavaScript.
682
683 ## What Are Blocks?
684
685 Blocks are custom HTML elements that can:
686 - Display forms for data collection
687 - Show interactive widgets
688 - Present rich media content
689 - Lock the chatbot until user interaction
690 - Execute custom JavaScript code
691
692 ## Adding Blocks via JavaScript
693
694 ### Simple Content Block
695
696 ```javascript
697 // Display a welcome message with custom styling
698 MwaiAPI.getChatbot().setBlocks([
699 {
700 type: 'content',
701 data: {
702 html: `
703 <div style="background: #f0f0f0; padding: 20px; border-radius: 10px;">
704 <h3>Welcome to Our Support Chat!</h3>
705 <p>How can we help you today?</p>
706 <ul>
707 <li>Technical Support</li>
708 <li>Billing Questions</li>
709 <li>Product Information</li>
710 </ul>
711 </div>
712 `
713 }
714 }
715 ]);
716 ```
717
718 ### Interactive Form Block
719
720 ```javascript
721 // Create a form that locks the chatbot until completed
722 MwaiAPI.getChatbot().setBlocks([
723 {
724 type: 'content',
725 data: {
726 html: `
727 <div class="custom-form-block">
728 <h4>Quick Survey</h4>
729 <p>Please help us improve by answering this question:</p>
730 <form id="surveyForm">
731 <label>How satisfied are you with our service?</label><br>
732 <select id="satisfaction" required>
733 <option value="">Choose...</option>
734 <option value="very-satisfied">Very Satisfied</option>
735 <option value="satisfied">Satisfied</option>
736 <option value="neutral">Neutral</option>
737 <option value="unsatisfied">Unsatisfied</option>
738 </select><br><br>
739 <button type="submit">Submit</button>
740 </form>
741 </div>
742 `,
743 script: `
744 const chatbot = MwaiAPI.getChatbot();
745 chatbot.lock(); // Prevent further messages
746
747 document.getElementById('surveyForm').addEventListener('submit', function(e) {
748 e.preventDefault();
749 const satisfaction = document.getElementById('satisfaction').value;
750
751 // Send the response as a message
752 chatbot.ask('My satisfaction level is: ' + satisfaction, true);
753
754 // Remove the block and unlock
755 chatbot.setBlocks([]);
756 chatbot.unlock();
757 });
758 `
759 }
760 }
761 ]);
762 ```
763
764 ## Adding Blocks via PHP
765
766 ### Conditional Block Display
767
768 ```php
769 add_filter( 'mwai_chatbot_blocks', function ( $blocks, $args ) {
770 // Show block when specific keywords are detected
771 $message = $args['newMessage'] ?? '';
772 $reply = $args['reply'] ?? '';
773
774 // Show appointment form when appointment is mentioned
775 if (stripos($message . $reply, 'appointment') !== false) {
776 $blocks[] = [
777 'type' => 'content',
778 'data' => [
779 'html' => '
780 <div class="appointment-block">
781 <h4>Book an Appointment</h4>
782 <form id="appointmentForm">
783 <label>Select Date:</label>
784 <input type="date" id="apptDate" required><br><br>
785
786 <label>Select Time:</label>
787 <select id="apptTime" required>
788 <option value="9:00">9:00 AM</option>
789 <option value="10:00">10:00 AM</option>
790 <option value="14:00">2:00 PM</option>
791 <option value="15:00">3:00 PM</option>
792 </select><br><br>
793
794 <label>Your Name:</label>
795 <input type="text" id="apptName" required><br><br>
796
797 <button type="submit">Book Now</button>
798 </form>
799 </div>
800 ',
801 'script' => '
802 const chatbot = MwaiAPI.getChatbot("' . $args['botId'] . '");
803 chatbot.lock();
804
805 document.getElementById("appointmentForm").addEventListener("submit", function(e) {
806 e.preventDefault();
807
808 const date = document.getElementById("apptDate").value;
809 const time = document.getElementById("apptTime").value;
810 const name = document.getElementById("apptName").value;
811
812 // Send appointment details
813 chatbot.ask(`Book appointment for ${name} on ${date} at ${time}`, true);
814
815 // Show confirmation
816 chatbot.setBlocks([{
817 type: "content",
818 data: {
819 html: "<div style=\"color: green; padding: 10px;\">�
820 Appointment request sent!</div>"
821 }
822 }]);
823
824 chatbot.unlock();
825
826 // Clear confirmation after 3 seconds
827 setTimeout(() => chatbot.setBlocks([]), 3000);
828 });
829 '
830 ]
831 ];
832 }
833
834 return $blocks;
835 }, 10, 2);
836 ```
837
838 ### Product Showcase Block
839
840 ```php
841 add_filter( 'mwai_chatbot_blocks', function ( $blocks, $args ) {
842 // Show products when requested
843 if (stripos($args['reply'], 'here are our products') !== false) {
844 $products = wc_get_products(['limit' => 3, 'status' => 'publish']);
845
846 $html = '<div class="products-showcase">';
847 $html .= '<h4>Featured Products</h4>';
848 $html .= '<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;">';
849
850 foreach ($products as $product) {
851 $html .= sprintf(
852 '<div style="border: 1px solid #ddd; padding: 10px; text-align: center;">
853 <img src="%s" style="width: 100%%; height: 100px; object-fit: cover;">
854 <h5>%s</h5>
855 <p>%s</p>
856 <button onclick="MwaiAPI.getChatbot(\'%s\').ask(\'Tell me more about %s\', true)">Learn More</button>
857 </div>',
858 wp_get_attachment_url($product->get_image_id()),
859 esc_html($product->get_name()),
860 wc_price($product->get_price()),
861 $args['botId'],
862 esc_html($product->get_name())
863 );
864 }
865
866 $html .= '</div></div>';
867
868 $blocks[] = [
869 'type' => 'content',
870 'data' => ['html' => $html]
871 ];
872 }
873
874 return $blocks;
875 }, 10, 2);
876 ```
877
878 ### Data Collection Wizard
879
880 ```php
881 add_filter( 'mwai_chatbot_blocks', function ( $blocks, $args ) {
882 // Multi-step form wizard
883 if (stripos($args['newMessage'], 'start wizard') !== false) {
884 $blocks[] = [
885 'type' => 'content',
886 'data' => [
887 'html' => '
888 <div id="wizard" data-step="1">
889 <div class="step" id="step1">
890 <h4>Step 1: Your Information</h4>
891 <input type="text" id="userName" placeholder="Your name">
892 <button onclick="nextStep()">Next</button>
893 </div>
894
895 <div class="step" id="step2" style="display:none;">
896 <h4>Step 2: Your Interest</h4>
897 <select id="interest">
898 <option>Product Information</option>
899 <option>Technical Support</option>
900 <option>Pricing</option>
901 </select>
902 <button onclick="prevStep()">Back</button>
903 <button onclick="nextStep()">Next</button>
904 </div>
905
906 <div class="step" id="step3" style="display:none;">
907 <h4>Step 3: Summary</h4>
908 <div id="summary"></div>
909 <button onclick="prevStep()">Back</button>
910 <button onclick="submitWizard()">Submit</button>
911 </div>
912 </div>
913 ',
914 'script' => '
915 const chatbot = MwaiAPI.getChatbot("' . $args['botId'] . '");
916 chatbot.lock();
917
918 window.nextStep = function() {
919 const wizard = document.getElementById("wizard");
920 const currentStep = parseInt(wizard.dataset.step);
921
922 // Hide current step
923 document.getElementById("step" + currentStep).style.display = "none";
924
925 // Show next step
926 const nextStep = currentStep + 1;
927 document.getElementById("step" + nextStep).style.display = "block";
928 wizard.dataset.step = nextStep;
929
930 // Update summary on last step
931 if (nextStep === 3) {
932 const name = document.getElementById("userName").value;
933 const interest = document.getElementById("interest").value;
934 document.getElementById("summary").innerHTML =
935 `<p>Name: ${name}</p><p>Interest: ${interest}</p>`;
936 }
937 };
938
939 window.prevStep = function() {
940 const wizard = document.getElementById("wizard");
941 const currentStep = parseInt(wizard.dataset.step);
942 document.getElementById("step" + currentStep).style.display = "none";
943 const prevStep = currentStep - 1;
944 document.getElementById("step" + prevStep).style.display = "block";
945 wizard.dataset.step = prevStep;
946 };
947
948 window.submitWizard = function() {
949 const name = document.getElementById("userName").value;
950 const interest = document.getElementById("interest").value;
951
952 chatbot.ask(`Wizard completed. Name: ${name}, Interest: ${interest}`, true);
953 chatbot.setBlocks([]);
954 chatbot.unlock();
955 };
956 '
957 ]
958 ];
959 }
960
961 return $blocks;
962 }, 10, 2);
963 ```
964
965 ## Block Best Practices
966
967 1. **Always unlock the chatbot** when done with user interaction
968 2. **Clean up blocks** after they're no longer needed
969 3. **Use unique IDs** for form elements to avoid conflicts
970 4. **Test across devices** - ensure blocks work on mobile
971 5. **Provide fallbacks** for users who might have JavaScript disabled
972 6. **Keep scripts focused** - each block should have a single purpose
973
974 ---
975
976 # MCP (Model Context Protocol)
977
978 The Model Context Protocol (MCP) enables AI agents like Claude to interact with WordPress sites through a standardized tool interface. AI Engine provides a comprehensive MCP implementation that allows developers to extend WordPress functionality accessible to AI.
979
980 ## Overview
981
982 MCP is a protocol that allows AI models to use tools (functions) to interact with external systems. In AI Engine, this means Claude can manage WordPress content, upload media, analyze images, and perform custom operations defined by developers.
983
984 ## Adding Custom MCP Functions
985
986 ### Basic Example
987
988 ```php
989 // 1. Register your tool
990 add_filter( 'mwai_mcp_tools', function( $tools ) {
991 $tools[] = [
992 'name' => 'get_weather',
993 'description' => 'Get current weather for a city. Returns temperature and conditions.',
994 'inputSchema' => [
995 'type' => 'object',
996 'properties' => [
997 'city' => [
998 'type' => 'string',
999 'description' => 'City name (e.g., "New York", "London")'
1000 ],
1001 'units' => [
1002 'type' => 'string',
1003 'enum' => ['celsius', 'fahrenheit'],
1004 'default' => 'celsius',
1005 'description' => 'Temperature units'
1006 ]
1007 ],
1008 'required' => ['city']
1009 ]
1010 ];
1011 return $tools;
1012 });
1013
1014 // 2. Handle execution
1015 add_filter( 'mwai_mcp_callback', function( $result, $tool, $args, $id ) {
1016 if ( $tool !== 'get_weather' ) {
1017 return $result;
1018 }
1019
1020 // Your logic here
1021 $city = $args['city'];
1022 $units = $args['units'] ?? 'celsius';
1023
1024 // Simulated weather data
1025 $weather = [
1026 'city' => $city,
1027 'temperature' => rand(15, 30),
1028 'units' => $units,
1029 'conditions' => 'Partly cloudy'
1030 ];
1031
1032 return $weather; // AI Engine handles JSON-RPC wrapping
1033 }, 10, 4 );
1034 ```
1035
1036 ### WordPress Integration Example
1037
1038 ```php
1039 // Register a tool for custom post type management
1040 add_filter( 'mwai_mcp_tools', function( $tools ) {
1041 $tools[] = [
1042 'name' => 'manage_products',
1043 'description' => 'Create, update, or search WooCommerce products. Can handle inventory, pricing, and product details.',
1044 'inputSchema' => [
1045 'type' => 'object',
1046 'properties' => [
1047 'action' => [
1048 'type' => 'string',
1049 'enum' => ['create', 'update', 'search'],
1050 'description' => 'Action to perform'
1051 ],
1052 'title' => [
1053 'type' => 'string',
1054 'description' => 'Product title (for create/update)'
1055 ],
1056 'price' => [
1057 'type' => 'number',
1058 'description' => 'Product price'
1059 ],
1060 'sku' => [
1061 'type' => 'string',
1062 'description' => 'Product SKU'
1063 ],
1064 'stock' => [
1065 'type' => 'integer',
1066 'description' => 'Stock quantity'
1067 ],
1068 'search_term' => [
1069 'type' => 'string',
1070 'description' => 'Search term (for search action)'
1071 ],
1072 'product_id' => [
1073 'type' => 'integer',
1074 'description' => 'Product ID (for update action)'
1075 ]
1076 ],
1077 'required' => ['action']
1078 ]
1079 ];
1080 return $tools;
1081 });
1082
1083 add_filter( 'mwai_mcp_callback', function( $result, $tool, $args, $id ) {
1084 if ( $tool !== 'manage_products' ) return $result;
1085
1086 switch ( $args['action'] ) {
1087 case 'create':
1088 $product = new WC_Product_Simple();
1089 $product->set_name( $args['title'] );
1090 $product->set_regular_price( $args['price'] );
1091 if ( isset($args['sku']) ) $product->set_sku( $args['sku'] );
1092 if ( isset($args['stock']) ) {
1093 $product->set_manage_stock( true );
1094 $product->set_stock_quantity( $args['stock'] );
1095 }
1096 $product->save();
1097
1098 return [
1099 'success' => true,
1100 'product_id' => $product->get_id(),
1101 'message' => "Product '{$args['title']}' created successfully"
1102 ];
1103
1104 case 'search':
1105 $products = wc_get_products([
1106 's' => $args['search_term'],
1107 'limit' => 10
1108 ]);
1109
1110 return array_map( function($p) {
1111 return [
1112 'id' => $p->get_id(),
1113 'title' => $p->get_name(),
1114 'price' => $p->get_price(),
1115 'stock' => $p->get_stock_quantity()
1116 ];
1117 }, $products );
1118
1119 case 'update':
1120 // Update logic here
1121 break;
1122 }
1123 }, 10, 4 );
1124 ```
1125
1126 ## Best Practices for Tool Descriptions
1127
1128 **EXTREMELY IMPORTANT**: Write clear, detailed descriptions that help AI understand exactly what your tool does and when to use it.
1129
1130 ### Good Description Examples
1131
1132 ```php
1133 // �
1134 GOOD - Clear, specific, and actionable
1135 'description' => 'Search and filter WooCommerce products by name, SKU, or category. Returns product details including price, stock, and variations.'
1136
1137 // �
1138 GOOD - Explains capabilities and use cases
1139 'description' => 'Analyze website performance metrics including page load times, database queries, and memory usage. Useful for debugging slow pages.'
1140
1141 // ❌ BAD - Too vague
1142 'description' => 'Handle products'
1143
1144 // ❌ BAD - No context about what it returns
1145 'description' => 'Get data from API'
1146 ```
1147
1148 ### Parameter Descriptions
1149
1150 Always describe parameters clearly:
1151
1152 ```php
1153 'properties' => [
1154 'post_id' => [
1155 'type' => 'integer',
1156 'description' => 'WordPress post ID. Use 0 to get the current post.'
1157 ],
1158 'meta_key' => [
1159 'type' => 'string',
1160 'description' => 'Custom field name (e.g., "_price", "custom_color")'
1161 ],
1162 'format' => [
1163 'type' => 'string',
1164 'enum' => ['raw', 'formatted'],
1165 'default' => 'formatted',
1166 'description' => 'Output format. "raw" returns database value, "formatted" applies WordPress filters.'
1167 ]
1168 ]
1169 ```
1170
1171 ## Error Handling
1172
1173 ```php
1174 add_filter( 'mwai_mcp_callback', function( $result, $tool, $args, $id ) {
1175 if ( $tool !== 'your_tool' ) return $result;
1176
1177 try {
1178 // Validate inputs
1179 if ( empty($args['required_param']) ) {
1180 throw new Exception('Missing required parameter: required_param');
1181 }
1182
1183 // Check permissions
1184 if ( !current_user_can('edit_posts') ) {
1185 throw new Exception('Insufficient permissions to perform this action');
1186 }
1187
1188 // Your logic here
1189 $data = process_something($args);
1190
1191 if ( !$data ) {
1192 throw new Exception('Failed to process request: No data returned');
1193 }
1194
1195 return $data;
1196
1197 } catch ( Exception $e ) {
1198 // Exception message will be properly formatted as JSON-RPC error
1199 throw $e;
1200 }
1201 }, 10, 4 );
1202 ```
1203
1204 ## Built-in Tools Reference
1205
1206 AI Engine includes 40+ built-in tools. Key categories:
1207
1208 - **Posts**: create_post, read_post, update_post, delete_post, search_posts
1209 - **Media**: upload_media, get_media_url, delete_attachment
1210 - **Users**: create_user, update_user, get_current_user
1211 - **Options**: get_option, update_option
1212 - **AI Features**: vision (image analysis), imagine (image generation)
1213
1214 See implementation examples in:
1215 - `labs/mcp-core.php` - Core WordPress tools
1216 - `labs/mcp-rest.php` - REST API integration
1217 - `premium/mcp_plugin.php` - Plugin management
1218 - `premium/mcp_theme.php` - Theme management
1219
1220 ## Testing Your MCP Tools
1221
1222 1. **Enable MCP** in AI Engine settings
1223 2. **Get your Bearer token** from the MCP section
1224 3. **Add to Claude**: Use the MCP server URL with your token
1225 4. **Test with Claude**: Ask Claude to use your custom tool
1226
1227 Example Claude prompt:
1228 ```
1229 "Can you search for products with 'laptop' in the name and show me their prices?"
1230 ```
1231
1232 ## Advanced Features
1233
1234 ### Conditional Tool Registration
1235
1236 ```php
1237 add_filter( 'mwai_mcp_tools', function( $tools ) {
1238 // Only add tool if WooCommerce is active
1239 if ( class_exists('WooCommerce') ) {
1240 $tools[] = [
1241 'name' => 'woo_reports',
1242 'description' => 'Generate WooCommerce sales reports',
1243 // ... rest of tool definition
1244 ];
1245 }
1246
1247 // Add tool based on user capabilities
1248 if ( current_user_can('manage_options') ) {
1249 $tools[] = [
1250 'name' => 'admin_tasks',
1251 'description' => 'Perform administrative tasks',
1252 // ... rest of tool definition
1253 ];
1254 }
1255
1256 return $tools;
1257 });
1258 ```
1259
1260 ### Complex Return Values
1261
1262 ```php
1263 // Return structured data - AI Engine handles JSON encoding
1264 return [
1265 'status' => 'success',
1266 'data' => [
1267 'total' => 42,
1268 'items' => $items,
1269 'metadata' => [
1270 'generated_at' => current_time('mysql'),
1271 'cache_hit' => false
1272 ]
1273 ],
1274 'messages' => [
1275 'Found 42 matching items',
1276 'Results limited to first 20'
1277 ]
1278 ];
1279 ```
1280
1281 ### Access Control
1282
1283 ```php
1284 // Control MCP access
1285 add_filter( 'mwai_allow_mcp', function( $allow, $user_id ) {
1286 // Only allow specific users
1287 $allowed_users = [1, 42, 99];
1288 return in_array($user_id, $allowed_users);
1289 }, 10, 2 );
1290 ```
1291
1292 ## Tips for Success
1293
1294 1. **Start Simple**: Begin with read-only tools before adding write operations
1295 2. **Test Thoroughly**: Ensure your tools handle edge cases and invalid inputs
1296 3. **Document Well**: Good descriptions save time and improve AI accuracy
1297 4. **Security First**: Always validate inputs and check permissions
1298 5. **Return Useful Data**: Structure responses for easy AI interpretation
1299
1300 Remember: The MCP system automatically handles JSON-RPC protocol details, so focus on your business logic and return clean, structured data.
1301
1302 ---
1303
1304 # Discussion Context Menu
1305
1306 You can customize the context menu that appears when clicking the three-dot icon on discussions. The menu supports regular items, separators, and custom HTML content.
1307
1308 ## Menu Item Structure
1309
1310 Each menu item can have the following properties:
1311
1312 - `id`: Unique identifier for the item (required for regular items)
1313 - `type`: Item type - 'separator' or 'title' (optional, defaults to regular item)
1314 - `label`: Text to display (for regular items and titles)
1315 - `onClick`: Function called when item is clicked, receives the discussion object
1316 - `className`: CSS class names (defaults to 'mwai-menu-item')
1317 - `style`: Inline styles object (optional)
1318 - `html`: Custom HTML content (overrides label)
1319
1320 ## Examples
1321
1322 ### Add Custom Actions
1323
1324 ```javascript
1325 // Add a simple alert action
1326 MwaiAPI.addFilter('mwai_discussion_menu_items', (items, discussion) => {
1327 items.push({
1328 id: 'alert',
1329 label: 'Show Info',
1330 onClick: (discussion) => {
1331 alert(`Discussion ID: ${discussion.chatId}\nMessages: ${discussion.messages.length}`);
1332 }
1333 });
1334 return items;
1335 });
1336
1337
1338 // Add multiple items with separator
1339 MwaiAPI.addFilter('mwai_discussion_menu_items', (items, discussion) => {
1340 // Add separator before custom items
1341 items.push({ type: 'separator' });
1342
1343 // Add title
1344 items.push({
1345 type: 'title',
1346 label: 'Custom Actions'
1347 });
1348
1349 // Add export action
1350 items.push({
1351 id: 'export',
1352 label: 'Export JSON',
1353 onClick: (discussion) => {
1354 const json = JSON.stringify(discussion, null, 2);
1355 const blob = new Blob([json], { type: 'application/json' });
1356 const url = URL.createObjectURL(blob);
1357 const a = document.createElement('a');
1358 a.href = url;
1359 a.download = `discussion-${discussion.chatId}.json`;
1360 a.click();
1361 }
1362 });
1363
1364 // Add copy ID action
1365 items.push({
1366 id: 'copy-id',
1367 label: 'Copy Chat ID',
1368 onClick: (discussion) => {
1369 navigator.clipboard.writeText(discussion.chatId);
1370 alert('Chat ID copied to clipboard!');
1371 }
1372 });
1373
1374 return items;
1375 });
1376
1377 // Add item with custom HTML and styling
1378 MwaiAPI.addFilter('mwai_discussion_menu_items', (items, discussion) => {
1379 items.push({
1380 id: 'custom-html',
1381 html: `<div style="display: flex; align-items: center; gap: 8px;">
1382 <span style="font-size: 16px;">📊</span>
1383 <span>Stats: ${discussion.messages.length} msgs</span>
1384 </div>`,
1385 onClick: (discussion) => {
1386 console.log('Custom item clicked', discussion);
1387 }
1388 });
1389 return items;
1390 });
1391
1392 // Reorder or remove default items
1393 MwaiAPI.addFilter('mwai_discussion_menu_items', (items, discussion) => {
1394 // Move delete to top
1395 const deleteItem = items.find(item => item.id === 'delete');
1396 const otherItems = items.filter(item => item.id !== 'delete');
1397 return [deleteItem, ...otherItems];
1398 });
1399
1400 // Conditionally show items based on discussion
1401 MwaiAPI.addFilter('mwai_discussion_menu_items', (items, discussion) => {
1402 // Only show archive option for discussions with more than 10 messages
1403 if (discussion.messages.length > 10) {
1404 items.push({
1405 id: 'archive',
1406 label: 'Archive',
1407 className: 'mwai-menu-item',
1408 style: { color: '#0066cc' },
1409 onClick: (discussion) => {
1410 console.log('Archiving discussion:', discussion.chatId);
1411 // Your archive logic here
1412 }
1413 });
1414 }
1415 return items;
1416 });
1417 ```
1418
1419 ### Complete Example with All Features
1420
1421 ```javascript
1422 // Comprehensive context menu customization
1423 MwaiAPI.addFilter('mwai_discussion_menu_items', (items, discussion) => {
1424 // Keep default items
1425 const newItems = [...items];
1426
1427 // Add separator
1428 newItems.push({ type: 'separator' });
1429
1430 // Add section title
1431 newItems.push({
1432 type: 'title',
1433 label: 'Developer Tools'
1434 });
1435
1436 // Add debug info item
1437 newItems.push({
1438 id: 'debug',
1439 label: 'Debug Info',
1440 onClick: (discussion) => {
1441 console.log('Discussion Object:', discussion);
1442 alert(`Chat ID: ${discussion.chatId}\nTitle: ${discussion.title || 'Untitled'}\nMessages: ${discussion.messages.length}`);
1443 }
1444 });
1445
1446 // Add item with custom icon (using emoji as HTML)
1447 newItems.push({
1448 id: 'favorite',
1449 html: '<span>⭐ Add to Favorites</span>',
1450 onClick: (discussion) => {
1451 // Your favorite logic here
1452 console.log('Added to favorites:', discussion.chatId);
1453 }
1454 });
1455
1456 return newItems;
1457 }, 20); // Higher priority to run after other filters
1458 ```