UNPKG

signalk-mcp-server

Version:
429 lines 15.8 kB
import { Server } from '@modelcontextprotocol/sdk/server/index.js'; import { SignalKClient } from './signalk-client.js'; import type { MCPToolResponse } from './types/index.js'; export interface SignalKMCPServerOptions { serverName?: string; serverVersion?: string; signalkClient?: SignalKClient; /** * Execution mode for MCP server * - 'tools': Legacy tools-based approach (backward compatible, deprecated) * - 'code': Code execution mode with V8 isolates (default) * - 'hybrid': Both tools and code execution available (for migration only) */ executionMode?: 'tools' | 'code' | 'hybrid'; } /** * SignalK MCP Server - Provides AI agents with access to marine vessel data via Model Context Protocol * * This server bridges SignalK marine data systems with AI agents by exposing vessel navigation, * AIS targets, alarms, and sensor data through standardized MCP tools. It maintains a persistent * connection to a SignalK server and provides real-time access to marine data. * * Features: * - Real-time vessel state (position, heading, speed, wind) * - AIS target tracking (nearby vessels) * - System alarm monitoring * - Dynamic path discovery * - Connection status monitoring * - Graceful error handling with continued operation * * @example * // Basic usage * const server = new SignalKMCPServer({ * serverName: 'my-signalk-mcp', * serverVersion: '1.0.0' * }); * await server.run(); * * // With custom SignalK client * const client = new SignalKClient({ hostname: '192.168.1.100', port: 3000 }); * const server = new SignalKMCPServer({ signalkClient: client }); * await server.run(); */ export declare class SignalKMCPServer { private signalkClient; private server; private serverName; private serverVersion; private resources; private resourcesDir; private executionMode; private sandbox?; private binding?; private sdkCode?; /** * Creates a new SignalK MCP Server instance with configuration from options or environment variables * * Configuration priority: * 1. Constructor options * 2. Environment variables (SERVER_NAME, SERVER_VERSION) * 3. Default values * * Server capabilities: * - Registers 6 MCP tools for vessel data access * - Sets up error handling for SignalK connection failures * - Initiates asynchronous connection to SignalK server * - Continues operation even if SignalK is unavailable * * @param options - Server configuration options * @param options.serverName - MCP server identifier (default: 'signalk-mcp-server') * @param options.serverVersion - Version string (default: '1.0.0') * @param options.signalkClient - Custom SignalK client instance (optional) * * @example * // Default configuration * const server = new SignalKMCPServer(); * * // Custom configuration * const server = new SignalKMCPServer({ * serverName: 'my-boat-mcp', * serverVersion: '2.1.0' * }); * * // With environment variables * // SERVER_NAME=production-signalk-mcp * // SERVER_VERSION=1.5.0 * const server = new SignalKMCPServer(); */ constructor(options?: SignalKMCPServerOptions); /** * Loads resources from the filesystem */ loadResources(): Promise<void>; /** * Establishes connection to SignalK server with graceful error handling * * Connection behavior: * - Attempts to connect to SignalK server using client configuration * - Logs success/failure without throwing errors * - Allows MCP server to continue operating even if SignalK is unavailable * - Called automatically during server initialization * * @returns Promise that always resolves (never rejects) * * @example * // Manual reconnection attempt * await server.connectToSignalK(); * * // Connection is also attempted automatically during construction * const server = new SignalKMCPServer(); * // connectToSignalK() is called internally */ connectToSignalK(): Promise<void>; /** * Extract MCP tool definitions in the format expected by SDK generator * * @returns Array of MCPTool definitions */ /** * Returns tool definitions for SDK generation * * NOTE: Most legacy tools removed in favor of execute_code. * Only essential utility tools remain for debugging and documentation. */ private getToolDefinitions; /** * Registers MCP tool handlers and defines the available tools for AI agents * * Execution modes: * - 'tools': Only legacy tools (backward compatible) * - 'code': Only execute_code tool (new approach) * - 'hybrid': Both legacy tools and execute_code (default) * * Legacy tools: * - get_vessel_state: Current vessel navigation data * - get_ais_targets: Nearby vessels from AIS * - get_active_alarms: System notifications and alerts * - list_available_paths: Discover available SignalK data paths * - get_path_value: Get latest value for specific path * - get_connection_status: WebSocket connection health * - get_initial_context: Comprehensive SignalK documentation * * Code execution tool: * - execute_code: Execute JavaScript code in V8 isolate with SignalK SDK * * Handler features: * - JSON Schema validation for tool inputs * - Standardized error handling with MCP error codes * - Automatic request routing to appropriate methods * - Graceful error responses for tool execution failures * * @example * // Tools are registered automatically during construction * const server = new SignalKMCPServer(); * // setupToolHandlers() is called internally * * // AI agents can then call tools like: * // - get_vessel_state() * // - get_ais_targets() * // - get_path_value({"path": "navigation.position"}) * // - execute_code({"code": "const vessel = await getVesselState(); ..."}) */ setupToolHandlers(): void; /** * Sets up MCP resource handlers for listing and reading reference resources * * Provides reference resources: * - SignalK overview and documentation * - Data model reference * - Path categories guide * - MCP tool reference */ setupResourceHandlers(): void; /** * MCP tool handler that executes JavaScript code in a V8 isolate with SignalK SDK * * Execution environment: * - Secure V8 isolate (128MB memory limit, 30s timeout) * - SignalK SDK functions auto-injected * - No access to Node.js globals or filesystem * - Console.log captured and returned * * Available SDK functions: * - getVesselState() * - getAisTargets(options?) * - getActiveAlarms() * - listAvailablePaths() * - getPathValue(path) * - getConnectionStatus() * - getInitialContext() * * Code requirements: * - Must be wrapped in async IIFE: (async () => { ... })() * - Must return JSON.stringify() of result object * * @param code - JavaScript code to execute * @returns MCPToolResponse with execution result and logs * * @example * // Called by AI agents via MCP protocol: * // Tool: execute_code * // Arguments: { * // "code": "(async () => { const vessel = await getVesselState(); return JSON.stringify({ name: vessel.data.name?.value }); })()" * // } * * // Response content: * // { * // "success": true, * // "result": "{\"name\":\"My Boat\"}", * // "logs": ["Calling getVesselState..."], * // "executionTime": 45 * // } */ executeCode(code: string): Promise<MCPToolResponse>; /** * MCP tool handler that returns current vessel state with all available sensor data * * Response format: * - JSON text content with vessel navigation and sensor data * - Includes connection status, context, and timestamp * - Dynamic data structure based on available SignalK paths * - Formatted with 2-space indentation for readability * * @returns MCPToolResponse with vessel state as formatted JSON text */ getVesselState(): Promise<MCPToolResponse>; /** * MCP tool handler that returns nearby AIS targets (other vessels) with position and navigation data * * @param page - Page number (1-based, default: 1) * @param pageSize - Number of targets per page (default: 10, max: 50) * @returns MCPToolResponse with AIS targets as formatted JSON text */ getAISTargets(page?: number, pageSize?: number): Promise<MCPToolResponse>; /** * MCP tool handler that returns current active alarms and system notifications * * @returns MCPToolResponse with active alarms as formatted JSON text */ getActiveAlarms(): Promise<MCPToolResponse>; /** * MCP tool handler that discovers and returns all available SignalK data paths * * @returns MCPToolResponse with available paths as formatted JSON text */ listAvailablePaths(): Promise<MCPToolResponse>; /** * MCP tool handler that gets the latest value for a specific SignalK data path * * @param path - SignalK data path in dot notation (e.g., 'navigation.position') * @returns MCPToolResponse with path value as formatted JSON text */ getPathValue(path: string): Promise<MCPToolResponse>; /** * MCP tool handler that returns comprehensive SignalK connection status and health information * * Response format: * - JSON text content with detailed connection information * - WebSocket and HTTP URLs for debugging * - Server configuration details (hostname, port, TLS) * - Data cache statistics (paths, AIS targets, alarms) * - Current vessel context being monitored * * Status information includes: * - Connection state and server URLs * - Configuration parameters * - Data cache statistics * - Timestamp of status check * * @returns MCPToolResponse with connection status as formatted JSON text * * @example * // Called by AI agents via MCP protocol: * // Tool: get_connection_status * // Arguments: {} * * // Response content: * // { * // "connected": true, * // "url": "ws://localhost:3000", * // "wsUrl": "ws://localhost:3000", * // "httpUrl": "http://localhost:3000", * // "hostname": "localhost", * // "port": 3000, * // "useTLS": false, * // "context": "vessels.self", * // "pathCount": 25, * // "aisTargetCount": 3, * // "activeAlarmCount": 1, * // "timestamp": "2023-06-22T10:30:15.123Z" * // } */ getConnectionStatus(): MCPToolResponse; /** * MCP tool handler that returns comprehensive SignalK context and documentation * * This tool provides AI agents with essential context about: * - SignalK overview and core concepts * - Complete data model reference with path meanings * - Path categorization guide for understanding data organization * - MCP tool reference with usage patterns and examples * * Response format: * - JSON text content with all reference materials combined * - Structured sections for each type of documentation * - Comprehensive guide for AI agents to understand and utilize SignalK data * * Usage: * - Call this tool first to understand the SignalK system * - Use the returned context to make informed decisions about other tool calls * - Reference the path categories and data model when interpreting vessel data * * @returns MCPToolResponse with comprehensive SignalK context as formatted JSON text * * @example * // Called by AI agents via MCP protocol: * // Tool: get_initial_context * // Arguments: {} * * // Response content: * // { * // "signalk_overview": {...}, * // "data_model_reference": {...}, * // "path_categories_guide": {...}, * // "mcp_tool_reference": {...}, * // "server_info": { * // "name": "signalk-mcp-server", * // "version": "1.0.0", * // "loaded_at": "2023-06-22T10:30:15.123Z" * // } * // } */ getInitialContext(): MCPToolResponse; /** * Starts the MCP server and begins listening for requests via stdio transport * * Server startup: * - Establishes stdio transport for MCP communication * - Connects MCP server to transport layer * - Logs server startup information to stderr * - Begins processing MCP requests from AI agents * * Transport details: * - Uses stdio (stdin/stdout) for MCP protocol communication * - Stderr used for logging to avoid interfering with MCP protocol * - Server runs indefinitely until process termination * * @returns Promise that resolves when server is running * * @example * // Start the MCP server * const server = new SignalKMCPServer(); * await server.run(); * // Server is now running and accepting MCP requests * * // Server logs will appear on stderr: * // "signalk-mcp-server v1.0.0 running on stdio" */ run(): Promise<void>; /** * Gets the underlying MCP Server instance for testing and advanced usage * * Testing usage: * - Allows direct access to MCP server internals * - Enables testing of request handlers and server configuration * - Provides access to server capabilities and metadata * * @returns The MCP Server instance * * @example * // Testing server configuration * const server = new SignalKMCPServer(); * const mcpServer = server.mcpServer; * console.log('Server name:', mcpServer.name); * console.log('Server version:', mcpServer.version); * * // Testing tool handlers * const tools = await mcpServer.request({method: 'tools/list'}); * console.log('Available tools:', tools.tools.length); */ get mcpServer(): Server; /** * Gets the SignalK client instance for testing and direct access * * Testing usage: * - Allows direct access to SignalK client methods * - Enables testing of SignalK connection and data processing * - Provides access to cached vessel data and connection state * * @returns The SignalK client instance * * @example * // Testing SignalK connection * const server = new SignalKMCPServer(); * const client = server.signalkClientInstance; * console.log('Connected:', client.connected); * console.log('Available paths:', client.availablePaths.size); * * // Direct access to vessel data * const vesselState = client.getVesselState(); * console.log('Vessel data:', vesselState.data); * * // Testing event handling * client.on('delta', (delta) => { * console.log('Received delta:', delta); * }); */ get signalkClientInstance(): SignalKClient; /** * Cleans up resources when shutting down the server * * - Clears automatic update intervals * - Disconnects from SignalK server * - Releases any held resources * * @example * // Graceful shutdown * const server = new SignalKMCPServer(); * await server.run(); * * // On shutdown signal * process.on('SIGINT', async () => { * await server.cleanup(); * process.exit(0); * }); */ cleanup(): void; } //# sourceMappingURL=signalk-mcp-server.d.ts.map