- Netsis & Mistral AI MCP Server Bridge
Netsis & Mistral AI MCP Server Bridge
Netsis & Mistral AI MCP Server Bridge
🌟 Overview
The Netsis & Mistral AI MCP Server Bridge is a specialized .NET application that serves as an intelligent intermediary, leveraging the Model Context Protocol (MCP). Its core purpose is to expose complex functionalities from a Netsis Enterprise Resource Planning (ERP) system and Mistral AI's Optical Character Recognition (OCR) service in a standardized, LLM-friendly manner.
By acting as an MCP server, this application enables Large Language Models (LLMs) and other MCP-compliant clients to seamlessly query data, execute operations within Netsis, and perform document text extraction via Mistral AI. This is achieved by translating natural language requests (interpreted by an LLM) into structured API calls to the respective backend systems, all orchestrated through the robust MCP framework.
The server is designed as a console application, typically intended to be launched and managed by an MCP client using the Stdio (Standard Input/Output) transport mechanism. This allows for tight integration where an LLM can delegate tasks to this server to interact with enterprise data and advanced AI services.
✨ Core Capabilities & Features
The server empowers MCP clients with a suite of tools that bridge the gap to essential business and AI functionalities:
Netsis ERP Integration
Leveraging the NetOpenXApiClient.cs, the server provides a comprehensive set of tools (exposed via NetsisMcpTools.cs) for interacting with your Netsis instance:
- Customer Relationship Management (CRM):
get_netsis_customer_details: Retrieve comprehensive details for a specific customer using their unique Netsis customer code (CARI_KOD).list_netsis_customers: Fetch a paginated list of customers. Supports filtering by parts of the customer's name to narrow down results.update_netsis_customer_phone: Modify the registered phone number for a specified customer.
- Inventory & Stock Management:
get_netsis_stock_item_details: Access detailed information about a specific stock item using its item code (STOK_KODU).
- Sales, Invoicing & Order Processing:
create_netsis_sales_invoice: Programmatically generate new sales invoices within Netsis, including customer details and a list of line items.list_sales_orders_for_customer: Retrieve a list of sales order headers associated with a particular customer. Supports filtering by date range and pagination.get_sales_order_details: Fetch the complete details of a specific sales order, including both header information and all associated line items, using its order number.print_netsis_invoice_pdf: Generate a PDF representation of a sales invoice based on a predefined Netsis design number.
- Financial Operations:
list_netsis_exchange_rates: Obtain a list of currency exchange rates, with an option to filter for a specific date.get_netsis_check_note_details: Retrieve detailed information about a specific Check/Note (Çek/Senet) using its Bordro number and type.create_netsis_check_note: Create new Check/Note entries within the Netsis financial system.list_netsis_gl_accounts: List General Ledger (Muhasebe) accounts from the Netsis chart of accounts.
- Project Management:
get_netsis_project_details: Fetch information and status for a specific project code.
- System Information:
get_netsis_netopenx_version: Query and return the current version of the NetOpenX API being utilized by the Netsis instance.
Mistral AI OCR Integration
Utilizing MistralApiClient.cs, the server offers a powerful OCR tool via NetsisMcpTools.cs:
extract_text_from_document_url_with_mistral_ocr: Accepts a publicly accessible URL pointing to a PDF or image file. It then uses Mistral AI's advanced OCR capabilities to extract all textual content from the document. This is invaluable for digitizing documents and making their content programmatically accessible.
⚙️ Prerequisites
To successfully build and run this server, the following components and configurations are necessary:
- .NET SDK: Version 8.0 or a more recent compatible version.
- Netsis ERP System:
- An operational instance of Netsis ERP.
- Valid NetOpenX API credentials: username, password, company code, and specific database connection details (server, DB name, DB user/password, DB type).
- Mistral AI API Key:
- An active API key obtained from Mistral AI, granting access to their OCR and potentially other services.
- (Recommended for Development) .NET User Secrets: A mechanism for securely storing sensitive credentials (like API keys and passwords) outside of version-controlled configuration files.
🚀 Setup & Configuration
Follow these steps to get the server up and running:
-
Clone the Repository:
git clone <your-repository-url> cd netsisMCP -
Configure Application Settings (
appsettings.jsonand User Secrets): The core configuration resides inappsettings.json. Crucially, sensitive details like API keys and passwords should be managed using .NET User Secrets for development environments.appsettings.json(Template):{ "NetOpenX": { "BaseUrl": "http://YOUR_NETSIS_SERVER_IP_OR_HOSTNAME:7070/api/v2/", // Replace with your NetOpenX API endpoint "Username": "YOUR_NETSIS_API_USER", "Password": "NETOPENX_PASSWORD_USER_SECRET", // Placeholder - store actual in User Secrets "BranchCode": 0, // Or your specific branch code "DbType": "vtMSSQL", // Or "VTORACLE" as per your Netsis setup "DbName": "YOUR_NETSIS_DATABASE_NAME", "DbUser": "YOUR_DB_USER", // Often same as NetsisUser or a dedicated DB user "DbPassword": "DB_PASSWORD_USER_SECRET" // Placeholder - store actual in User Secrets }, "MistralAI": { "ApiKey": "MISTRAL_API_KEY_USER_SECRET", // Placeholder - store actual in User Secrets "OcrSubmitEndpoint": "https://api.mistral.ai/v1/documents/ocr/jobs", "OcrJobStatusEndpointFormat": "https://api.mistral.ai/v1/documents/ocr/jobs/{0}" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.Hosting.Lifetime": "Information", "ModelContextProtocol": "Debug", "NetsisMcpServer": "Information", // For this application's logs "NetOpenXApiClient": "Information", "MistralApiClient": "Information" } } }Using .NET User Secrets (Highly Recommended): Initialize user secrets for your project (run from the
netsisMCPproject directory):dotnet user-secrets initThen set your sensitive values:
dotnet user-secrets set "NetOpenX:Password" "your_actual_netsis_api_password" dotnet user-secrets set "NetOpenX:DbPassword" "your_actual_db_password" dotnet user-secrets set "MistralAI:ApiKey" "your_actual_mistral_api_key" # Add other sensitive configurations as neededThe application is configured to automatically load these secrets, overriding placeholders in
appsettings.json. -
Build the Project: Navigate to the project's root directory (where
netsisMCP.csprojis located) and run:dotnet build
▶️ Running the Server
To start the MCP server, execute the following command from the project's root directory:
dotnet run --project netsisMCP/netsisMCP.csproj
Alternatively, if your current directory is already netsisMCP:
dotnet run
Upon successful startup, the server will print a message like "Netsis & Mistral MCP Server starting (vX.Y.Z)..." to the console. It will then listen for MCP commands via its Standard Input (Stdin) and send responses/notifications via its Standard Output (Stdout). This server is typically launched and its lifecycle managed by an external MCP client application.
🛠️ Usage
This application is an MCP server and requires an MCP client for interaction. The client (often driven by an LLM) will connect to this server, discover its available tools, and invoke them as needed.
Connecting an MCP Client
A typical connection from an MCP client (e.g., one built with the ModelContextProtocol C# SDK) would involve launching this server as a child process and communicating over Stdio.
Conceptual C# Client Snippet:
using ModelContextProtocol.Client;
using ModelContextProtocol.Server; // For StdioClientTransportOptions
// ...
var serverExecutable = "dotnet"; // Or the path to your compiled NetsisMcpServer.exe
var serverArguments = new List<string> { "run", "--project", "path/to/your/netsisMCP/netsisMCP.csproj" };
// Adjust arguments if running a pre-compiled executable
var stdioOptions = new StdioClientTransportOptions
{
Command = serverExecutable,
Arguments = serverArguments,
Name = "MyNetsisMistralClient" // A descriptive name for your client instance
};
var transport = new StdioClientTransport(stdioOptions);
IMcpClient mcpClient = await McpClientFactory.CreateAsync(transport);
// Discover and use tools
var availableTools = await mcpClient.ListToolsAsync();
Console.WriteLine($"Available tools: {string.Join(", ", availableTools.Select(t => t.Name))}");
// Example: Get customer details
// var customerDetailsJson = await mcpClient.CallToolAsync("get_netsis_customer_details", new Dictionary<string, object?> { { "customerCode", "CUST001" } });
// Console.WriteLine(customerDetailsJson);
// ... further interactions
await mcpClient.DisposeAsync();
Tool Interaction Example
An LLM, via an MCP client, might process a user request like: "Fetch the details for customer 'ABC Corp' from Netsis and then extract text from their latest invoice found at http://example.com/invoice.pdf"
- The LLM (or client logic) would first call
list_netsis_customerswithfilterByName: "ABC Corp"to get thecustomerCode. - Then, it would call
get_netsis_customer_detailswith the retrievedcustomerCode. - Finally, it would call
extract_text_from_document_url_with_mistral_ocrwithdocumentUrl: "http://example.com/invoice.pdf". - The LLM would then synthesize this information to answer the user's request.
🏗️ Project Architecture
Program.cs: The application's main entry point. It configures the .NET host, sets up dependency injection (DI) for API clients (NetOpenXApiClient,MistralApiClient) and MCP tools, initializes logging, and starts the MCP server.NetsisMcpTools.cs: This class houses the public static methods that are exposed as MCP tools. Each method is decorated with[McpServerTool]and[Description]attributes. These methods orchestrate the logic by calling appropriate methods on the injected API client services.NetOpenXApiClient.cs: A dedicated client class responsible for all interactions with the NetOpenX (Netsis) REST API. It handles authentication (obtaining and refreshing access tokens) and makes HTTP requests to fetch or submit data to Netsis.MistralApiClient.cs: A client class for interacting with the Mistral AI API. Currently, it implements the OCR functionality, including job submission and polling for results.NetsisDataModels.cs: Contains Plain Old C# Objects (POCOs) or Data Transfer Objects (DTOs) that map to the JSON structures expected by and returned from the Netsis NetOpenX API. These are used for serialization and deserialization.MistralDataModels.cs: Defines DTOs for request and response payloads when communicating with the Mistral AI API for OCR tasks.appsettings.json: The primary configuration file for storing non-sensitive settings like API base URLs and logging levels. Sensitive data should be managed via User Secrets.netsisMCP.csproj: The .NET project file defining project metadata, target framework, and package dependencies (e.g.,ModelContextProtocol,Microsoft.Extensions.Hosting).
🪵 Logging
The application utilizes the Microsoft.Extensions.Logging framework.
- Logging levels are configurable in
appsettings.jsonunder theLoggingsection. This allows fine-grained control over log verbosity for different components. - By default, logs are written to the console (specifically, to
stderrwhich is standard for diagnostic output). - The
ModelContextProtocollibrary itself produces debug logs, which can be enabled for deeper insights into MCP communication. - The
NetOpenXApiClientandMistralApiClientalso log their operations, aiding in diagnosing API interaction issues.
🐛 Troubleshooting
- Authentication Failures (NetOpenX or Mistral):
- Verify that API keys, usernames, passwords, and other credentials in
appsettings.json(or preferably, User Secrets) are accurate and have the necessary permissions. - Ensure the Netsis API user is active and configured correctly.
- Check if your Mistral AI API key is valid and has OCR entitlements.
- Verify that API keys, usernames, passwords, and other credentials in
- Connection Problems:
- Confirm that the
NetOpenX:BaseUrlinappsettings.jsonpoints to the correct, accessible NetOpenX API endpoint. - Check network connectivity to both Netsis and Mistral AI API endpoints. Firewalls or proxy servers might be blocking access.
- Confirm that the
- Tool Invocation Errors (
McpExceptionor tool-specific errors):- Ensure the tool name used by the MCP client exactly matches the
Nameproperty in the[McpServerTool(Name = "...")]attribute inNetsisMcpTools.cs. - Verify that the arguments provided by the client match the schema expected by the tool (parameter names, types, and requiredness).
- Examine the server's console output (stderr) for detailed error messages and stack traces. Enable
DebugorTracelog levels for more information.
- Ensure the tool name used by the MCP client exactly matches the
- Mistral OCR Issues:
- The
documentUrlpassed toextract_text_from_document_url_with_mistral_ocrmust be publicly accessible by Mistral AI's servers. Local file paths or intranet URLs will not work. - Review your Mistral AI dashboard for any API usage limits, billing issues, or service status updates.
- The OCR process is asynchronous; the tool polls for results. Ensure network stability during this polling phase.
- The
- General Issues:
- If the server fails to start, check the console for any .NET host startup errors.
- Ensure all NuGet package dependencies are correctly restored (
dotnet restore).
🛣️ Potential Future Enhancements
- Expanded Netsis Toolset: Implement a wider range of Netsis API functionalities as MCP tools (e.g., inventory adjustments, purchase order creation, detailed financial reporting tools).
- MCP Prompts & Resources:
- Define
McpServerPrompts for common Netsis queries or data entry tasks. - Expose certain Netsis data entities (e.g., product catalogs, price lists) as MCP
McpServerResources for direct LLM consumption.
- Define
- More Granular Error Handling: Return more specific error details within the
CallToolResponse.Content(withIsError = true) for tool-specific failures, providing better context to the LLM. - Comprehensive Testing: Implement unit tests for API clients and tool logic, and integration tests for end-to-end MCP server functionality.
- Alternative Transports: Consider adding support for HTTP/SSE or Streamable HTTP transports if the server needs to be hosted as a persistent web service rather than a Stdio-managed process. This would require changes to
Program.csto useWebApplication.CreateBuilderandMapMcp. - Configuration for Retries/Timeouts: Make API client retry policies and timeouts configurable via
appsettings.json. - Caching: Implement caching for frequently requested, non-volatile data from Netsis to improve performance and reduce API load.