### MCP SuperAssistant Development Setup and Build Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/README.md Commands for setting up the development environment and building the MCP SuperAssistant project. It includes installing dependencies, starting the development server, building for production, and creating a distributable zip package. ```bash # Install dependencies pnpm install # Start development server pnpm dev # Build for production pnpm build # Create zip package for distribution pnpm zip ``` -------------------------------- ### Installing UI Package Dependency Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/packages/ui/README.md Details the steps for installing the `@extension/ui` package as a dependency in a project. This includes navigating to the relevant directory, updating `package.json` with the workspace dependency, and running the package manager install command. ```shell cd pages/options ``` ```json { "dependencies": { "@extension/ui": "workspace:*" } } ``` ```shell pnpm install ``` -------------------------------- ### Example config.json for MCP SuperAssistant Proxy Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/README.md An example configuration file (config.json) for the MCP SuperAssistant proxy. This JSON object specifies server configurations, including commands and arguments for launching specific tools like desktop-commander. ```json { "mcpServers": { "desktop-commander": { "command": "npx", "args": [ "-y", "@wonderwhy-er/desktop-commander" ] } } } ``` -------------------------------- ### Adapter Hostname Configuration Example Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/plugins/adapters/README.md Illustrates the best practice of defining specific hostnames for an adapter to ensure it only activates on designated websites, preventing conflicts. ```typescript readonly hostnames = ['example.com', 'www.example.com']; ``` -------------------------------- ### Setup Popup and Options Apps - TypeScript Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/core/README.md This code initializes the React-based UI applications for popup and options pages. It uses `setupPopupApp` and `setupOptionsApp` from the UI initializer, requiring the respective React component as an argument. Error handling is included for the asynchronous initialization process. ```typescript import { setupPopupApp } from './core/ui-initializer'; // For popup applications await setupPopupApp(PopupAppComponent); // For options pages await setupOptionsApp(OptionsAppComponent); ``` -------------------------------- ### Action Design Examples (TypeScript) Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/stores/README.md Provides examples of well-designed and less optimal actions for state mutations. The 'Good' examples show actions with a single responsibility (e.g., `setActiveAdapter`, `clearAdapterError`), contrasting with the 'Less optimal' example of an action performing multiple tasks. ```typescript // Good - single responsibility const setActiveAdapter = (name: string) => { /* ... */ }; const clearAdapterError = () => { /* ... */ }; // Less optimal - multiple responsibilities const updateAdapter = (name?: string, clearError?: boolean) => { /* ... */ }; ``` -------------------------------- ### Install shadcn/ui Dependencies Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/packages/ui/README.md Installs the required npm packages for shadcn/ui and Tailwind CSS integration. These include 'tailwindcss-animate', 'class-variance-authority', 'tailwind-merge', and 'lucide-react'. ```shell pnpm add tailwindcss-animate class-variance-authority tailwind-merge lucide-react -F ui ``` -------------------------------- ### Git Workflow for Contributions Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/README.md This snippet demonstrates the standard Git commands for contributing to a project. It covers forking the repository, creating a new feature branch, committing changes, and pushing the branch to initiate a pull request. No external dependencies are required beyond a Git installation. ```bash git checkout -b feature/amazing-feature git commit -m 'Add some amazing feature' git push origin feature/amazing-feature ``` -------------------------------- ### Full Component Architecture Integration Example Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/components/README.md A template for a component that integrates fully with the project's architecture, utilizing hooks for state management (`useStores`), adapters (`useAdapter`), and event handling (`useEventBus`). ```typescript // Component with full architecture integration import { useStores } from '../../hooks/useStores'; import { useAdapter } from '../../hooks/useAdapter'; import { useEventBus } from '../../hooks/useEventBus'; interface MyComponentProps { // Props interface } export function MyComponent({ ...props }: MyComponentProps) { // Hook usage const stores = useStores(); const adapter = useAdapter(); const events = useEventBus(); // Component logic return ( // JSX with proper styling and event handling ); } ``` -------------------------------- ### State Structure Examples (TypeScript) Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/stores/README.md Compares two approaches for structuring state related to 'tools'. The 'Good' example shows a normalized and flat structure using records, while the 'Less optimal' example demonstrates a less efficient structure with nested arrays and direct object references. ```typescript // Good interface ToolState { tools: Record; activeToolId: string | null; } // Less optimal interface ToolState { activeTool: Tool | null; otherTools: Tool[]; } ``` -------------------------------- ### Event-Driven Components with Hooks Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/hooks/README.md Shows how to use `useEventListener` to monitor events and `useEventEmitter` to trigger them. This example demonstrates capturing tool execution start and completion events and updating component state accordingly. ```typescript import { useEventListener, useEventEmitter } from '@src/hooks'; function EventMonitor() { const [events, setEvents] = useState([]); const emit = useEventEmitter(); // Monitor all tool executions useEventListener('tool:execution-started', (data) => { setEvents(prev => [...prev, { type: 'started', ...data }]); }); useEventListener('tool:execution-completed', (data) => { setEvents(prev => [...prev, { type: 'completed', ...data }]); }); const triggerTest = () => { emit('tool:execution-started', { toolName: 'test', callId: Date.now().toString() }); }; return (
); } ``` -------------------------------- ### Run MCP SuperAssistant Proxy via npx Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/README.md Command to start the MCP SuperAssistant proxy server using npx. This is useful for proxying remote MCP servers, adding CORS support, and providing health endpoints. It requires Node.js and pnpm. ```bash npx @srbhptl39/mcp-superassistant-proxy@latest --config ./config.json ``` -------------------------------- ### Migrating from Legacy Adapters (TypeScript) Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/plugins/README.md Compares the old method of getting and initializing adapters with the new approach using React hooks. The new method utilizes `useCurrentAdapter` to access adapter functionalities like `insertText` and `isReady`. ```typescript // Old way const adapter = adapterRegistry.getAdapter(hostname); adapter.initialize(); // New way import { useCurrentAdapter } from '@src/hooks'; const { insertText, isReady } = useCurrentAdapter(); ``` -------------------------------- ### Install Package with pnpm Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/packages/i18n/README.md Command to install the project dependencies, including the '@extension/i18n' package, after updating package.json. This command is specific to the pnpm package manager. ```bash pnpm install ``` -------------------------------- ### Configurable Persistence with Zustand `persist` (TypeScript) Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/stores/README.md Shows how to configure Zustand stores for persistence using the `persist` middleware. This example demonstrates setting a `name` for the storage key and using `partialize` to selectively persist only specific parts of the state, such as `globalSettings`. It requires the `zustand/persist` middleware. ```typescript import { create } from 'zustand'; import { devtools } from 'zustand/middleware'; import { persist } from 'zustand/middleware'; export const useAppStore = create()( devtools( persist( (set, get) => ({ // Store implementation }), { name: 'app-store', partialize: (state) => ({ globalSettings: state.globalSettings }) } ) ) ); ``` -------------------------------- ### Event System Integration using Event Bus Hook Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/components/README.md Shows how components can emit events using the `useEventBus` hook. This example demonstrates emitting a 'tool:requested' event when a tool button is clicked, passing relevant data. ```typescript import { useEventBus } from '../../hooks/useEventBus'; export function ToolButton({ toolId }: { toolId: string }) { const { emit } = useEventBus(); const handleClick = () => { emit('tool:requested', { toolId, source: 'button' }); }; return ; } ``` -------------------------------- ### Get Error Statistics - TypeScript Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/core/README.md This snippet shows how to retrieve error statistics from the global error handler. It accesses `getErrorStats` to get details like the total number of errors and a breakdown of errors by component, which is useful for monitoring and debugging. ```typescript const errorStats = globalErrorHandler.getErrorStats(); console.log('Total errors:', errorStats.totalErrors); console.log('Errors by component:', errorStats.errorsByComponent); ``` -------------------------------- ### Define Placeholders in Korean Messages Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/packages/i18n/README.md Provides an example of messages with placeholders in a Korean messages.json file. It mirrors the English structure for 'greeting' and 'hello' messages. ```json { "greeting": { "description": "인사 메시지", "message": "안녕하세요, 제 이름은 $NAME$입니다.", "placeholders": { "name": { "content": "$1", "example": "서종학" } } }, "hello": { "description": "Placeholder 예시", "message": "안녕 $1" } } ``` -------------------------------- ### Initialize Event System in TypeScript Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/events/README.md Provides an example of how to initialize the entire event system, including the event bus and global event handlers, by calling `initializeEventSystem()`. This function is typically invoked during the application's startup phase. The `async` keyword indicates that initialization might involve asynchronous operations. ```typescript import { initializeEventSystem } from './events/event-system'; async function startApp() { await initializeEventSystem(); // ... other initializations } ``` -------------------------------- ### Performance Monitoring (TypeScript) Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/plugins/README.md Illustrates how to use the `performanceMonitor` utility to track the performance of plugin operations, such as activation. It involves starting a timer before an operation and ending it afterward to measure execution time. ```typescript // Track plugin performance import { performanceMonitor } from '@src/core/performance'; performanceMonitor.startTimer('plugin-activation'); await plugin.activate(); performanceMonitor.endTimer('plugin-activation'); ``` -------------------------------- ### Importing and Using Logger Utility in TypeScript Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/utils/README.md Shows how to import and use a default logger instance from a hypothetical 'logger.ts' utility module. This example logs an informational message with a specific prefix. ```typescript import logger from './logger'; // Assuming logger.ts exports a default logger instance logger.info('[MyComponent] Component initialized successfully.'); ``` -------------------------------- ### React Component Adapting UI based on Adapter Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/packages/ui/README.md Illustrates how UI components can adapt their appearance or behavior based on the current site adapter provided by the extension architecture. This example shows how to use the `useAdapter` hook to retrieve adapter-specific UI themes. ```tsx import { useAdapter } from '@extension/content'; export function AdaptiveButton() { const { currentAdapter } = useAdapter(); // Adapt button style based on current site adapter const buttonStyle = currentAdapter?.getUITheme?.() || 'default'; return ; } ``` -------------------------------- ### Defensive Programming: Element Existence Check Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/plugins/adapters/README.md Provides an example of defensive programming by checking if a target DOM element exists before attempting to interact with it, logging a warning if not found. ```typescript const element = document.querySelector('.target'); if (!element) { this.context.logger.warn('Target element not found'); return false; } ``` -------------------------------- ### Automatic Store Synchronization with Event Bus (TypeScript) Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/stores/README.md Shows how to subscribe to events from an event bus within a store to automatically synchronize state. This example listens for `adapter:activated` and `adapter:error` events and updates the store's state accordingly. It assumes a global `eventBus` object is available and configured. ```typescript // In adapter.store.ts eventBus.on('adapter:activated', ({ pluginName }) => { set(state => ({ ...state, activeAdapterName: pluginName, lastAdapterError: null })); }); eventBus.on('adapter:error', ({ name, error }) => { set(state => ({ ...state, lastAdapterError: { name, error, timestamp: Date.now() } })); }); ``` -------------------------------- ### Cross-Store Operations with Multiple Hooks (TypeScript) Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/stores/README.md Demonstrates how to access state from multiple Zustand stores within a single component to derive combined state. This example checks the initialization status of the app store and the readiness of an adapter from the adapter store. It requires importing multiple store hooks. ```typescript import { useAppStore, useAdapterStore } from '@src/stores'; function StatusDisplay() { const appInitialized = useAppStore(state => state.isInitialized); const adapterReady = useAdapterStore(state => !!state.activeAdapterName); const isReady = appInitialized && adapterReady; return (
Status: {isReady ? 'Ready' : 'Initializing...'}
); } ``` -------------------------------- ### Initialize and Cleanup Application - TypeScript Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/core/README.md This snippet demonstrates how to initialize and clean up the entire application using the `applicationInit` and `applicationCleanup` functions from the main initializer. It's crucial for setting up and tearing down application-wide services and states. ```typescript import { applicationInit, applicationCleanup } from './core/main-initializer'; // Initialize the complete application await applicationInit(); // Cleanup when needed await applicationCleanup(); ``` -------------------------------- ### Initialize Plugin System (TypeScript) Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/plugins/README.md Demonstrates the basic usage of initializing the plugin system. It imports the `initializePluginRegistry` function and calls it asynchronously to set up the system. ```typescript // Initialize the plugin system import { initializePluginRegistry } from '@src/plugins'; await initializePluginRegistry(); ``` -------------------------------- ### Popup Initialization with React Component - TypeScript Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/core/README.md This code snippet initializes the popup application in a Chrome extension context. It imports `setupPopupApp` and the main initializer, then uses `setupPopupApp` with the `PopupApp` React component. It includes error handling for the asynchronous initialization. ```typescript // chrome-extension/src/popup/index.tsx import React from 'react'; import { setupPopupApp } from '../content/src/core/ui-initializer'; import PopupApp from './PopupApp'; setupPopupApp(PopupApp).catch(error => { console.error('Popup initialization failed:', error); }); ``` -------------------------------- ### Content Script Application Initialization - TypeScript Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/core/README.md This snippet shows the initialization of the application within a content script. It calls `applicationInit` and uses a `.then()` and `.catch()` block to log success or failure messages to the console, indicating whether the application is ready or if initialization failed. ```typescript // pages/content/src/index.ts import { applicationInit } from './core/main-initializer'; // Initialize the complete application applicationInit() .then(() => { console.log('Application ready'); }) .catch(error => { console.error('Initialization failed:', error); }); ``` -------------------------------- ### Define Korean Translation Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/packages/i18n/README.md Example of a messages.json file for Korean locales. It defines a 'helloWorld' message, providing the Korean translation for internationalization. ```json { "helloWorld": { "message": "안녕하세요, 여러분!" } } ``` -------------------------------- ### TypeScript: Backward Compatibility with Legacy System Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/core/README.md Maintains backward compatibility with a legacy system through bridge functions. It shows how to import from legacy initializers while recommending the new approach. ```typescript // Legacy initializer still works import { initializeApp } from './initializer'; // Still works // Recommended new approach import { applicationInit } from './core/main-initializer'; ``` -------------------------------- ### Configure shadcn/ui with components.json Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/packages/ui/README.md This JSON file configures shadcn/ui, specifying schema, style, Tailwind CSS integration, and component aliases. It's essential for initializing shadcn/ui within your project. ```json { "$schema": "https://ui.shadcn.com/schema.json", "style": "new-york", "rsc": false, "tsx": true, "tailwind": { "config": "tailwind.config.ts", "css": "lib/global.css", "baseColor": "zinc", "cssVariables": true, "prefix": "" }, "aliases": { "components": "@/lib/components", "utils": "@/lib/utils", "ui": "@/lib/components/ui", "lib": "@/lib", "hooks": "@/lib/hooks" }, "iconLibrary": "lucide" } ``` -------------------------------- ### Define English Translation Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/packages/i18n/README.md Example of a messages.json file for English locales. It defines a 'helloWorld' message for internationalization within a Chrome Extension. ```json { "helloWorld": { "message": "Hello, World!" } } ``` -------------------------------- ### Access Debug Utilities - TypeScript Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/core/README.md This code demonstrates how to access and utilize various debugging utilities exposed on the `window._appDebug` object in development mode. It allows direct access to application stores, services, performance statistics, and provides functions to clear debugging data. ```typescript // Access stores window._appDebug.stores.app.getState() // Access services window._appDebug.services.performanceMonitor.getStats() // Get performance and error statistics window._appDebug.getStats() // Clear debugging data window._appDebug.clearData() ``` -------------------------------- ### TypeScript: Cross-Component Event Listening Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/core/README.md Integrates with an event system for cross-component communication. It demonstrates listening for application initialization completion and unhandled errors using `eventBus.on`. ```typescript // Listen for initialization complete eventBus.on('app:initialized', ({ version, timestamp, initializationTime }) => { console.log(`App v${version} initialized in ${initializationTime}ms`); }); // Listen for errors eventBus.on('error:unhandled', ({ error, context }) => { console.error('Unhandled error:', error, 'Context:', context); }); ``` -------------------------------- ### Install I18n Package Dependency Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/packages/i18n/README.md Adds the '@extension/i18n' package as a dependency in package.json for use in Chrome Extensions. This allows access to internationalization features. ```json { "dependencies": { "@extension/i18n": "workspace:*" } } ``` -------------------------------- ### TypeScript: Plugin Event Emission and Listening Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/core/README.md Enables plugin integration with the event system, allowing plugins to emit custom events and listen for events like plugin registration. It uses `eventBus.emit` and `eventBus.on`. ```typescript // In a plugin eventBus.emit('plugin:custom-event', { data: 'example' }); // Listen for plugin events eventBus.on('plugin:registered', ({ name, version }) => { console.log(`Plugin ${name} v${version} registered`); }); ``` -------------------------------- ### TypeScript: Environment-Specific Configuration Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/core/README.md Handles environment-specific settings, such as enabling debug utilities, verbose logging, extended error reporting, and performance monitoring in development environments. ```typescript if (process.env.NODE_ENV === 'development') { // Debug utilities and verbose logging // Extended error reporting // Performance monitoring enabled } ``` -------------------------------- ### Hook Testing with @testing-library/react Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/hooks/README.md Provides an example of how to test custom hooks using `renderHook` from `@testing-library/react`. This allows for isolated testing of hook logic and its returned values and functions. ```typescript import { renderHook } from '@testing-library/react'; import { useCurrentAdapter } from '@src/hooks'; test('useCurrentAdapter returns correct data', () => { const { result } = renderHook(() => useCurrentAdapter()); expect(result.current.isReady).toBeDefined(); expect(typeof result.current.insertText).toBe('function'); }); ``` -------------------------------- ### TypeScript: Custom Performance Tracking Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/core/README.md Allows for custom performance tracking by timing specific operations and marking/measuring performance points. It uses `performanceMonitor.time`, `performanceMonitor.mark`, and `performanceMonitor.measure`. ```typescript // Time a custom operation await performanceMonitor.time('custom-operation', async () => { await customAsyncOperation(); }); // Mark performance points performanceMonitor.mark('operation-start'); // ... do work ... performanceMonitor.measure('operation-duration', 'operation-start'); ``` -------------------------------- ### Background Script Core Initialization - TypeScript Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/core/README.md This snippet initializes the core application services within the background script of a Chrome extension. It calls `applicationInit` and logs a confirmation message upon successful initialization, ensuring background services are operational. ```typescript // chrome-extension/src/background/index.ts import { applicationInit } from '../content/src/core/main-initializer'; // Initialize core services in background context applicationInit().then(() => { console.log('Background services initialized'); }); ``` -------------------------------- ### Adapter Status Monitoring with React Hooks Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/hooks/README.md Enables monitoring of adapter events and their history. It provides utilities to get the count of events, clear the event log, and filter events specific to a particular adapter. ```typescript const { adapterEvents, eventCount, clearEvents, getEventsForAdapter } = useAdapterStatus(); ``` -------------------------------- ### TypeScript: Error Simulation for Testing Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/core/README.md Simulates errors for testing purposes, including forcing the circuit breaker open and handling simulated errors using `globalErrorHandler.handleError`. ```typescript // Force circuit breaker open for testing circuitBreaker.forceOpen(); // Simulate errors for testing recovery globalErrorHandler.handleError(new Error('Test error'), { component: 'test', operation: 'simulation', }); ``` -------------------------------- ### TypeScript: Automatic Initialization Timing Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/core/README.md Automatically times all initialization phases of the application. It retrieves performance statistics and logs the initialization time. ```typescript const stats = performanceMonitor.getStats(); console.log('Initialization time:', stats.measurements); ``` -------------------------------- ### Plugin System Integration with Site Adapters Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/components/README.md Illustrates how components adapt their behavior and styling based on the current site adapter provided by the plugin system. It fetches UI configuration from the adapter to apply theme and position. ```typescript import { useAdapter } from '../../hooks/useAdapter'; export function AdaptiveSidebar() { const { currentAdapter } = useAdapter(); // Get site-specific styling or behavior const sidebarConfig = currentAdapter?.getUIConfig?.() || defaultConfig; return ( ); } ``` -------------------------------- ### Application Store State and Actions Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/stores/README.md Manages global application-level state and lifecycle. Includes properties for initialization status, version, current site/host, settings, and errors. Actions allow initialization, updating site information, settings, and resetting state. ```typescript // State: // isInitialized: Application initialization status // version: Current application version // currentSite: Current website/hostname // currentHost: Current host domain // globalSettings: Global user preferences // initializationError: Initialization error state // Actions: // initialize(): Initialize application // setCurrentSite(site, host): Update current site // updateSettings(settings): Update global settings // resetState(): Reset to initial state ``` -------------------------------- ### Create Mock AppStore (TypeScript) Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/stores/README.md Illustrates the creation of a mock 'AppStore' for testing purposes. This mock store simulates the behavior of the actual store, including properties like `isInitialized` and `version`, and mocks functions like `initialize` using Jest. ```typescript // Create mock store for testing const mockAppStore = create(() => ({ isInitialized: true, version: '1.0.0', initialize: jest.fn() })); ``` -------------------------------- ### Plugin Context Creation (TypeScript) Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/plugins/README.md Demonstrates the creation of a plugin context using `createPluginContext`. The context object provides access to various essential resources and utilities, including Zustand stores, the event bus, helper functions, Chrome extension APIs, and structured logging. ```typescript const context = createPluginContext('my-adapter'); // Provides access to: // - context.stores (Zustand stores) // - context.eventBus (event communication) // - context.utils (helper functions) // - context.chrome (extension APIs) // - context.logger (structured logging) ``` -------------------------------- ### Selective State Subscription for Performance (TypeScript) Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/stores/README.md Highlights the performance benefit of subscribing to only specific state properties instead of the entire store. The example shows accessing `isVisible` directly, which is more performant than retrieving the whole store and then accessing the property. This reduces unnecessary re-renders. ```typescript // Good - only subscribes to specific state const isVisible = useUIStore(state => state.sidebar.isVisible); // Less optimal - subscribes to entire store const store = useUIStore(); const isVisible = store.sidebar.isVisible; ``` -------------------------------- ### Action Execution with Zustand Hook (TypeScript) Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/stores/README.md Illustrates how to call actions defined within a Zustand store to modify state. This example shows calling `setActiveAdapter` from `useAdapterStore` to change the application's active adapter. It assumes the existence of an `setActiveAdapter` action in the store. ```typescript import { useAdapterStore } from '@src/stores'; function AdapterControl() { const setActiveAdapter = useAdapterStore(state => state.setActiveAdapter); const activeAdapterName = useAdapterStore(state => state.activeAdapterName); const handleSwitch = async () => { await setActiveAdapter('DefaultAdapter'); }; return ( ); } ``` -------------------------------- ### Subscribe to Events using TypedEventBus in TypeScript Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/events/README.md Shows how to subscribe to specific events ('app:initialized', 'app:shutdown') or all events ('onWildcard') using the `eventBus`. It includes examples of using `on`, `once`, and `onWildcard`, and highlights the importance of unsubscribing using the returned `unsubscribe` function to prevent memory leaks. ```typescript import { eventBus } from './event-bus'; // Listen for a specific event const unsubscribeAppInit = eventBus.on('app:initialized', (data) => { console.log('App initialized:', data.version, data.timestamp); }); // Listen for an event only once eventBus.once('app:shutdown', (data) => { console.log('App shutdown reason:', data.reason); }); // Listen to all events (wildcard) const unsubscribeAll = eventBus.onWildcard((payload) => { console.log(`Event [${payload.event}] fired with data:`, payload.data); }); // Remember to unsubscribe when the listener is no longer needed // unsubscribeAppInit(); // unsubscribeAll(); ``` -------------------------------- ### TypeScript: Customizable Circuit Breaker Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/core/README.md Configures a circuit breaker with customizable thresholds for failure rate, reset timeout, and monitoring window. It instantiates `CircuitBreaker` with specific parameters. ```typescript const circuitBreaker = new CircuitBreaker({ failureThreshold: 5, resetTimeout: 60000, monitoringWindow: 300000, }); ``` -------------------------------- ### Configuring Tailwind CSS for UI Package Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/packages/ui/README.md Shows how to integrate the UI package's Tailwind CSS configuration with the project's `tailwind.config.ts` file. It uses the `withUI` utility from the UI package to extend the base configuration and include necessary content paths. ```ts import baseConfig from '@extension/tailwindcss-config'; import { withUI } from '@extension/ui'; export default withUI({ ...baseConfig, content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'], }); ``` -------------------------------- ### Plugin Development: Extending with Custom Adapters Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/README.md Demonstrates how to create a new site-specific adapter by extending the BaseAdapter class. It includes a method to check if the adapter can handle a given URL and an abstract method for inserting text, which must be implemented by the subclass. This pattern allows for easy extensibility of the MCP-SuperAssistant's site interaction capabilities. ```typescript export class CustomSiteAdapter extends BaseAdapter { canHandle(url: string): boolean { return url.includes('customsite.com'); } async insertText(text: string): Promise { // Site-specific implementation } } ``` -------------------------------- ### Create Custom Adapter Plugin (TypeScript) Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/plugins/README.md Demonstrates how to create a custom adapter by extending the BaseAdapterPlugin. This involves defining adapter properties like name, version, supported hostnames, and capabilities, along with implementing specific methods like `insertText` for site-specific interactions. ```typescript import { BaseAdapterPlugin } from '@src/plugins'; export class MySiteAdapter extends BaseAdapterPlugin { readonly name = 'MySiteAdapter'; readonly version = '1.0.0'; readonly hostnames = ['mysite.com']; readonly capabilities = ['text-insertion', 'form-submission']; async insertText(text: string): Promise { // Site-specific implementation return true; } // ... other methods } ``` -------------------------------- ### Use useEventBus Hook in React Component (TypeScript) Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/events/README.md Shows how to integrate the event system into a React component using the `useEventBus` hook. The hook provides `emit`, `on`, and `off` functions, allowing components to interact with the event bus. An example demonstrates subscribing to an event within a `useEffect` hook and cleaning up the subscription on unmount. ```typescript import { useEventBus } from '../hooks/useEventBus'; import { useEffect } from 'react'; function MyComponent() { const { emit, on, off } = useEventBus(); useEffect(() => { const unsubscribe = on('adapter:switched', (data) => { console.log('Adapter changed:', data.toAdapter); }); return unsubscribe; // Cleanup subscription on component unmount }, [on]); // Dependency array includes 'on' to ensure it's stable return ; } ``` -------------------------------- ### Initialize and Use McpClient for MCP Connections Source: https://context7.com/srbhptl39/mcp-superassistant/llms.txt Demonstrates how to initialize the McpClient class to establish connections with MCP servers, set up event listeners for connection and tool execution status, retrieve available primitives (tools, resources, prompts), execute tools, check connection health, and disconnect. It requires the McpClient class from './chrome-extension/src/mcpclient/core/McpClient'. ```typescript import { McpClient } from './chrome-extension/src/mcpclient/core/McpClient'; // Initialize with configuration const client = new McpClient({ defaultTransport: 'sse', defaultUri: 'http://localhost:3006/sse', plugins: { sse: { keepAlive: true, connectionTimeout: 5000, readTimeout: 30000 } }, global: { timeout: 30000, maxRetries: 3, healthCheckInterval: 60000, reconnectDelay: 2000, logLevel: 'info' } }); // Initialize the client await client.initialize(); // Set up event listeners client.on('client:connected', (event) => { console.log('Connected to:', event.uri, 'via', event.type); }); client.on('tool:call-completed', (event) => { console.log(`Tool ${event.toolName} completed in ${event.duration}ms`); }); // Connect to MCP server await client.connect({ uri: 'http://localhost:3006/sse', type: 'sse' }); // Get available tools, resources, and prompts const primitives = await client.getPrimitives(false); console.log('Available tools:', primitives.tools); // Execute a tool const result = await client.callTool('read_file', { path: '/path/to/file.txt' }); console.log('Tool result:', result); // Check connection health const isHealthy = await client.isHealthy(); console.log('Connection healthy:', isHealthy); // Disconnect await client.disconnect(); ``` -------------------------------- ### Event Communication: Type-Safe Event Emission and Handling Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/README.md Shows how to use the typed event bus for decoupled communication between different parts of the MCP-SuperAssistant. The example demonstrates emitting an event with specific data payload (`adapter:switched`) and setting up a listener for another event (`tool:executed`) to handle incoming data. This pattern ensures type safety and facilitates loose coupling. ```typescript eventBus.emit('adapter:switched', { adapterId: 'custom-adapter' }); eventBus.on('tool:executed', (data) => { /* handle */ }); ``` -------------------------------- ### Create MySiteAdapter TypeScript File Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/plugins/adapters/README.md Defines a custom adapter 'MySiteAdapter' inheriting from 'BaseAdapterPlugin'. It specifies hostnames, capabilities like text insertion and form submission, and implements methods for these actions. Includes initialization, activation, deactivation, and cleanup logic. ```typescript // my-site.adapter.ts import { BaseAdapterPlugin } from './base.adapter'; import type { AdapterCapability } from '../plugin-types'; export class MySiteAdapter extends BaseAdapterPlugin { readonly name = 'MySiteAdapter'; readonly version = '1.0.0'; readonly hostnames = ['my-site.com', 'www.my-site.com']; readonly capabilities: AdapterCapability[] = [ 'text-insertion', 'form-submission', 'url-navigation' ]; async insertText(text: string): Promise { // Site-specific text insertion logic const textArea = document.querySelector('.my-site-textarea'); if (textArea) { (textArea as HTMLTextAreaElement).value = text; return true; } return false; } async submitForm(): Promise { // Site-specific form submission logic const submitBtn = document.querySelector('.my-site-submit'); if (submitBtn) { (submitBtn as HTMLButtonElement).click(); return true; } return false; } protected async initializePlugin(): Promise { this.context.logger.info('Initializing MySiteAdapter...'); // Site-specific initialization } protected async activatePlugin(): Promise { this.context.logger.info('Activating MySiteAdapter...'); // Add site-specific event listeners } protected async deactivatePlugin(): Promise { this.context.logger.info('Deactivating MySiteAdapter...'); // Remove site-specific event listeners } protected async cleanupPlugin(): Promise { this.context.logger.info('Cleaning up MySiteAdapter...'); // Final cleanup } } ``` -------------------------------- ### Register MySiteAdapter in Plugin Registry Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/plugins/adapters/README.md Demonstrates how to register the 'MySiteAdapter' within the plugin registry. This involves importing the adapter and calling the 'register' method with adapter details and configuration, including its ID, name, description, version, and priority. ```typescript import { MySiteAdapter } from './adapters/my-site.adapter'; private async registerBuiltInAdapters(): Promise { // ... existing adapters await this.register(new MySiteAdapter(), { id: 'my-site-adapter', name: 'My Site Adapter', description: 'Specialized adapter for My Site', version: '1.0.0', enabled: true, priority: 10, // Higher priority than default settings: {} }); } ``` -------------------------------- ### Manage Initialization Status - TypeScript Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/core/README.md This snippet shows how to interact with initialization utilities provided by the main initializer. It includes functions to check the current initialization status and, in development environments, to force a re-initialization of the application. ```typescript import { initializationUtils } from './core/main-initializer'; // Check initialization status const status = initializationUtils.getStatus(); // Force re-initialization (development only) await initializationUtils.forceReinit(); ``` -------------------------------- ### Initialize and Connect MCP Client with TypeScript Configuration Source: https://context7.com/srbhptl39/mcp-superassistant/llms.txt Demonstrates how to define and use production and development configurations for initializing an McpClient. It includes setting up transport protocols (websocket, sse), plugin-specific options, global settings, and handling dynamic connections and transport switching. This code relies on 'McpClient' and type definitions from './chrome-extension/src/mcpclient/types/config'. ```typescript import { ClientConfig, ConnectionRequest } from './chrome-extension/src/mcpclient/types/config'; import { McpClient } from './chrome-extension/src/mcpclient/core/McpClient'; // Production configuration const productionConfig: ClientConfig = { defaultTransport: 'websocket', defaultUri: 'wss://api.example.com/mcp', plugins: { websocket: { protocols: ['mcp-v1', 'mcp-v2'], pingInterval: 60000, pongTimeout: 10000, maxReconnectAttempts: 5, binaryType: 'arraybuffer' }, sse: { keepAlive: true, connectionTimeout: 10000, readTimeout: 60000, headers: { 'Authorization': 'Bearer prod-token-xyz', 'X-API-Version': '2.0' } }, 'streamable-http': { keepAlive: true, connectionTimeout: 10000, readTimeout: 60000, fallbackToSSE: true, maxRetries: 3, headers: { 'Authorization': 'Bearer prod-token-xyz' } } }, global: { timeout: 60000, maxRetries: 5, healthCheckInterval: 30000, reconnectDelay: 5000, logLevel: 'warn' } }; // Development configuration const devConfig: ClientConfig = { defaultTransport: 'sse', defaultUri: 'http://localhost:3006/sse', plugins: { sse: { keepAlive: true, connectionTimeout: 5000, readTimeout: 30000 } }, global: { timeout: 30000, maxRetries: 3, healthCheckInterval: 60000, reconnectDelay: 2000, logLevel: 'debug' } }; // Initialize with environment-specific config const config = process.env.NODE_ENV === 'production' ? productionConfig : devConfig; const client = new McpClient(config); await client.initialize(); // Dynamic connection based on environment const connectionRequest: ConnectionRequest = { uri: config.defaultUri, type: config.defaultTransport, config: config.plugins[config.defaultTransport] }; await client.connect(connectionRequest); // Switch transport at runtime await client.switchTransport({ uri: 'ws://localhost:3006/message', type: 'websocket', config: { protocols: ['mcp-v1'], pingInterval: 30000 } }); ``` -------------------------------- ### Running Project Tests and Checks Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/README.md This bash snippet provides commands for managing the project's testing, type checking, and linting processes. It uses `pnpm` as the package manager for executing these development tasks. ```bash # Run tests (when implemented) pnpm test # Type checking pnpm type-check # Linting pnpm lint ``` -------------------------------- ### Registry Configuration Object (TypeScript) Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/plugins/README.md Defines the structure of a configuration object for a registry entry, including essential properties like ID, name, description, version, and enabled status. It also allows for custom settings, such as `logLevel`. ```typescript const config: AdapterConfig = { id: 'my-adapter', name: 'My Adapter', description: 'Description', version: '1.0.0', enabled: true, priority: 10, settings: { logLevel: 'info' } }; ``` -------------------------------- ### Test AppStore Initialization (TypeScript) Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/stores/README.md Demonstrates how to test the initialization logic of the 'AppStore' using Jest. It includes setting up the test environment, resetting the store's state before each test, and asserting that the store initializes correctly and sets the `isInitialized` flag. ```typescript import { useAppStore } from '@src/stores'; describe('AppStore', () => { beforeEach(() => { useAppStore.getState().resetState(); }); test('initializes correctly', async () => { const { initialize } = useAppStore.getState(); await initialize(); expect(useAppStore.getState().isInitialized).toBe(true); }); }); ``` -------------------------------- ### Integrate Plugin and Tool Events in TypeScript Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/events/README.md Illustrates emitting various events related to plugin registration, adapter switching, and tool execution. These events follow a naming convention (e.g., 'plugin:registered', 'tool:executed') and carry relevant payload data. This demonstrates the event bus's utility for inter-component communication. ```typescript // Plugin events eventBus.emit('plugin:registered', { pluginId: 'default-adapter', capabilities: ['insertText'] }); eventBus.emit('adapter:switched', { fromAdapter: 'default', toAdapter: 'gemini' }); // Tool execution events eventBus.emit('tool:executed', { toolId: 'file-reader', result: 'success' }); eventBus.emit('tool:error', { toolId: 'file-writer', error: 'Permission denied' }); ``` -------------------------------- ### Export MySiteAdapter from Index Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/plugins/adapters/README.md Shows how to export the 'MySiteAdapter' from the main plugin index file, making it available for import and use throughout the project. ```typescript export { MySiteAdapter } from './adapters/my-site.adapter'; ``` -------------------------------- ### Execute Operation with Circuit Breaker - TypeScript Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/core/README.md This code illustrates how to protect a potentially risky operation using the circuit breaker pattern. The `circuitBreaker.execute` method wraps the asynchronous operation, preventing cascading failures by monitoring its success and failure rates. ```typescript await circuitBreaker.execute(async () => { // Protected operation await riskyOperation(); }, 'operation-name'); ``` -------------------------------- ### TypeScript: Initialization Testing Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/core/README.md Tests the initialization status of the system by checking if it's initialized and verifying the error count. It uses `getInitializationStatus` and `expect` assertions. ```typescript // Test initialization status const status = getInitializationStatus(); expect(status.isInitialized).toBe(true); expect(status.errorCount).toBe(0); ``` -------------------------------- ### Importing Global CSS for UI Package Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/packages/ui/README.md Explains how to import the global CSS file provided by the UI package into the application's entry point (`index.tsx`). This ensures that the package's styles are applied correctly throughout the application. ```ts import '@extension/ui/lib/global.css'; ``` -------------------------------- ### Debugging Adapter Information Retrieval Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/plugins/adapters/README.md Provides JavaScript snippets to be executed in the browser console for debugging the plugin system. It shows how to retrieve debug information and the currently active plugin. ```javascript // In browser console window.__pluginSystem.getRegistry().getDebugInfo(); window.__pluginSystem.getRegistry().getActivePlugin(); ``` -------------------------------- ### Error Handling with Try-Catch and Logging Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/plugins/adapters/README.md Shows a robust error handling pattern using a try-catch block to gracefully manage potential errors during adapter logic execution and log them using the provided logger. ```typescript try { // Adapter logic return true; } catch (error) { this.context.logger.error('Operation failed:', error); return false; } ``` -------------------------------- ### TypeScript Configuration for Tailwind CSS with shadcn/ui Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/packages/ui/README.md This TypeScript function, `withUI`, merges shadcn/ui's default Tailwind CSS configuration with your project's existing configuration. It ensures proper integration of styles and component paths. ```typescript import deepmerge from 'deepmerge'; import type { Config } from 'tailwindcss'; import { fontFamily } from 'tailwindcss/defaultTheme'; import tailwindAnimate from 'tailwindcss-animate'; export function withUI(tailwindConfig: Config): Config { return deepmerge( shadcnConfig, deepmerge(tailwindConfig, { content: ['./node_modules/@extension/ui/lib/**/*.{tsx,ts,js,jsx}'], }), ); } const shadcnConfig = { darkMode: ['class'], theme: { container: { center: true, padding: '2rem', screens: { '2xl': '1400px', }, }, extend: { colors: { border: 'hsl(var(--border))', input: 'hsl(var(--input))', ring: 'hsl(var(--ring))', background: 'hsl(var(--background))', foreground: 'hsl(var(--foreground))', primary: { DEFAULT: 'hsl(var(--primary))', foreground: 'hsl(var(--primary-foreground))', }, secondary: { DEFAULT: 'hsl(var(--secondary))', foreground: 'hsl(var(--secondary-foreground))', }, destructive: { DEFAULT: 'hsl(var(--destructive))', foreground: 'hsl(var(--destructive-foreground))', }, muted: { DEFAULT: 'hsl(var(--muted))', foreground: 'hsl(var(--muted-foreground))', }, accent: { DEFAULT: 'hsl(var(--accent))', foreground: 'hsl(var(--accent-foreground))', }, popover: { DEFAULT: 'hsl(var(--popover))', foreground: 'hsl(var(--popover-foreground))', }, card: { DEFAULT: 'hsl(var(--card))', foreground: 'hsl(var(--card-foreground))', }, }, borderRadius: { lg: `var(--radius)`, md: `calc(var(--radius) - 2px)`, sm: 'calc(var(--radius) - 4px)', }, fontFamily: { sans: ['var(--font-sans)', ...fontFamily.sans], }, keyframes: { 'accordion-down': { from: { height: '0' }, to: { height: 'var(--radix-accordion-content-height)' }, }, 'accordion-up': { from: { height: 'var(--radix-accordion-content-height)' }, to: { height: '0' }, }, }, animation: { 'accordion-down': 'accordion-down 0.2s ease-out', 'accordion-up': 'accordion-up 0.2s ease-out', }, }, }, plugins: [tailwindAnimate], }; ``` -------------------------------- ### Define and Configure New Adapter (TypeScript) Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/plugins/adapters/README.md This snippet shows how to define a new adapter configuration object in TypeScript. It includes essential properties like id, name, description, version, and enabled status. The configuration can also include custom settings and priority. ```typescript export const myWebsiteAdapterConfig: AdapterConfig = { id: 'my-website-adapter', name: 'My Website Adapter', description: 'Adapter for specific interactions on my-website.com.', version: '1.0.0', enabled: true, priority: 10, // Higher priority (lower number) than DefaultAdapter settings: { /* ... */ }, }; ``` -------------------------------- ### Event Emission for Tool Execution Tracking Source: https://github.com/srbhptl39/mcp-superassistant/blob/main/pages/content/src/plugins/adapters/README.md Demonstrates how to emit a 'tool:execution-completed' event to track the execution of an adapter tool, including details about the execution, parameters, result, and timestamp. ```typescript this.context.eventBus.emit('tool:execution-completed', { execution: { id: this.generateId(), toolName: 'insertText', parameters: { text }, result: { success: true }, timestamp: Date.now(), status: 'success' } }); ```