### Installation, Configuration, and Server Start Commands Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/00-START-HERE.md Provides essential bash commands for installing the MCP server package, setting up environment variables for API keys, and starting the server. ```bash # Installation npm install @sinch-engage/mcp-server # Configuration export SINCH_ENGAGE_API_KEY="your-key" export SINCH_ENGAGE_API_SECRET="your-secret" # Start server node src/index.js # Run tests npm test ``` -------------------------------- ### Install Dependencies Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/README.md Navigate to the cloned repository directory and install the necessary Node.js dependencies using npm. ```bash cd sinch-engage-mcp-server npm install ``` -------------------------------- ### Start MCP Server Initialization Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/index.md This function initializes and starts the MCP server. It first validates essential configuration, then creates the server instance, loads tools from the API, registers them, and finally connects to the stdio transport to make the server operational. Errors during configuration validation will cause the process to exit. ```javascript async function startMCPServer() { console.error('Starting MCP server initialization...'); // 1. Validate configuration if (!config.isValid()) { console.error(' ERROR: MCP server startup failed. API_KEY and API_SECRET environment variables are required...'); console.error('Sample MCP server config: { "mcpServers": { ... } }'); process.exit(1); } // 2. Create MCP server server = new McpServer({ name: config.server.name, version: config.server.version, }); // 3. Load tools from API const tools = await waitForToolsToLoadOrFail(); // 4. Register tools with server await registerToolsWithServer(server, tools); // 5. Connect to stdio transport const transport = new StdioServerTransport(); await server.connect(transport); } ``` -------------------------------- ### Expected Startup Output Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/QUICK_START.md Example of the expected console output upon successful startup of the MCP server. ```text Starting MCP server initialization... [MCP server listening on stdio] ``` -------------------------------- ### Set API Credentials and Start Server Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/errors.md Set the required environment variables for API key and secret, then start the MCP server. This is necessary for the server to pull tools from the tool API. ```bash export SINCH_ENGAGE_API_KEY="your-api-key" export SINCH_ENGAGE_API_SECRET="your-api-secret" node src/index.js ``` -------------------------------- ### Install MCP Server Package Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/QUICK_START.md Install the MCP server package using npm. For development, clone the repository and install dependencies. ```bash npm install @sinch-engage/mcp-server ``` ```bash git clone https://github.com/messagemedia/sinch-engage-mcp-server.git cd sinch-engage-mcp-server npm install ``` -------------------------------- ### Start MCP Server for Development Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/QUICK_START.md Use the `npm run dev` command for development with auto-reloading capabilities. ```bash npm run dev ``` -------------------------------- ### Verify Installation with Test Credentials Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/QUICK_START.md Test the server startup with fake credentials to check for expected error messages. Use real credentials for successful startup. ```bash # Test with environment variables set SINCH_ENGAGE_API_KEY=test SINCH_ENGAGE_API_SECRET=test node src/index.js # Should fail with "Failed to load any tools from the API" (expected, creds are fake) # Or try with real credentials and it will start successfully ``` -------------------------------- ### Full Configuration Usage Example Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/config.md Demonstrates how to use the config module to validate credentials, create an authenticated Axios client, and fetch tools with filter parameters. ```javascript import config from './config.js'; // Check if credentials are set before starting the server if (!config.isValid()) { throw new Error('Missing SINCH_ENGAGE_API_KEY or SINCH_ENGAGE_API_SECRET'); } // Use platform URL in API client const axiosClient = axios.create({ baseURL: config.api.platformUrl, timeout: config.api.timeout, headers: { 'Authorization': config.getAuthHeader() } }); // Get filter query params for tool listing const filterParams = config.getFilterQueryParams(); const response = await axiosClient.get('/v1/mcp/tools', { params: filterParams }); ``` -------------------------------- ### MCP Tool API Request Example Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/endpoints.md Example of an HTTP GET request to retrieve MCP tool definitions, including query parameters for filtering and authentication headers. ```http GET /v1/mcp/tools?categories=reporting,contacts&modes=read,write HTTP/1.1 Host: api.messagemedia.com Content-Type: application/json Authorization: Basic dGVzdC1rZXk6dGVzdC1zZWNyZXQ= ``` -------------------------------- ### Example: String with Description Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/schema-converter.md Demonstrates how a 'description' field in the property schema is attached to the generated Zod type. ```javascript { type: 'string', description: 'User\'s email address' } // Produces: z.string().describe('User\'s email address') ``` -------------------------------- ### Start the Sinch Engage MCP Server Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/INDEX.md Export your API credentials and run the server script using Node.js. ```bash export SINCH_ENGAGE_API_KEY="your-key" export SINCH_ENGAGE_API_SECRET="your-secret" node src/index.js ``` -------------------------------- ### Set Required Environment Variables Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/INDEX.md Set these environment variables before starting the server to provide API credentials. ```bash SINCH_ENGAGE_API_KEY= SINCH_ENGAGE_API_SECRET= ``` -------------------------------- ### Run Tests with npm Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/INDEX.md Use these npm commands to execute tests or generate a coverage report. Ensure you have the project dependencies installed. ```bash npm test ``` ```bash npm run test:coverage ``` -------------------------------- ### Start MCP Server Directly Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/QUICK_START.md Run the MCP server directly using Node.js. Ensure environment variables are set. ```bash node src/index.js ``` -------------------------------- ### startMCPServer Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/index.md Initializes and starts the MCP server. This function performs configuration validation, creates the MCP server instance, loads and registers tools, and finally connects to the stdio transport to make the server operational. ```APIDOC ## startMCPServer() ### Description Initializes and starts the MCP server. ### Parameters None ### Returns Promise ### Execution Flow 1. **Validation:** Checks for required environment variables (`SINCH_ENGAGE_API_KEY`, `SINCH_ENGAGE_API_SECRET`). Exits if invalid. 2. **Server Creation:** Instantiates `McpServer` with name and version from configuration. 3. **Tool Loading:** Calls `waitForToolsToLoadOrFail()` to fetch tool definitions from the Sinch Engage API. 4. **Tool Registration:** Calls `registerToolsWithServer()` to register loaded tools with the server. 5. **Transport Connection:** Creates `StdioServerTransport` and connects it to the server. ### Error Handling - Configuration errors result in immediate process exit. - Tool loading errors are thrown and propagated. - Tool registration errors are logged but do not halt server startup. ### Request Example ```javascript async function startMCPServer() { console.error('Starting MCP server initialization...'); // 1. Validate configuration if (!config.isValid()) { console.error('\n\x1bERROR: MCP server startup failed. API_KEY and API_SECRET environment variables are required...'); console.error('Sample MCP server config: { "mcpServers": { ... } }'); process.exit(1); } // 2. Create MCP server server = new McpServer({ name: config.server.name, version: config.server.version, }); // 3. Load tools from API const tools = await waitForToolsToLoadOrFail(); // 4. Register tools with server await registerToolsWithServer(server, tools); // 5. Connect to stdio transport const transport = new StdioServerTransport(); await server.connect(transport); } ``` ``` -------------------------------- ### Tool Handler Example Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/tool-utils.md An example of a tool handler function that utilizes the `executeTool` function. MCP validates parameters against the Zod schema before calling the handler. ```javascript async function toolHandler(params) { return executeTool(toolDefinition, params); } ``` -------------------------------- ### Filter Tools by Category Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/INDEX.md Start the server with specific tool categories enabled using the MCP_TOOL_CATEGORIES environment variable. ```bash export MCP_TOOL_CATEGORIES="messaging,reporting" node src/index.js ``` -------------------------------- ### Executable Usage Examples Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/index.md Provides various methods for running the MCP server executable. This includes direct execution using the node interpreter, or using npx for package execution. ```bash #!/usr/bin/env node # Makes it runnable as: ./src/index.js # Or via node: node src/index.js # Or via npm package (when installed): npx @sinch-engage/mcp-server ``` -------------------------------- ### Example Full Error Log with Context Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/errors.md This log shows detailed context for an execution error, including the phase, tool name, and parameters, aiding in debugging. ```text [MCP Error] [executeTool] Error: Request failed with status code 401 Error: Request failed with status code 401 at createError (/project/node_modules/axios/lib/core/createError.js:16:16) at settle (/project/node_modules/axios/lib/core/settle.js:18:18) at IncomingMessage.handleStreamEnd (/project/node_modules/axios/lib/adapters/http.js:369:69) at IncomingMessage.emit (events.js:388:22) [MCP Error] [executeTool] Tool: sendMessage [MCP Error] [executeTool] Params: {"to":"+61400000000","body":"Hello"} ``` -------------------------------- ### GET Request Method Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/endpoints.md For GET requests, parameters are exclusively sourced from the query string or path parameters. No request body is expected. ```javascript method: 'GET' // No requestBodySchema expected // All parameters via parameter_locations: 'path' or 'query' ``` -------------------------------- ### Example of Invalid Filter Parameters Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/errors.md This example shows the format of an error message when invalid filter parameters are provided, such as unrecognized category or mode names. ```text INVALID_FILTER_PARAMETER: categories, modes ``` -------------------------------- ### Configure Faster Retries Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/configuration.md Adjust retry attempts and delay for tool loading failures. This example sets 5 retry attempts with a 500ms delay between them. ```bash MCP_MAX_RETRIES="5" MCP_RETRY_DELAY_MS="500" ``` -------------------------------- ### Custom Retry Configuration for Tool Loading Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/tool-spec-api.md Example of using waitForToolsToLoadOrFail with custom parameters for maximum retries and delay between retries. This allows fine-tuning the loading behavior. ```javascript try { const tools = await waitForToolsToLoadOrFail(5, 2000); // Max 5 retries, 2 seconds between retries console.log(`Loaded ${tools.length} tools`); } catch (error) { console.error('Failed to load tools:', error.message); process.exit(1); } ``` -------------------------------- ### Filter Tools by Mode Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/INDEX.md Start the server with tools restricted to a specific mode, such as read-only, using the MCP_TOOL_MODES environment variable. ```bash export MCP_TOOL_MODES="read" # Read-only tools node src/index.js ``` -------------------------------- ### Simple Error Logging Example Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/error-handler.md Logs a simple error with a specified phase. This is useful for tracking errors within a particular operational phase. ```javascript const error = new Error('Connection timeout'); handleError(error, { phase: 'toolExecution' }); // Logs: // [blank line] // [MCP Error] [toolExecution] Error: Connection timeout // Error: Connection timeout // at ...stack trace... // [blank line] ``` -------------------------------- ### Log Failed Tool Registration Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/errors.md These examples show the format of messages logged when a tool fails to register. Check these logs to identify which tools encountered issues. ```text Failed to register tool sendMessage: Schema validation failed ``` ```text Failed to register tool getReport: Invalid requestBodySchema ``` -------------------------------- ### Configure Tool Filters Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/QUICK_START.md Set environment variables to filter tool categories and modes, reducing token usage. Examples show filtering for messaging tools or read-only modes. ```bash # Only messaging tools export MCP_TOOL_CATEGORIES="messaging" # Only read-only tools export MCP_TOOL_MODES="read" # Reporting and contacts, read/write only export MCP_TOOL_CATEGORIES="reporting,contacts" export MCP_TOOL_MODES="read,write" ``` -------------------------------- ### Send SMS Message using executeTool Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/tool-utils.md Example of sending an SMS message using the `executeTool` function with a defined tool. The result is shown in the standard MCP response format. ```javascript // Example 1: Send SMS message const sendMsgTool = { name: 'sendMessage', method: 'POST', path: '/v1/messages', requestBodySchema: { type: 'object', properties: { to: { type: 'string' }, body: { type: 'string' } }, required: ['to', 'body'] } }; const result = await executeTool(sendMsgTool, { to: '+61400000000', body: 'Hello, this is a test' }); // result: // { // content: [ // { type: 'text', text: '{"message_id":"m-12345","status":"submitted"}' } // ] // } ``` -------------------------------- ### 429 Too Many Requests Typical Response Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/endpoints.md Example of a 429 Too Many Requests error response, including the `retry_after` field to guide clients on when to retry. ```javascript { error: "RATE_LIMITED", message: "Too many requests", retry_after: 60 } ``` -------------------------------- ### Typical MCP Server Startup Sequence Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/index.md Illustrates the expected output during a typical startup sequence of the MCP server. This includes initialization messages, tool loading status, and confirmation of the server listening on stdio. ```shell $ node src/index.js Starting MCP server initialization... [Loaded 24 tools from API] [Tool registration: sendMessage... ok] [Tool registration: getDetailedMessageReport... ok] ... [Server listening on stdio] ``` -------------------------------- ### Server Integration with Tool Loading Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/tool-spec-api.md Shows how to import and use the `waitForToolsToLoadOrFail` function from the `tool-spec-api.js` module to ensure tools are loaded before server initialization. ```javascript import { waitForToolsToLoadOrFail } from './tool-spec-api.js'; async function startMCPServer() { const tools = await waitForToolsToLoadOrFail(); await registerToolsWithServer(server, tools); // ... } ``` -------------------------------- ### Get Specific Contact Endpoint Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/endpoints.md Retrieve a specific contact by its ID. This endpoint is part of the Contacts category. ```http GET /v1/contacts/{id} ``` -------------------------------- ### EU Region Configuration with All Tools Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/configuration.md Configures the server for the EU region, enabling all available tools. ```bash export SINCH_ENGAGE_API_KEY="your-api-key" export SINCH_ENGAGE_API_SECRET="your-api-secret" export SINCH_ENGAGE_REGION="EU" ``` -------------------------------- ### Get Specific Report Endpoint Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/endpoints.md Retrieve a specific report by its ID. This endpoint is part of the Reporting category. ```http GET /v1/reports/{report_id} ``` -------------------------------- ### Handle Server Initialization Failures Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/error-handler.md Use `handleError` to log errors during server startup. Ensure the process exits if initialization fails. ```javascript startMCPServer().catch((error) => { handleError(error, { phase: 'startMCPServer' }); process.exit(1); }); ``` -------------------------------- ### Unhandled Startup Exception Format Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/errors.md This shows the format of an error message for an unhandled exception during server initialization. It includes the error type, message, and the phase where the error occurred. ```text [MCP Error] [startMCPServer] : ``` -------------------------------- ### 401 Unauthorized Typical Response Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/endpoints.md Example of a 401 Unauthorized error response, which occurs when API credentials are invalid, expired, or missing. ```javascript { error: "UNAUTHORIZED", message: "Invalid API credentials" } ``` -------------------------------- ### Integration with Index Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/tool-spec-api.md Illustrates how the tool specification module is integrated into the main server, specifically how tools are loaded before server startup. ```APIDOC ## Integration with Index The main server (`src/index.js`) uses this module: ```javascript import { waitForToolsToLoadOrFail } from './tool-spec-api.js'; async function startMCPServer() { const tools = await waitForToolsToLoadOrFail(); await registerToolsWithServer(server, tools); // ... } ``` Tools are loaded before any other setup occurs, ensuring the server has a complete tool list before connecting to the MCP transport. ``` -------------------------------- ### MCP Tool API Error Response (Unauthorized) Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/endpoints.md Example of a JSON response indicating an authentication failure due to invalid credentials. ```javascript { error: "UNAUTHORIZED", message: "Authentication failed" } ``` -------------------------------- ### Import Configuration Module Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/configuration.md Import the configuration module to load settings. Configuration is read from environment variables at this point and cached. ```javascript import config from './config.js'; // Configuration is read from environment at this point ``` -------------------------------- ### Register Tools with Server Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/tool-registration.md Iterates through tool definitions, creates tool registrations, and registers them with the server. Handles and logs errors during the registration process. ```javascript import { createToolRegistration } from './tool-registration.js'; async function registerToolsWithServer(server, toolDefinitions) { const results = { registered: [], failed: [] }; for (const toolDefinition of toolDefinitions) { try { const registration = createToolRegistration(toolDefinition); server.tool( registration.name, registration.description, registration.schema, registration.handler ); results.registered.push(registration.name); } catch (error) { console.error(`Failed to register tool`, error.message); results.failed.push({ name: toolDefinition.name, error: error.message }); } } return results; } ``` -------------------------------- ### MCP Tool API Error Response (Bad Request) Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/endpoints.md Example of a JSON response indicating a bad request due to invalid filter parameters. ```javascript { error: "INVALID_FILTER_PARAMETER", message: "Invalid filter parameters", invalid_parameters: ["categories", "modes"] } ``` -------------------------------- ### Configure MCP Server in Claude Desktop (Local Build) Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/README.md Configure Claude Desktop to use your locally built MCP server by specifying the command to run the Node.js script. Update the path to the `index.js` file and fill in your credentials and region. ```json { "mcpServers": { "Sinch Engage": { "command": "node", "args": ["/path/to/sinch-engage-mcp-server/src/index.js"], "env": { "SINCH_ENGAGE_API_KEY": "", "SINCH_ENGAGE_API_SECRET": "", "SINCH_ENGAGE_REGION": "", "MCP_TOOL_CATEGORIES": "reporting, contacts, messaging", "MCP_TOOL_MODES": "read, write, delete" } } } } ``` -------------------------------- ### MCP Tool API Success Response Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/endpoints.md Example of a successful JSON response from the MCP Tool API, detailing available tool definitions with their properties. ```javascript { resources: [ { name: "sendMessage", id: "send-message-1", description: "Send SMS to a mobile number", method: "POST", path: "/v1/messages", category: "messaging", mode: "write", requestBodySchema: { type: "object", properties: { to: { type: "string" }, body: { type: "string" } }, required: ["to", "body"] }, parameter_locations: { to: "body", body: "body" } }, // ... more tool definitions ] } ``` -------------------------------- ### Environment Variables Reference Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/QUICK_START.md Reference for all available environment variables, including required API credentials and optional configuration for region, tool filters, server name, and retry settings. ```bash # Required SINCH_ENGAGE_API_KEY= SINCH_ENGAGE_API_SECRET= # Optional SINCH_ENGAGE_REGION=AU # Default: AU MCP_TOOL_CATEGORIES=reporting,contacts # Default: all MCP_TOOL_MODES=read,write # Default: all MCP_TOOL_EXCLUDE_MODES=delete # Default: none MCP_SERVER_NAME="My MCP Server" # Default: Sinch MessageMedia MCP Server MCP_SERVER_VERSION=1.0.0 # Default: 0.4.0 MCP_MAX_RETRIES=5 # Default: 3 MCP_RETRY_DELAY_MS=2000 # Default: 3000 (3 seconds) ``` -------------------------------- ### Run Tests Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/QUICK_START.md Execute the test suite or generate code coverage reports using npm commands. ```bash npm test # Run tests npm run test:coverage # Generate coverage ``` -------------------------------- ### Configure Optional Environment Variables Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/INDEX.md Customize server behavior by setting optional environment variables. Defaults are provided for most. ```bash SINCH_ENGAGE_REGION=AU|EU # Default: AU MCP_TOOL_CATEGORIES= # Default: all MCP_TOOL_MODES=read|write|delete # Default: all MCP_TOOL_EXCLUDE_MODES= # Default: none MCP_SERVER_NAME= # Default: Sinch MessageMedia MCP Server MCP_SERVER_VERSION= # Default: 0.4.0 MCP_MAX_RETRIES= # Default: 3 MCP_RETRY_DELAY_MS= # Default: 3000 ``` -------------------------------- ### Generated HTTP Request for getDetailedMessageReport Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/endpoints.md This shows the generated HTTP GET request for retrieving a detailed message report. It includes path parameter substitution and a query parameter for filtering. ```http GET /v1/reports/rpt-9876543/details?limit=100 HTTP/1.1 Host: api.messagemedia.com Accept: application/json Authorization: Basic ``` -------------------------------- ### Import MCP SDK Server Components Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/index.md Import the necessary classes for the MCP server and Stdio transport. Ensure these are included at the beginning of your server file. ```javascript import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; ``` -------------------------------- ### Configure MCP Server in Claude Desktop (NPM) Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/README.md Add this configuration to your Claude Desktop's `claude_desktop_config.json` file to run the MCP server as an NPM package. Ensure you replace placeholders with your actual credentials and desired region. ```json { "mcpServers": { "Sinch Engage": { "command": "npx", "args": [ "-y", "@sinch-engage/mcp-server" ], "env": { "SINCH_ENGAGE_API_KEY": "", "SINCH_ENGAGE_API_SECRET": "", "SINCH_ENGAGE_REGION": "", "MCP_TOOL_CATEGORIES": "reporting, contacts, messaging", "MCP_TOOL_MODES": "read, write, delete" } } } } ``` -------------------------------- ### Execute Tool with Raw Response and JSON Parsing Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/tool-utils.md Demonstrates executing a tool with `formatResponse` set to false and `parseStringAsJson` set to true. Errors are thrown directly, not wrapped in MCP format. ```javascript // Example 2: Get report with internal error handling const rawData = await executeTool(reportTool, params, { formatResponse: false, parseStringAsJson: true }); // Errors thrown directly, not wrapped in MCP format ``` -------------------------------- ### Configure Claude Desktop Integration Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/QUICK_START.md Edit the `claude_desktop_config.json` file to integrate the MCP server with Claude Desktop. Specify command, arguments, and environment variables. ```json { "mcpServers": { "Sinch Engage": { "command": "npx", "args": ["-y", "@sinch-engage/mcp-server"], "env": { "SINCH_ENGAGE_API_KEY": "", "SINCH_ENGAGE_API_SECRET": "", "SINCH_ENGAGE_REGION": "AU" } } } } ``` -------------------------------- ### Tool Definition for getDetailedMessageReport Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/endpoints.md This JavaScript object defines the 'getDetailedMessageReport' tool, specifying its HTTP GET method, path with a path parameter, and query parameter. It's used to retrieve detailed message reports. ```javascript { name: "getDetailedMessageReport", method: "GET", path: "/v1/reports/{report_id}/details", parameter_locations: { report_id: "path", limit: "query" }, requestBodySchema: { type: "object", properties: { limit: { type: "integer" } } } } ``` -------------------------------- ### Clone the MCP Server Repository Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/README.md Clone the Sinch Engage MCP Server repository to your local machine. This is the first step for local development and testing. ```bash git clone https://github.com/messagemedia/sinch-engage-mcp-server.git ``` -------------------------------- ### Claude Desktop Configuration Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/configuration.md JSON configuration for integrating the MCP server with Claude Desktop, specifying command, arguments, and environment variables. ```json { "mcpServers": { "Sinch Engage": { "command": "npx", "args": ["-y", "@sinch-engage/mcp-server"], "env": { "SINCH_ENGAGE_API_KEY": "your-api-key", "SINCH_ENGAGE_API_SECRET": "your-api-secret", "SINCH_ENGAGE_REGION": "AU", "MCP_TOOL_CATEGORIES": "reporting,contacts,messaging", "MCP_TOOL_MODES": "read,write,delete" } } } } ``` -------------------------------- ### waitForToolsToLoadOrFail(maxRetries?, delayMs?) Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/tool-spec-api.md Repeatedly attempts to load tool definitions from the API with exponential backoff until success or max retries are exceeded. Useful for ensuring tools are available before proceeding. ```APIDOC ## waitForToolsToLoadOrFail(maxRetries?, delayMs?) ### Description Repeatedly attempts to load tool definitions from the API with exponential backoff until success or max retries are exceeded. Useful for ensuring tools are available before proceeding. ### Parameters #### Path Parameters None. #### Query Parameters None. #### Request Body None. #### Optional Parameters - **maxRetries** (number) - Optional - Maximum number of retry attempts. Defaults to `config.retries.max` (typically 3). - **delayMs** (number) - Optional - Delay in milliseconds between retries. Defaults to `config.retries.delayMs` (typically 3000). ### Method GET (internally calls `listResources()`) ### Endpoint (Internally calls `/v1/mcp/tools`) ### Request Example ```javascript import { waitForToolsToLoadOrFail } from './tool-spec-api.js'; try { const tools = await waitForToolsToLoadOrFail(5, 2000); console.log(`Loaded ${tools.length} tools`); } catch (error) { console.error('Failed to load tools:', error.message); process.exit(1); } ``` ### Response #### Success Response (200) - **ToolDefinition[]** - An array of tool definitions. Resolves immediately on first successful fetch with non-empty results. #### Response Example ```json [ { "name": "sendMessage", "description": "...", ... }, { "name": "getDetailedMessageReport", ... }, ... ] ``` ### Behavior 1. Calls `listResources()` immediately. 2. If tools are returned (length > 0), resolves with the tools array. 3. If no tools or an error occurs, logs a retry message and waits `delayMs` before retrying, up to `maxRetries` times. 4. If all retries are exhausted without success, throws an error. ### Throws - `Error('Failed to load any tools from the API after multiple attempts.')` if no tools are loaded after all retries. ### Logging - Retry attempts are logged to stderr, e.g., "No tools loaded, retrying (1/3)..." - Errors are handled via `handleError()` with phase `'waitForToolsToLoadOrFail'`. ``` -------------------------------- ### Configure API Credentials Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/QUICK_START.md Set the required Sinch Engage API key and secret as environment variables. Obtain credentials from the Sinch Engage Hub. ```bash export SINCH_ENGAGE_API_KEY="your-api-key" export SINCH_ENGAGE_API_SECRET="your-api-secret" ``` -------------------------------- ### Local Development Configuration Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/configuration.md JSON configuration for running the MCP server locally from a cloned repository, specifying the Node.js command and script path. ```json { "mcpServers": { "Sinch Engage": { "command": "node", "args": ["/path/to/sinch-engage-mcp-server/src/index.js"], "env": { "SINCH_ENGAGE_API_KEY": "your-api-key", "SINCH_ENGAGE_API_SECRET": "your-api-secret", "SINCH_ENGAGE_REGION": "AU", "MCP_TOOL_CATEGORIES": "reporting,contacts,messaging", "MCP_TOOL_MODES": "read,write,delete" } } } } ``` -------------------------------- ### Custom Server Info and Aggressive Retries Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/configuration.md Sets custom server name and version, and configures aggressive retry behavior with a 1-second delay between retries. ```bash export SINCH_ENGAGE_API_KEY="your-api-key" export SINCH_ENGAGE_API_SECRET="your-api-secret" export MCP_SERVER_NAME="My Custom MCP Server" export MCP_SERVER_VERSION="1.0.0" export MCP_MAX_RETRIES="10" export MCP_RETRY_DELAY_MS="1000" ``` -------------------------------- ### Register Tools with MCP Server Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/index.md Use this function to register tool definitions with the MCP server. It iterates through provided definitions, attempts to create registrations, and handles both successful registrations and failures, logging errors and continuing with the next tool. ```javascript async function registerToolsWithServer(server, toolDefinitions) { const results = { registered: [], failed: [] }; for (const toolDefinition of toolDefinitions) { try { const registration = createToolRegistration(toolDefinition); server.tool( registration.name, registration.description, registration.schema, registration.handler ); results.registered.push(registration.name); } catch (error) { const toolName = toolDefinition.name || toolDefinition.id || 'unknown'; console.error(`Failed to register tool ${toolName}:`, error.message); results.failed.push({ name: toolName, error: error.message }); handleError(error, { phase: 'registerToolsWithServer', toolDefinition }); } } registeredTools = results.registered; return results; } ``` -------------------------------- ### Configure Claude Desktop Integration Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/INDEX.md Edit the `claude_desktop_config.json` file to integrate the Sinch Engage MCP Server. Ensure API keys, secrets, and region are correctly set within the `env` block. ```json { "mcpServers": { "Sinch Engage": { "command": "npx", "args": ["-y", "@sinch-engage/mcp-server"], "env": { "SINCH_ENGAGE_API_KEY": "...", "SINCH_ENGAGE_API_SECRET": "...", "SINCH_ENGAGE_REGION": "AU" } } } } ``` -------------------------------- ### listResources() Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/tool-spec-api.md Fetches the list of available MCP tool definitions from the remote API. It automatically includes tool category and mode filters from configuration. ```APIDOC ## listResources() ### Description Fetches the list of available MCP tool definitions from the remote API. It automatically includes tool category and mode filters from configuration. ### Method GET ### Endpoint /v1/mcp/tools ### Parameters #### Query Parameters - **categories** (string) - Optional - Tool categories to filter by (from config). - **modes** (string) - Optional - Tool modes to filter by (from config). ### Request Example ```javascript import { listResources } from './tool-spec-api.js'; const response = await listResources(); console.log(response.resources); ``` ### Response #### Success Response (200) - **resources** (ToolDefinition[]) - An array of tool definitions. #### Response Example ```json { "resources": [ { "name": "sendMessage", "description": "...", ... }, { "name": "getDetailedMessageReport", ... }, ... ] } ``` ### Throws - `Error` if HTTP request fails. - Special handling for 400 errors with `INVALID_FILTER_PARAMETER` — error message includes invalid parameter names. ### Error Example ```javascript try { await listResources(); } catch (error) { // error.message might be: "INVALID_FILTER_PARAMETER: categories, modes" } ``` ``` -------------------------------- ### HTTP Method Handling Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/endpoints.md Details on how each HTTP method is processed, including where parameters are expected. ```APIDOC ## GET Requests ### Description GET requests do not have a request body. Parameters are supplied via query string and path parameters. ### Method GET ### Parameters #### Path Parameters Parameters are specified in the `parameter_locations` object with the value 'path'. #### Query Parameters Parameters are specified in the `parameter_locations` object with the value 'query'. ### Request Example No request body is expected. ### Response Details on response structure are not provided in this section. ``` ```APIDOC ## POST Requests ### Description POST requests can include parameters in the request body, and optionally in path or query parameters. ### Method POST ### Parameters #### Path Parameters Parameters are specified in the `parameter_locations` object with the value 'path'. #### Query Parameters Parameters are specified in the `parameter_locations` object with the value 'query'. #### Request Body Parameters are specified in the `parameter_locations` object with the value 'body'. The `requestBodySchema` is used for these parameters. ### Request Example ```json { "example": "request body" } ``` ### Response Details on response structure are not provided in this section. ``` ```APIDOC ## PUT Requests ### Description PUT requests are typically used for updates and expect parameters in the request body. A path parameter is often used to identify the resource. ### Method PUT ### Parameters #### Path Parameters Parameters are specified in the `parameter_locations` object with the value 'path'. Often used for resource identification. #### Request Body Parameters are specified in the `parameter_locations` object with the value 'body'. The `requestBodySchema` is used for these parameters. ### Request Example ```json { "example": "request body" } ``` ### Response Details on response structure are not provided in this section. ``` ```APIDOC ## DELETE Requests ### Description DELETE requests usually do not have a request body and typically use a path parameter to identify the resource to be deleted. ### Method DELETE ### Parameters #### Path Parameters Parameters are specified in the `parameter_locations` object with the value 'path'. Usually used for resource identification. ### Request Example No request body is expected. ### Response Details on response structure are not provided in this section. ``` ```APIDOC ## PATCH Requests ### Description PATCH requests are used for partial updates and are similar to PUT requests, expecting parameters in the request body. A path parameter is often used to identify the resource. ### Method PATCH ### Parameters #### Path Parameters Parameters are specified in the `parameter_locations` object with the value 'path'. Often used for resource identification. #### Request Body Parameters are specified in the `parameter_locations` object with the value 'body'. The `requestBodySchema` is used for these parameters. ### Request Example ```json { "example": "request body" } ``` ### Response Details on response structure are not provided in this section. ``` -------------------------------- ### Minimal Configuration (AU Region) Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/configuration.md Sets the API key and secret for the AU region. Other variables will use their default values. ```bash export SINCH_ENGAGE_API_KEY="your-api-key" export SINCH_ENGAGE_API_SECRET="your-api-secret" # All other variables use defaults ``` -------------------------------- ### Handle Tool Loading Failures Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/error-handler.md Log errors that occur while loading tools, including retry information if applicable. This ensures visibility into tool loading issues. ```javascript try { const response = await listResources(); } catch (error) { handleError(error, { phase: 'waitForToolsToLoadOrFail', retry: retries }); } ``` -------------------------------- ### Handle Tool Registration Failures Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/error-handler.md Catch errors during the tool registration loop and log them with the appropriate phase and tool definition. ```javascript for (const toolDefinition of toolDefinitions) { try { const registration = createToolRegistration(toolDefinition); // ... register tool } catch (error) { handleError(error, { phase: 'registerToolsWithServer', toolDefinition }); } } ``` -------------------------------- ### createToolRegistration(toolDefinition) Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/tool-registration.md Converts a tool definition from the Sinch Engage API into an MCP tool registration object. This includes schema conversion and handler creation. ```APIDOC ## createToolRegistration(toolDefinition) ### Description Converts a tool definition from the Sinch Engage API into an MCP tool registration object. It handles schema conversion, validation, and creates executable tool handlers. ### Method JavaScript Function ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **toolDefinition** (object) - Required - Tool definition from Sinch Engage API. Expected fields include `name`, `description`, `requestBodySchema` or `parameters`. ### Returns - **registration** (object) - An MCP-compatible tool registration object containing `name`, `description`, `schema` (Zod schema), and `handler` (async function). ### Request Example ```javascript import { createToolRegistration } from './tool-registration.js'; const toolDefinition = { name: 'sendMessage', description: 'Send SMS to a mobile number', method: 'POST', path: '/v1/messages', requestBodySchema: { type: 'object', properties: { to: { type: 'string' }, body: { type: 'string' } }, required: ['to', 'body'] } }; const registration = createToolRegistration(toolDefinition); console.log(registration); ``` ### Response #### Success Response - **registration** (object) - An object with the following properties: - `name` (string): Tool name from `toolDefinition`. - `description` (string): Tool description from `toolDefinition`. - `schema` (ZodShape): Zod schema object for parameter validation. - `handler` (async function): Async function that executes the tool. #### Response Example ```json { "name": "sendMessage", "description": "Send SMS to a mobile number", "schema": { /* Zod schema object */ }, "handler": async (params) => { /* ... */ } } ``` ``` -------------------------------- ### Schema Conversion Workflow Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/schema-converter.md Illustrates the step-by-step process from an API tool definition's JSON Schema to a Zod object used for validation in MCP tool handlers. ```plaintext API Tool Definition ↓ requestBodySchema (JSON Schema) ↓ normalizeSchema(schema) ↓ [Ensure type, properties, required exist] ↓ convertToZodSchema(normalized) ↓ For each property: ├─ createZodType(property) ├─ Apply .describe(description) if present └─ Apply .optional() if not in required ↓ zodShape: { propertyName: ZodType, ... } ↓ MCP tool handler uses z.object(zodShape) for validation ``` -------------------------------- ### MCP Server Registration Results Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/index.md The result object returned by `registerToolsWithServer` indicates which tools were successfully registered and which failed, along with error messages for the failures. ```javascript { registered: string[], // Names of successfully registered tools failed: Array<{ // Tools that failed to register name: string, error: string }> } ``` -------------------------------- ### Validate Configuration with config.isValid() Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/config.md Check if required API credentials (username and password) are set in the configuration. Exits the process if credentials are missing. ```javascript import config from './config.js'; if (!config.isValid()) { console.error('Missing API_KEY or API_SECRET'); process.exit(1); } ``` -------------------------------- ### Wait for Tools to Load with Retries Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/tool-spec-api.md Repeatedly attempts to load tool definitions from the API with exponential backoff until success or max retries exceeded. Use this when initial tool loading might be delayed. ```javascript import { waitForToolsToLoadOrFail } from './tool-spec-api.js'; const tools = await waitForToolsToLoadOrFail(); // Returns immediately on first success // Retries with delay if no tools loaded // Throws if all retries exhausted ``` -------------------------------- ### Handle Tool Execution Errors in Client Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/errors.md This JavaScript code demonstrates how to handle potential errors when executing a tool. It includes checks for both formatted tool errors and unexpected exceptions. ```javascript try { const result = await executeTool(toolDef, params); if (result.error) { console.error('Tool error:', result.error.message); console.error('Status:', result.content[1].text); console.error('Response:', result.content[2].text); } } catch (error) { // Unformatted error (only if formatResponse: false) console.error('Unexpected error:', error.message); } ``` -------------------------------- ### registerToolsWithServer Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/index.md Registers tool definitions with the MCP server. This function iterates through provided tool definitions, converts them into a format suitable for the MCP server, and registers them. It tracks successful registrations and any failures, allowing for partial registration if some tools encounter errors. ```APIDOC ## registerToolsWithServer(server, toolDefinitions) ### Description Registers tool definitions with the MCP server. ### Parameters #### Path Parameters - `server` (McpServer) - MCP server instance - `toolDefinitions` (array) - Tool definitions from API ### Returns Promise - Resolves to an object containing `registered` (array of strings) and `failed` (array of objects with `name` and `error` properties). ### Request Example ```javascript async function registerToolsWithServer(server, toolDefinitions) { const results = { registered: [], failed: [] }; for (const toolDefinition of toolDefinitions) { try { const registration = createToolRegistration(toolDefinition); server.tool( registration.name, registration.description, registration.schema, registration.handler ); results.registered.push(registration.name); } catch (error) { const toolName = toolDefinition.name || toolDefinition.id || 'unknown'; console.error(`Failed to register tool ${toolName}:`, error.message); results.failed.push({ name: toolName, error: error.message }); handleError(error, { phase: 'registerToolsWithServer', toolDefinition }); } } registeredTools = results.registered; return results; } ``` ### Response #### Success Response (200) - `registered` (string[]) - Names of successfully registered tools - `failed` (Array<{ name: string, error: string }>) ### Response Example ```json { "registered": ["tool1", "tool2"], "failed": [ { "name": "tool3", "error": "Schema validation failed" } ] } ``` ``` -------------------------------- ### Construct Tool Filter Query Parameters with config.getFilterQueryParams() Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/config.md Constructs query parameters for tool filtering API requests based on configured categories and modes. Only includes parameters with non-empty values. ```javascript const params = config.getFilterQueryParams(); // Returns: { categories: 'reporting,contacts', modes: 'read,write' } ``` -------------------------------- ### Execute Tool with Standard MCP Response Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/tool-utils.md Executes a tool and formats the response into the standard MCP content array. This is the default behavior. ```javascript import { executeTool } from './tool-utils.js'; const toolDef = { /* ... */ }; const params = { to: '+61400000000', body: 'Hello' }; // Standard MCP response format const result = await executeTool(toolDef, params); // { // content: [ // { type: 'text', text: '{"message_id":"m-123",...}' } // ] // } ``` -------------------------------- ### JavaScript: Create Tool Schema with Schema Converter Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/schema-converter.md Integrates schema conversion into the tool registration process. This function takes a tool definition, normalizes its schema, and converts it into a Zod schema for parameter validation. ```javascript import { convertToZodSchema, normalizeSchema } from './schema-converter.js'; function createToolSchema(toolDefinition) { const parameters = toolDefinition.requestBodySchema || toolDefinition.parameters || {}; const normalizedSchema = normalizeSchema(parameters); return convertToZodSchema(normalizedSchema); } ``` -------------------------------- ### HTTP Client Configuration Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/tool-spec-api.md Details the configuration of the HTTP client used for making requests, including base URL, timeout, and default headers. ```APIDOC ## HTTP Client Details The module creates an axios client with: - **Base URL:** `config.api.platformUrl` - **Timeout:** `config.api.timeout` (10 seconds) - **Default Headers:** - `Content-Type: application/json` - `Authorization: Basic ` The axios instance is created once at module load time and reused for all requests. ``` -------------------------------- ### Generate Basic Auth Header with config.getAuthHeader() Source: https://github.com/messagemedia/sinch-engage-mcp-server/blob/main/_autodocs/api-reference/config.md Generates the Basic Authentication header string required for authenticating API requests. Used by HTTP clients. ```javascript const authHeader = config.getAuthHeader(); // Returns: "Basic " ```