UNPKG

ai-ip-plugin

Version:

AI-IP Plugin for MCP Workflow Management with SSE streaming and event handling

563 lines (455 loc) 13.9 kB
# AI-IP Plugin [![npm version](https://badge.fury.io/js/ai-ip-plugin.svg)](https://badge.fury.io/js/ai-ip-plugin) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg)](http://www.typescriptlang.org/) A comprehensive TypeScript plugin for managing MCP (Multi-agent Conversation Protocol) workflows with SSE (Server-Sent Events) streaming, event handling, and data management. ## ✨ Features - 🚀 **Complete MCP Workflow Management**: Start, continue, resume, and stop workflows - 📡 **SSE Stream Processing**: Real-time server-sent events handling with automatic reconnection - 🎯 **Event-Driven Architecture**: Comprehensive event system for workflow states - 📊 **Intelligent Data Management**: Advanced workflow data caching and state management - 🔧 **Full TypeScript Support**: Complete type safety with comprehensive type definitions - ⚛️ **React Integration**: Optional React hooks for seamless integration - 🏗️ **Modular Architecture**: Clean separation of concerns with pluggable design - 🛡️ **Error Handling**: Robust error handling and recovery mechanisms - 🔄 **State Synchronization**: Real-time state updates and data synchronization - 📝 **Oral Text Processing**: Advanced text processing for speech synthesis ## Installation ```bash # Using npm npm install ai-ip-plugin # Using yarn yarn add ai-ip-plugin # Using pnpm pnpm add ai-ip-plugin ``` ## Quick Start ### Basic Usage ```typescript import { MCPManager } from "ai-ip-plugin"; // Initialize the manager const mcpManager = new MCPManager({ baseURL: "https://your-api-endpoint.com", token: "your-auth-token", // Optional timeout: 30000, // Optional, default 30s onStateChange: (state) => { console.log("State changed:", state); // state: { taskId, isLoading, error, currentStep } }, onDataUpdate: (data) => { console.log("Data updated:", data); // data: Map<string, MessageItem> }, onError: (error) => { console.error("Error:", error); }, }); // Start a workflow await mcpManager.startWorkflow({ userInput: "Create a blog post about AI", pid: 123, language: "zh", readability: 5, scriptLength: 1000, style: "professional", isRag: true, isPersona: false, isWebsearch: true, }); // Continue a workflow await mcpManager.continueWorkflow({ taskId: "task-123", userMessage: "Make it more technical", pid: 123, }); // Stop a workflow await mcpManager.stopWorkflow({ taskId: "task-123", pid: 123, interruptReason: "User requested stop", interruptType: 1, interruptData: { userMessage: "Stop processing" }, }); ``` ### React Hook Usage ```typescript import { useMCPPlugin } from "ai-ip-plugin"; function MyComponent() { const { // State currentTaskId, isLoading, error, currentStep, workflowData, // Actions startWorkflow, continueWorkflow, resumeWorkflow, stopWorkflow, getHistory, getWorkflowSlider, // Utilities initNewOralTxt, updateOralTxt, synchronousOralTxt, } = useMCPPlugin({ baseURL: "https://your-api-endpoint.com", token: "your-auth-token", }); const handleStart = async () => { await startWorkflow({ userInput: "Generate content about AI", pid: 123, language: "zh", isRag: true, isWebsearch: true, }); }; const handleContinue = async () => { if (currentTaskId) { await continueWorkflow({ taskId: currentTaskId, userMessage: "Make it more detailed", pid: 123, }); } }; const handleStop = async () => { if (currentTaskId) { await stopWorkflow({ taskId: currentTaskId, pid: 123, interruptReason: "User stop", interruptType: 1, interruptData: { userMessage: "Stop" }, }); } }; return ( <div> <div> <button onClick={handleStart} disabled={isLoading}> {isLoading ? "Processing..." : "Start Workflow"} </button> <button onClick={handleContinue} disabled={!currentTaskId || isLoading}> Continue </button> <button onClick={handleStop} disabled={!currentTaskId}> Stop </button> </div> <div> <p>Task ID: {currentTaskId || "None"}</p> <p>Current Step: {currentStep || "None"}</p> <p>Workflow Items: {workflowData.size}</p> {error && <p style={{ color: "red" }}>Error: {error}</p>} </div> <div> <h3>Workflow Data:</h3> {Array.from(workflowData.entries()).map(([id, item]) => ( <div key={id}> <strong>{item.agent_type}:</strong> {item.content} </div> ))} </div> </div> ); } ``` ## 🏗️ Architecture ### Core Components 1. **MCPManager**: Main orchestrator class that manages the entire workflow lifecycle 2. **EventHandler**: Robust event emission and listening system with error handling 3. **StreamProcessor**: Advanced SSE stream processing with automatic parsing and reconnection 4. **DataManager**: Intelligent workflow data and state management with caching 5. **APIService**: HTTP API communication layer with retry logic and error handling ### 🎯 Event System The plugin supports comprehensive event handling for all workflow states: #### Workflow Events - `workflow_created`: New workflow initiated - `workflow_restarted`: Workflow restarted from interruption - `workflow_resumed`: Workflow resumed after pause - `workflow_interrupted`: Workflow interrupted by user or system - `end_of_workflow`: Workflow completed successfully #### Agent Events - `start_of_agent`: Agent begins processing - `end_of_agent`: Agent completes processing - `message`: Real-time content generation events - `tool_call`: Tool invocation events - `tool_call_result`: Tool execution results #### System Events - `connected`: SSE connection established - `error`: Error events with detailed information - `start_of_llm`: LLM processing begins - `end_of_llm`: LLM processing completes ### 📊 Data Flow ``` User Input MCPManager APIService SSE Stream State Updates EventHandler StreamProcessor Server Events DataManager React Components ``` ## 📚 API Reference ### MCPManager The main class for managing MCP workflows. #### Constructor Options ```typescript interface MCPManagerConfig extends APIConfig { // API Configuration baseURL: string; // Required: API endpoint URL token?: string; // Optional: Authentication token timeout?: number; // Optional: Request timeout (default: 30000ms) // Event Callbacks onStateChange?: (state: MCPManagerState) => void; onDataUpdate?: (data: Map<string, MessageItem>) => void; onError?: (error: Error) => void; } interface MCPManagerState { taskId: string | null; // Current task ID isLoading: boolean; // Loading state error: string | null; // Error message currentStep: string | null; // Current processing step } ``` #### Core Methods ##### Workflow Management - `startWorkflow(params: MCPStartProps): Promise<void>` - Start a new workflow with user input - `continueWorkflow(params: MCPContinueProps): Promise<void>` - Continue an interrupted workflow - `resumeWorkflow(params: MCPResumeParams): Promise<void>` - Resume a paused workflow with new parameters - `stopWorkflow(params: MCPInterruptParams): Promise<void>` - Stop a running workflow ##### Data Retrieval - `getWorkflowHistory(taskId: string): Promise<any[]>` - Get complete workflow history - `getWorkflowStateData(taskId: string): Promise<{success: boolean, oralText: string}>` - Get workflow state and oral text data ##### Utility Methods - `destroy(): void` - Clean up resources and event listeners - `abortCurrentStream(): void` - Abort current SSE stream ### 🔧 Type Definitions #### Workflow Parameters ```typescript interface MCPStartProps { userInput: string; // User's input text pid: number; // User/Project ID language: string; // Language code (e.g., "zh", "en") readability?: number; // Readability level (1-10) scriptLength?: number; // Target script length style?: string; // Writing style isRag?: boolean; // Enable RAG (Retrieval-Augmented Generation) isPersona?: boolean; // Enable persona-based generation isWebsearch?: boolean; // Enable web search } interface MCPContinueProps { taskId: string; // Task ID to continue userMessage: string; // User's continuation message pid: number; // User/Project ID } interface MCPResumeParams { taskId: string; // Task ID to resume pid: number; // User/Project ID action: string; // Resume action type data: { [key: string]: any }; // Resume data } interface MCPInterruptParams { taskId: string; // Task ID to interrupt pid: number; // User/Project ID interruptReason: string; // Reason for interruption interruptType: number; // Type of interruption (1=user, 2=system) interruptData: { userMessage: string; // User's interrupt message }; } ``` #### Message Structure ```typescript interface MessageItem { content: string; // Message content type: "human" | "ai" | "tool"; // Message type agent_type: string; // Agent type (e.g., "writer", "planner") event: MCPEvent; // Associated event uuid: string; // Unique identifier finished: boolean; // Completion status session_id: string; // Session identifier task_id?: number; // Associated task ID reasoning?: string; // Agent reasoning (for polisher) writing?: string; // Generated writing (for polisher) tool_calls?: ToolCall[]; // Tool calls made tool_content?: any[]; // Tool execution results additional_kwargs: { // Additional metadata tool_calls?: ToolFunctionCall[]; [key: string]: any; }; response_metadata: { // Response metadata finish_reason?: string; model_name?: string; system_fingerprint?: string; [key: string]: any; }; } ``` #### Utility Types ```typescript interface OralTextInfo { label: string; // Display label reasoning: string; // Reasoning text writing: string; // Writing content id: number; // Numeric ID uuid: string; // Unique identifier } interface SentenceInfo { speed: number; // Speech speed sentence: any; // Sentence data audioUrl: string; // Audio file URL voiceId: string; // Voice model ID } type LT = | "zh" | "zh-Hant" | "en" | "es" | "fr" | "de" | "ja" | "ru" | "it" | "pl" | "th" | "hi" | "id" | "pt" | "ko" | "vi"; ``` ## 🔄 Migration Guide ### From useMCP to ai-ip-plugin If you're migrating from the original `useMCP` hook, the transition is seamless: #### Before (Original useMCP) ```typescript import { useMCP } from "@/hooks/useMCP"; function MyComponent() { const { SSEInit, ContinueSSE, ResumeSSE, StopSSE, GetHistory, GetWorkflowSlider, currentTaskId, startError, initNewOralTxt, updateOralTxt, synchronousOralTxt, } = useMCP(); // Usage await SSEInit({ userInput: "Generate content", pid: 123, language: "zh", }); } ``` #### After (ai-ip-plugin) ```typescript import { useMCPPlugin } from "ai-ip-plugin"; function MyComponent() { const { startWorkflow, // Renamed from SSEInit continueWorkflow, // Renamed from ContinueSSE resumeWorkflow, // Renamed from ResumeSSE stopWorkflow, // Renamed from StopSSE getHistory, // Renamed from GetHistory getWorkflowSlider, // Renamed from GetWorkflowSlider currentTaskId, error, // Renamed from startError initNewOralTxt, updateOralTxt, synchronousOralTxt, } = useMCPPlugin({ baseURL: "https://your-api-endpoint.com", }); // Usage (same parameters) await startWorkflow({ userInput: "Generate content", pid: 123, language: "zh", }); } ``` ### Migration Benefits **Enhanced Features:** - Better error handling and recovery - Real-time state synchronization - Improved TypeScript support - Modular and reusable architecture - More reliable SSE connection handling **Backward Compatibility:** - Same parameter interfaces - Similar method signatures - Consistent data structures **New Capabilities:** - Advanced event system - Better debugging support - Plugin-based architecture - Cross-project reusability ## 🛠️ Development ### Prerequisites - Node.js 16+ - TypeScript 5.0+ - React 16.8+ (for React hooks) ### Building ```bash # Install dependencies npm install # Build the plugin npm run build # Watch mode for development npm run dev # Clean build artifacts npm run clean ``` ### Testing ```bash # Run tests npm test # Run tests in watch mode npm run test:watch # Run tests with coverage npm run test:coverage ``` ### Publishing ```bash # Build and publish to npm npm run prepublishOnly npm publish ``` ## 🤝 Contributing 1. Fork the repository 2. Create your feature branch (`git checkout -b feature/amazing-feature`) 3. Commit your changes (`git commit -m 'Add some amazing feature'`) 4. Push to the branch (`git push origin feature/amazing-feature`) 5. Open a Pull Request ## 📄 License MIT License - see [LICENSE](LICENSE) file for details. ## 🔗 Links - [NPM Package](https://www.npmjs.com/package/ai-ip-plugin) - [GitHub Repository](https://github.com/your-username/mono-repo) - [Documentation](https://github.com/your-username/mono-repo/tree/main/packages/js-ts-plugin#readme) - [Issues](https://github.com/your-username/mono-repo/issues) ## 📊 Package Stats - **Bundle Size**: ~50KB (minified) - **Dependencies**: Zero runtime dependencies - **TypeScript**: Full type definitions included - **React**: Optional peer dependency - **Node.js**: Compatible with Node.js 16+ --- Made with ❤️ for the AI development community