### Path Navigation Example Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/configuration.md Demonstrates the use of `path.dirname()` to get the directory and `path.basename()` to get the filename without extension. The example output shows how these functions are used. ```text imagePath: /home/user/scan.jpg dir: /home/user basename: scan ext: .jpg output: /home/user/scan-a1b2c3d4.txt ``` -------------------------------- ### Absolute File Paths Examples Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/endpoints.md Provide file paths as absolute paths, starting with '/' on Unix-like systems or 'C:\' on Windows. ```plaintext /Users/username/Documents/scan.jpg ``` ```plaintext /home/user/images/document.jpg ``` ```plaintext C:\Users\username\Pictures\image.png ``` -------------------------------- ### Start Project (npm) Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/README.md Start the OCR MCP server using npm. This command runs the built application. ```bash npm start ``` -------------------------------- ### Minimal .env File Example Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/configuration.md This is an example of a minimal .env file. Ensure the OPENAI_API_KEY is set to your actual key. ```dotenv OPENAI_API_KEY=sk-proj-YOUR_FULL_KEY_HERE ``` -------------------------------- ### Install Dependencies Source: https://github.com/cjus/openai-ocr-mcp/blob/main/README.md Installs project dependencies using npm. Ensure Node.js and npm are installed. ```bash npm install ``` -------------------------------- ### Log Output Example Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/configuration.md Example of log messages generated by the server, showing timestamps and messages. ```text [2024-01-15T10:30:45.123Z] OpenAI OCR MCP Server starting up... [2024-01-15T10:30:45.234Z] Successfully loaded .env file [2024-01-15T10:30:45.345Z] Found valid API key in environment variable: OPENAI_API_KEY [2024-01-15T10:30:45.456Z] API Key status: Found and loaded (starts with: sk-proj-...) ``` -------------------------------- ### Example Client Information JSON Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/configuration.md Illustrates the expected JSON structure for client information, including fields like name and version. ```json { "clientInfo": { "name": "Cursor", "version": "1.0.0" } } ``` -------------------------------- ### Start OpenAI OCR MCP Server Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/INDEX.md Start the MCP server using npm or by directly executing the compiled JavaScript file. ```bash npm start ``` ```bash # or: node dist/ocr.js ``` -------------------------------- ### OpenAIMessage Example Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/types.md An example of constructing an OpenAIMessage with both text and an image URL for the OpenAI API. ```typescript const message: OpenAIMessage = { role: 'user', content: [ { type: 'text', text: 'Extract all text from this image...' }, { type: 'image_url', image_url: { url: 'data:image/jpeg;base64,/9j/4AAQSkZJRg...', detail: 'high' } } ] }; ``` -------------------------------- ### McpOfferings Interface and Example Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/types.md Defines the structure for available MCP offerings, specifically a list of tools. An example demonstrates how to structure this object with tool names, descriptions, and parameters. ```typescript interface McpOfferings { tools: McpTool[]; } ``` ```typescript const offerings: McpOfferings = { tools: [ { name: "extract_text_from_image", description: "...", parameters: { /* schema */ } }, { name: "append_analysis", description: "...", parameters: { /* schema */ } } ] }; ``` -------------------------------- ### .env File Format Example Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/configuration.md Illustrates the correct format for entries within a .env file, specifying the OpenAI API key. ```dotenv OPENAI_API_KEY=sk-proj-your-full-api-key-here ``` -------------------------------- ### Create McpCapabilities Response Example Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/types.md Example of an McpCapabilities object advertising two tools: 'extract_text_from_image' and 'append_analysis'. The 'parameters' field should contain valid McpToolParameter schemas. ```typescript const capabilities: McpCapabilities = { tools: { extract_text_from_image: { description: "Extract text from images...", parameters: { /* schema */ } }, append_analysis: { description: "Append LLM analysis...", parameters: { /* schema */ } } } }; ``` -------------------------------- ### Create McpContentItem Instance Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/types.md Example of creating a single content item for a tool result. The 'type' should typically be 'text' for this server. ```typescript const item: McpContentItem = { type: "text", text: "Extracted text from image..." }; ``` -------------------------------- ### OpenAIResponse Success Example Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/types.md An example of a successful response from the OpenAI API, containing generated text content. ```typescript const response: OpenAIResponse = { choices: [ { message: { content: "The image contains...\n\nAnalysis: This document appears to be..." } } ] }; ``` -------------------------------- ### Output File Location Example Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/endpoints.md Extracted text is saved in the same directory as the input image, with a deterministic hash appended to the filename. ```plaintext Input: /path/to/image.jpg Output: /path/to/image-{hash}.txt ``` -------------------------------- ### Invalid .env File Examples Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/configuration.md Shows common mistakes in .env file formatting, such as incorrect spacing, quoting, or key structure. ```dotenv # ❌ Spaces around = OPENAI_API_KEY = sk-proj-... # ❌ Quotes around value OPENAI_API_KEY="sk-proj-..." OPENAI_API_KEY='sk-proj-...' # ❌ Incomplete key OPENAI_API_KEY=sk-proj-* # ❌ Missing prefix OPENAI_API_KEY=abcdef123456789012345678901234 ``` -------------------------------- ### JSON-RPC Server Error Example (Tool Execution Failed) Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/errors.md Example of a JSON-RPC server error (-32000). This typically indicates a failure during tool execution, such as file not found. ```json { "jsonrpc": "2.0", "id": "1", "error": { "code": -32000, "message": "Error executing tool: File not found at path: /path/to/missing.jpg" } } ``` -------------------------------- ### Response: Tool Execution Error Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/endpoints.md An example of an error response when a tool fails during execution, such as a file not being found. ```json { "jsonrpc": "2.0", "id": "3", "error": { "code": -32000, "message": "Error executing tool: File not found at path: /path/to/missing.jpg" } } ``` -------------------------------- ### OpenAIResponse Error Example Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/types.md An example of an error response from the OpenAI API, indicating a problem with the request. ```typescript const errorResponse: OpenAIResponse = { choices: [], error: { message: "Invalid API key provided" } }; ``` -------------------------------- ### Create McpToolParameter Instance Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/types.md Example of creating an McpToolParameter object for a tool that requires an image path. Ensure all required fields are provided. ```typescript const param: McpToolParameter = { type: "object", properties: { image_path: { type: "string", description: "Full path to image file" } }, required: ["image_path"] }; ``` -------------------------------- ### Create Successful McpToolResult Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/types.md Example of a successful tool result containing extracted text and a file path. Ensure the 'content' array is populated. ```typescript const result: McpToolResult = { content: [ { type: "text", text: "Extracted text..." }, { type: "text", text: "\n\nText has been saved to: /path/to/file.txt" } ] }; ``` -------------------------------- ### JSON-RPC Method Not Found Example Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/errors.md Example of a JSON-RPC method not found error (-32601). This occurs when an unknown or unsupported RPC method is called. ```json { "jsonrpc": "2.0", "id": "1", "error": { "code": -32601, "message": "Method not supported: get_tools" } } ``` -------------------------------- ### JSON-RPC Invalid Params Example (Undefined Params) Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/errors.md Example of a JSON-RPC invalid params error (-32602) due to undefined parameters. ```json { "jsonrpc": "2.0", "id": "1", "error": { "code": -32602, "message": "Invalid params: params is undefined" } } ``` -------------------------------- ### ListOfferings Request for MCP Server Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/endpoints.md Send this JSON-RPC request to the MCP server to get a list of available tools without their full capability details. This method requires no parameters. ```json { "jsonrpc": "2.0", "id": "2", "method": "ListOfferings" } ``` -------------------------------- ### API Key Validation Message Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/configuration.md Example output indicating a successfully loaded OpenAI API key. ```text API Key status: Found and loaded (starts with: sk-proj-...) ``` -------------------------------- ### JSON-RPC Invalid Params Example (Missing Image Path) Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/errors.md Example of a JSON-RPC invalid params error (-32602) when a required image path parameter is missing for tools/call. ```json { "jsonrpc": "2.0", "id": "1", "error": { "code": -32602, "message": "Invalid params: Please provide a path to a local image file as a simple string parameter" } } ``` -------------------------------- ### Example Usage of Conversation State Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/configuration.md Demonstrates how to update `lastOcrResult` and `lastImagePath` after OCR extraction, log LLM responses, and construct file paths based on the `lastImagePath` for finding corresponding text files. ```typescript // After OCR extraction conversationState.lastOcrResult = extractedText; conversationState.lastImagePath = imagePath; // When LLM response arrives conversationState.llmResponses.push({ timestamp: new Date().toISOString(), response: JSON.stringify(llmResponse) }); // To find the corresponding text file const dir = path.dirname(conversationState.lastImagePath); const baseNameWithoutExt = path.basename( conversationState.lastImagePath, path.extname(conversationState.lastImagePath) ); // Find {baseNameWithoutExt}-{hash}.txt files in dir ``` -------------------------------- ### Call Tool Request (JSON) Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/README.md Example JSON-RPC 2.0 request to call the 'extract_text_from_image' tool. The 'image_path' parameter specifies the image to process. ```json { "jsonrpc": "2.0", "id": "1", "method": "callTool", "params": { "name": "extract_text_from_image", "arguments": { "image_path": "/path/to/image.jpg" } } } ``` -------------------------------- ### Initial OCR File Content Format Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/configuration.md Defines the initial structure for OCR output files, starting with a header and the extracted text. ```text OCR EXTRACTED TEXT: ================== {extracted text} ``` -------------------------------- ### initialize Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/endpoints.md Establishes initial connection and negotiates capabilities between client and server. This method is crucial for setting up communication and understanding the server's supported features. ```APIDOC ## initialize ### Description Establishes initial connection and negotiates capabilities between client and server. ### Method `initialize` ### Request Parameters #### Request Body - **protocolVersion** (string) - Optional - Client's MCP protocol version - **clientInfo** (object) - Optional - Client identification - **clientInfo.name** (string) - Optional - Client name (e.g., "Cursor") - **clientInfo.version** (string) - Optional - Client version - **capabilities** (object) - Optional - Client capabilities ### Request Example ```json { "jsonrpc": "2.0", "id": "1", "method": "initialize", "params": { "protocolVersion": "2024-11-05", "clientInfo": { "name": "Cursor", "version": "1.0.0" }, "capabilities": {} } } ``` ### Response #### Success Response (200) - **protocolVersion** (string) - Server's MCP protocol version - **serverInfo.name** (string) - Server name: "openai-ocr-service" - **serverInfo.version** (string) - Server version: "1.0.0" - **capabilities.tools** (object) - Map of available tools and their schemas - **clientInfo** (object) - Echo of client info from request #### Response Example ```json { "jsonrpc": "2.0", "id": "1", "result": { "protocolVersion": "2024-11-05", "serverInfo": { "name": "openai-ocr-service", "version": "1.0.0" }, "capabilities": { "tools": { "extract_text_from_image": { "description": "Extract text from images using OpenAI's vision capabilities...", "parameters": { "type": "object", "properties": { "image_path": { "type": "string", "description": "Full path to a local image file (e.g., /Users/username/Pictures/image.jpg)" } }, "required": ["image_path"] } }, "append_analysis": { "description": "Append LLM analysis to an OCR text file...", "parameters": { "type": "object", "properties": { "text_file_path": { "type": "string", "description": "Path to the OCR text file to append analysis to" }, "analysis": { "type": "string", "description": "The LLM's analysis to append to the file" } }, "required": ["text_file_path", "analysis"] } } } }, "clientInfo": { "name": "Cursor", "version": "1.0.0" } } } ``` ### Error Responses - **-32700** (Parse error) - Malformed JSON request - **-32600** (Invalid Request) - Missing required fields ``` -------------------------------- ### handleInitialize Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/api-reference.md Handles the MCP initialize method to establish a connection with the client, returning server capabilities and protocol information. ```APIDOC ## handleInitialize ### Description Handles the MCP initialize method to establish connection with client. ### Signature ```typescript function handleInitialize(id: string | number, params?: any): void ``` ### Parameters #### Path Parameters - **id** (string | number) - Required - Request ID from JSON-RPC request - **params** (any) - Optional - Initialization parameters from client ### Response Returns JSON-RPC success response with: ```json { "protocolVersion": "string", // "2024-11-05" "serverInfo": { "name": "string", // "openai-ocr-service" "version": "string" // "1.0.0" }, "capabilities": { "tools": { "extract_text_from_image": { ... }, "append_analysis": { ... } } }, "clientInfo"?: any // Echo of client info if provided } ``` ``` -------------------------------- ### handleListOfferings Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/api-reference.md Lists all available tools offered by the server, providing details about each tool's capabilities. ```APIDOC ## handleListOfferings ### Description Lists available tools offered by the server. ### Signature ```typescript function handleListOfferings(id: string | number): void ``` ### Parameters #### Path Parameters - **id** (string | number) - Required - Request ID from JSON-RPC request ### Response Returns JSON-RPC success response with array of available tools: ```json { "protocolVersion": "string", "serverInfo": { "name": "string", "version": "string" }, "offerings": { "tools": McpTool[] }, "clientInfo"?: any } ``` ``` -------------------------------- ### JSON-RPC Parse Error Example Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/errors.md Example of a JSON-RPC parse error (-32700). This occurs when the request JSON is malformed. ```json { "jsonrpc": "2.0", "id": "1", "error": { "code": -32700, "message": "Parse error or internal error: Unexpected token } in JSON at position 45" } } ``` -------------------------------- ### JSON-RPC Invalid Request Example Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/errors.md Example of a JSON-RPC invalid request error (-32600). This occurs when required JSON-RPC fields are missing. ```json { "jsonrpc": "2.0", "error": { "code": -32600, "message": "Invalid Request" } } ``` -------------------------------- ### Configure OpenAI API Key Source: https://github.com/cjus/openai-ocr-mcp/blob/main/README.md Sets up the OpenAI API key. This key is required for the server to authenticate with the OpenAI API. Store it in a .env file. ```bash OPENAI_API_KEY=your_api_key_here ``` -------------------------------- ### ListOfferings Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/endpoints.md Returns a list of available tools without providing full capability details. This is useful for quickly discovering what operations the server supports. ```APIDOC ## ListOfferings ### Description Returns list of available tools without full capability details. ### Method `ListOfferings` ### Request Parameters None required. ### Request Example ```json { "jsonrpc": "2.0", "id": "2", "method": "ListOfferings" } ``` ### Response #### Success Response - **protocolVersion** (string) - Server's MCP protocol version - **serverInfo.name** (string) - Server name: "openai-ocr-service" - **serverInfo.version** (string) - Server version: "1.0.0" - **offerings.tools** (array) - List of available tools and their schemas - **clientInfo** (object) - Echo of client info from request #### Response Example ```json { "jsonrpc": "2.0", "id": "2", "result": { "protocolVersion": "2024-11-05", "serverInfo": { "name": "openai-ocr-service", "version": "1.0.0" }, "offerings": { "tools": [ { "name": "extract_text_from_image", "description": "Extract text from images using OpenAI's vision capabilities...", "parameters": { "type": "object", "properties": { "image_path": { "type": "string", "description": "Full path to a local image file (e.g., /Users/username/Pictures/image.jpg)" } }, "required": ["image_path"] } }, { "name": "append_analysis", "description": "Append LLM analysis to an OCR text file...", "parameters": { "type": "object", "properties": { "text_file_path": { "type": "string", "description": "Path to the OCR text file to append analysis to" }, "analysis": { "type": "string", "description": "The LLM's analysis to append to the file" } }, "required": ["text_file_path", "analysis"] } } ] }, "clientInfo": { "name": "Cursor", "version": "1.0.0" } } } ``` ``` -------------------------------- ### Initialize Response from MCP Server Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/endpoints.md This is a successful response to the 'initialize' request, confirming the connection and detailing the server's capabilities, including available tools like 'extract_text_from_image' and 'append_analysis'. ```json { "jsonrpc": "2.0", "id": "1", "result": { "protocolVersion": "2024-11-05", "serverInfo": { "name": "openai-ocr-service", "version": "1.0.0" }, "capabilities": { "tools": { "extract_text_from_image": { "description": "Extract text from images using OpenAI's vision capabilities...", "parameters": { "type": "object", "properties": { "image_path": { "type": "string", "description": "Full path to a local image file (e.g., /Users/username/Pictures/image.jpg)" } }, "required": ["image_path"] } }, "append_analysis": { "description": "Append LLM analysis to an OCR text file...", "parameters": { "type": "object", "properties": { "text_file_path": { "type": "string", "description": "Path to the OCR text file to append analysis to" }, "analysis": { "type": "string", "description": "The LLM's analysis to append to the file" } }, "required": ["text_file_path", "analysis"] } } } }, "clientInfo": { "name": "Cursor", "version": "1.0.0" } } } ``` -------------------------------- ### Run Tests Source: https://github.com/cjus/openai-ocr-mcp/blob/main/README.md Executes the project's test suite. This command is used to verify the functionality and stability of the server. ```bash npm test ``` -------------------------------- ### McpInitializeResponse Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/types.md Complete response to the initialize request, detailing protocol version, server information, and capabilities. ```APIDOC ## McpInitializeResponse ### Description Complete response to the initialize request. ### Fields - **protocolVersion** (string) - Yes - MCP protocol version "2024-11-05" - **serverInfo** (`McpServerInfo`) - Yes - Server identification - **clientInfo** (any) - No - Echo of client info from request - **capabilities** (`McpCapabilities`) - Yes - Server capabilities ### Sent by `handleInitialize()` function ``` -------------------------------- ### ListOfferings Response from MCP Server Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/endpoints.md This is a successful response to the 'ListOfferings' request, providing a list of available tools and their basic descriptions and parameters. It includes 'extract_text_from_image' and 'append_analysis'. ```json { "jsonrpc": "2.0", "id": "2", "result": { "protocolVersion": "2024-11-05", "serverInfo": { "name": "openai-ocr-service", "version": "1.0.0" }, "offerings": { "tools": [ { "name": "extract_text_from_image", "description": "Extract text from images using OpenAI's vision capabilities...", "parameters": { "type": "object", "properties": { "image_path": { "type": "string", "description": "Full path to a local image file (e.g., /Users/username/Pictures/image.jpg)" } }, "required": ["image_path"] } }, { "name": "append_analysis", "description": "Append LLM analysis to an OCR text file...", "parameters": { "type": "object", "properties": { "text_file_path": { "type": "string", "description": "Path to the OCR text file to append analysis to" }, "analysis": { "type": "string", "description": "The LLM's analysis to append to the file" } }, "required": ["text_file_path", "analysis"] } } ] }, "clientInfo": { "name": "Cursor", "version": "1.0.0" } } } ``` -------------------------------- ### Initialize Request for MCP Server Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/endpoints.md Use this JSON-RPC request to establish an initial connection with the MCP server and negotiate capabilities. Ensure the 'protocolVersion' and 'clientInfo' fields are correctly populated. ```json { "jsonrpc": "2.0", "id": "1", "method": "initialize", "params": { "protocolVersion": "2024-11-05", "clientInfo": { "name": "Cursor", "version": "1.0.0" }, "capabilities": {} } } ``` -------------------------------- ### Create Error McpToolResult Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/types.md Example of an erroneous tool result. Set 'isError' to true and provide an error message in the 'content'. ```typescript const errorResult: McpToolResult = { content: [ { type: "text", text: "Error: File not found at path: /path/to/missing.jpg" } ], isError: true }; ``` -------------------------------- ### Valid .env File Entries Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/configuration.md Demonstrates correct syntax for setting environment variables in a .env file, including standard and lowercase key variants. ```dotenv # Standard format OPENAI_API_KEY=sk-proj-abcdef123456789012345678901234 # Multiple keys (server checks in order) openai_api_key=sk-proj-abcdef123456789012345678901234 ``` -------------------------------- ### Handle MCP Initialize Request Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/api-reference.md Handles the MCP initialize method to establish a connection with the client. It returns protocol version, server info, and capabilities. ```typescript function handleInitialize(id: string | number, params?: any): void ``` -------------------------------- ### Send Initialization Notification Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/endpoints.md Send this notification after the client has completed its full initialization. This signals to the server that the client is ready. ```json { "jsonrpc": "2.0", "method": "notifications/initialized" } ``` -------------------------------- ### Get MIME Type from File Extension Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/api-reference.md Determines the MIME type based on a file's extension. Defaults to 'image/jpeg' for unsupported extensions. ```typescript function getMimeType(filePath: string): string ``` ```typescript getMimeType('/path/to/image.png'); // Returns 'image/png' getMimeType('/path/to/image.webp'); // Returns 'image/webp' getMimeType('/path/to/unknown'); // Returns 'image/jpeg' (default) ``` -------------------------------- ### Content-Based File Naming Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/README.md Illustrates how input filenames are transformed into output filenames using a content-based hash. This ensures deterministic naming for the same input content. ```text Input: /path/to/scan.jpg Output: /path/to/scan-a1b2c3d4.txt └─────────────────────┘ Content-based hash ``` -------------------------------- ### Example Log Message Format Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/errors.md Errors are logged to stderr with an ISO 8601 timestamp and the error message. This format helps in identifying when an error occurred and its nature. ```text [2024-01-15T10:30:45.123Z] Error: File not found at path: /path/to/missing.jpg ``` -------------------------------- ### List Available Tools (JSON-RPC) Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/endpoints.md Use this JSON-RPC request to list all available tools that can be called by MCP Inspector. The response details each tool's name, description, and input/output schemas. ```json { "jsonrpc": "2.0", "id": "5", "method": "tools/list" } ``` ```json { "jsonrpc": "2.0", "id": "5", "result": { "tools": [ { "name": "extract_text_from_image", "description": "Extract text from images using OpenAI's vision capabilities...", "inputSchema": { "type": "object", "properties": { "image_path": { "type": "string", "description": "Full path to a local image file (e.g., /Users/username/Pictures/image.jpg)" } }, "required": ["image_path"] }, "outputSchema": { "type": "object", "properties": { "content": { "type": "array", "items": { "type": "object", "properties": { "type": { "type": "string", "description": "Type of content (text)" }, "text": { "type": "string", "description": "Extracted text from the image" } } } } } } }, { "name": "append_analysis", "description": "Append LLM analysis to an OCR text file...", "inputSchema": { "type": "object", "properties": { "text_file_path": { "type": "string", "description": "Path to the OCR text file to append analysis to" }, "analysis": { "type": "string", "description": "The LLM's analysis to append to the file" } }, "required": ["text_file_path", "analysis"] }, "outputSchema": { "type": "object", "properties": { "content": { "type": "array", "items": { "type": "object", "properties": { "type": { "type": "string", "description": "Type of content (text)" }, "text": { "type": "string", "description": "Status message about the analysis being appended" } } } } } } } ] } } ``` -------------------------------- ### OpenAI API Error Response Example Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/errors.md This JSON structure represents a typical error response from the OpenAI API, detailing the error message, type, and code. ```json { "error": { "message": "Invalid API key provided. You can find your API key at https://platform.openai.com/account/api-keys.", "type": "invalid_request_error", "param": null, "code": "invalid_api_key" } } ``` -------------------------------- ### API Key Format Validation Error Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/errors.md Handles errors related to an invalid OpenAI API key format. Verify the key starts with 'sk-' or 'sk-proj-', has sufficient length, and is not truncated. ```text Invalid key format. Key must start with "sk-" or "sk-proj-" and be of sufficient length. Got: {prefix}... ``` -------------------------------- ### MCP Server Configuration (mcp-config.json) Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/configuration.md This JSON file configures how MCP clients launch the OCR server. It specifies the command to execute and its arguments. ```json { "mcpServers": { "ocr": { "command": "node", "args": ["dist/ocr.js"] } } } ``` -------------------------------- ### API Key Missing Error Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/errors.md Indicates that the OpenAI API key is not set in the environment variables. Ensure the OPENAI_API_KEY environment variable is correctly set. ```text OpenAI API key is not available. Please set the environment variable. ``` -------------------------------- ### Environment Variable Configuration Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/errors.md When the .env file is missing, the server continues by checking system environment variables. To resolve this, create a .env file in the project root and add your API key. ```env OPENAI_API_KEY=your_key_here ``` -------------------------------- ### List Available Tools Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/endpoints.md Lists all the tools that are available for use with the MCP Inspector and similar tools. This includes details about their names, descriptions, input schemas, and output schemas. ```APIDOC ## tools/list ### Description Lists available tools (used by MCP Inspector and similar tools). ### Method `tools/list` ### Request Example ```json { "jsonrpc": "2.0", "id": "5", "method": "tools/list" } ``` ### Response Example ```json { "jsonrpc": "2.0", "id": "5", "result": { "tools": [ { "name": "extract_text_from_image", "description": "Extract text from images using OpenAI's vision capabilities...", "inputSchema": { "type": "object", "properties": { "image_path": { "type": "string", "description": "Full path to a local image file (e.g., /Users/username/Pictures/image.jpg)" } }, "required": ["image_path"] }, "outputSchema": { "type": "object", "properties": { "content": { "type": "array", "items": { "type": "object", "properties": { "type": { "type": "string", "description": "Type of content (text)" }, "text": { "type": "string", "description": "Extracted text from the image" } } } } } } }, { "name": "append_analysis", "description": "Append LLM analysis to an OCR text file...", "inputSchema": { "type": "object", "properties": { "text_file_path": { "type": "string", "description": "Path to the OCR text file to append analysis to" }, "analysis": { "type": "string", "description": "The LLM's analysis to append to the file" } }, "required": ["text_file_path", "analysis"] }, "outputSchema": { "type": "object", "properties": { "content": { "type": "array", "items": { "type": "object", "properties": { "type": { "type": "string", "description": "Type of content (text)" }, "text": { "type": "string", "description": "Status message about the analysis being appended" } } } } } } } ] } } ``` ``` -------------------------------- ### McpListOfferingsResponse Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/types.md Response to the ListOfferings request, including protocol version, server information, and available offerings. ```APIDOC ## McpListOfferingsResponse ### Description Response to ListOfferings request. ### Fields - **protocolVersion** (string) - Yes - MCP protocol version - **serverInfo** (`McpServerInfo`) - Yes - Server identification - **clientInfo** (any) - No - Client information if provided - **offerings** (`McpOfferings`) - Yes - Available offerings ### Sent by `handleListOfferings()` function ``` -------------------------------- ### Define McpCapabilities Interface Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/types.md Defines the server capabilities, specifically the available tools and their descriptions/parameters. This is sent in the initialize response. ```typescript interface McpCapabilities { tools: { [key: string]: { description: string; parameters: McpToolParameter; }; }; } ``` -------------------------------- ### Client Initialization Request Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/INDEX.md This JSON payload is used to initialize the client connection. It includes the protocol version and client information. ```json { "jsonrpc": "2.0", "id": "0", "method": "initialize", "params": { "protocolVersion": "2024-11-05", "clientInfo": { "name": "Cursor", "version": "1.0.0" } } } ``` -------------------------------- ### notifications/initialized Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/endpoints.md Sent by client after full initialization is complete. ```APIDOC ## notifications/initialized ### Description Sent by client after full initialization is complete. ### Method notifications/initialized ### Request ```json { "jsonrpc": "2.0", "method": "notifications/initialized" } ``` ``` -------------------------------- ### Loading .env File in TypeScript Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/configuration.md Code snippet demonstrating how the server loads environment variables from a .env file using the 'dotenv' package and handles potential errors. ```typescript const envResult = dotenv.config(); if (envResult.error) { log('Warning: Error loading .env file: ' + envResult.error.message); } ``` -------------------------------- ### Initialize Client Information Storage Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/configuration.md Declares a variable `clientInfo` to store client-specific details received during initialization. This information is echoed back in all MCP response messages. ```typescript let clientInfo: any = null; ``` -------------------------------- ### Set OpenAI API Key (Bash) Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/README.md Set the OPENAI_API_KEY environment variable before running the application. Replace 'sk-proj-your-key' with your actual API key. ```bash export OPENAI_API_KEY="sk-proj-your-key" ``` -------------------------------- ### Handle MCP List Offerings Request Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/api-reference.md Handles the MCP list offerings method to return an array of available tools offered by the server. ```typescript function handleListOfferings(id: string | number): void ``` -------------------------------- ### Call Tool (JSON-RPC) - Multiple Formats Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/endpoints.md This endpoint allows for calling tools with different parameter formats. Choose the format that best suits your needs, whether it's a direct string, a named parameter object, or specifying the tool name with its parameters. ```json { "jsonrpc": "2.0", "id": "6", "method": "tools/call", "params": "/path/to/document.jpg" } ``` ```json { "jsonrpc": "2.0", "id": "6", "method": "tools/call", "params": { "image_path": "/path/to/document.jpg" } } ``` ```json { "jsonrpc": "2.0", "id": "6", "method": "tools/call", "params": { "name": "extract_text_from_image", "params": { "image_path": "/path/to/document.jpg" } } } ``` -------------------------------- ### McpInitializeResponse Interface Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/types.md Defines the structure of the response to an MCP initialize request. Includes protocol version, server information, optional client info, and server capabilities. ```typescript interface McpInitializeResponse { protocolVersion: string; serverInfo: McpServerInfo; clientInfo?: any; capabilities: McpCapabilities; } ``` -------------------------------- ### Initialize OpenAI API Key Storage Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/configuration.md Declares a variable to hold the OpenAI API key. It is initialized at startup, attempting to load from a .env file and falling back to system environment variables. ```typescript let OPENAI_API_KEY: string | undefined; ``` -------------------------------- ### Set OpenAI API Key Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/INDEX.md Export your OpenAI API key as an environment variable or define it in a .env file. This is required for authentication. ```bash export OPENAI_API_KEY="sk-proj-your-full-key" ``` ```bash # OR create .env file with: # OPENAI_API_KEY=sk-proj-your-full-key ``` -------------------------------- ### Handle File Existence Error Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/errors.md Throws an error if the image file does not exist at the specified path. Verify the path and file permissions for recovery. ```typescript if (!exists) { throw new Error(`File not found at path: ${imagePath}`); } ``` -------------------------------- ### Standard Protocol Methods Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/INDEX.md These are the primary methods for interacting with the OpenAI OCR MCP service to establish connections, list and call tools, and manage operations. ```APIDOC ## initialize ### Description Establishes a connection with the OCR MCP service and negotiates capabilities between the client and server. ### Method Not specified (assumed to be part of a custom protocol) ### Request - **Protocol version** (string) - The version of the protocol being used. - **Client info** (object) - Information about the client. ### Response - **Server info** (object) - Information about the server. - **Tools list** (array) - A list of available tools. ``` ```APIDOC ## ListOfferings ### Description Retrieves a list of all available tools that can be executed by the OCR MCP service. ### Method Not specified (assumed to be part of a custom protocol) ### Response - **Array of tool definitions** (array) - Each element describes an available tool. ``` ```APIDOC ## callTool ### Description Executes a specified tool with the provided arguments. ### Method Not specified (assumed to be part of a custom protocol) ### Request - **Tool name** (string) - The name of the tool to execute. - **Arguments** (object) - The arguments required by the tool. ### Response - **Tool result** (any) - The outcome of the tool execution. ``` ```APIDOC ## tools/list ### Description An alternative method to get a list of available tools, including their schemas. ### Method Not specified (assumed to be part of a custom protocol) ### Response - **Tools with schemas** (object) - An object containing tools and their associated schemas. ``` ```APIDOC ## tools/call ### Description An alternative method for invoking a tool, potentially with image-related arguments. ### Method Not specified (assumed to be part of a custom protocol) ### Request - **Image path** (string) - The path to the image to be processed by the tool. ### Response - **Tool result** (any) - The outcome of the tool execution. ``` -------------------------------- ### Response: Append Analysis (Success) Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/endpoints.md A successful response from the `append_analysis` tool. It confirms that the analysis has been appended to the specified text file. ```json { "jsonrpc": "2.0", "id": "4", "result": { "content": [ { "type": "text", "text": "Analysis has been appended to: /path/to/document-a1b2c3d4.txt" } ] } } ``` -------------------------------- ### getOpenAIApiKey Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/INDEX.md Retrieves the OpenAI API key from the environment variables. ```APIDOC ## getOpenAIApiKey ### Description Get API key from environment. ### Signature `(): string | undefined` ### Returns The OpenAI API key as a string, or undefined if not set. ``` -------------------------------- ### McpListOfferingsResponse Interface Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/types.md Defines the structure of the response to an MCP ListOfferings request. Includes protocol version, server information, optional client info, and available offerings. ```typescript interface McpListOfferingsResponse { protocolVersion: string; serverInfo: McpServerInfo; clientInfo?: any; offerings: McpOfferings; } ``` -------------------------------- ### API Key Not Found Error Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/configuration.md Error message displayed when a valid OpenAI API key is not found in environment variables or the .env file. ```text ERROR: Valid OpenAI API key not found in environment variables or .env file ``` -------------------------------- ### Call a Tool Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/endpoints.md Allows for invoking a specific tool with its required parameters. Supports multiple request formats for flexibility. ```APIDOC ## tools/call ### Description Alternative tool invocation method (used by MCP Inspector). ### Method `tools/call` ### Request Example (Format 1 - Direct string parameter) ```json { "jsonrpc": "2.0", "id": "6", "method": "tools/call", "params": "/path/to/document.jpg" } ``` ### Request Example (Format 2 - Named parameters object) ```json { "jsonrpc": "2.0", "id": "6", "method": "tools/call", "params": { "image_path": "/path/to/document.jpg" } } ``` ### Request Example (Format 3 - Tool name with parameters) ```json { "jsonrpc": "2.0", "id": "6", "method": "tools/call", "params": { "name": "extract_text_from_image", "params": { "image_path": "/path/to/document.jpg" } } } ``` ### Response Same as `callTool` — returns `McpToolResult` with `content` array. ``` -------------------------------- ### Generate Short SHA256 Hash for Filenames Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/configuration.md Creates a deterministic and unique 8-character hash from input text, suitable for appending to filenames to ensure uniqueness and avoid collisions. ```typescript function generateShortHash(text: string): string { const hash = createHash('sha256').update(text).digest('hex'); return hash.substring(0, 8); // First 8 chars } ``` -------------------------------- ### getOpenAIApiKey Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/api-reference.md Retrieves and validates the OpenAI API key from environment variables. It checks multiple common environment variable names and applies validation rules. ```APIDOC ## getOpenAIApiKey ### Description Retrieves and validates OpenAI API key from environment variables, checking multiple possible variable names. ### Returns - **apiKey** (string | undefined) - Valid API key if found, otherwise `undefined`. ### Environment Variables Checked 1. `OPENAI_API_KEY` 2. `openai_api_key` 3. `OpenAI_API_Key` ### Behavior Checks all three environment variable formats, trims whitespace, ignores placeholder values, and validates each key using `validateApiKey()`. Returns the first valid key found or `undefined`. ### Example ```typescript const apiKey = getOpenAIApiKey(); if (apiKey) { log(`Found API key: ${apiKey.substring(0, 8)}...`); } else { log('No valid API key found'); } ``` ``` -------------------------------- ### handleCallTool Source: https://github.com/cjus/openai-ocr-mcp/blob/main/_autodocs/api-reference.md Executes a specified tool with provided arguments. Supports 'extract_text_from_image' and 'append_analysis' tools. ```APIDOC ## handleCallTool ### Description Executes a tool by name with arguments. ### Signature ```typescript async function handleCallTool(id: string | number, params: any): Promise ``` ### Parameters #### Path Parameters - **id** (string | number) - Required - Request ID from JSON-RPC request - **params** (object) - Required - Tool invocation parameters - **params.name** (string) - Required - Name of tool to call (`extract_text_from_image` or `append_analysis`) - **params.arguments** (object) - Required - Tool-specific arguments ### Supported Tools 1. `extract_text_from_image` — requires `arguments.image_path` 2. `append_analysis` — requires `arguments.text_file_path` and `arguments.analysis` ```