### StreamableHTTP Server Running Instructions Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/transport-modes.md Steps to install dependencies, build, and start the StreamableHTTP server. Access the test UI at the specified address after starting. ```bash cd mcp-server npm install npm run build npm run start:http # Server starts on http://localhost:3000 # Test UI at http://localhost:3000 ``` -------------------------------- ### Setup Instructions from .env.example Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/security-handling.md These bash commands outline the steps to set up your environment using the generated `.env.example` file, including copying, editing, and installing dependencies. ```bash cp .env.example .env # Edit .env with your credentials npm install npm start ``` -------------------------------- ### Run Web (SSE) Server Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/transport-modes.md Install dependencies, build the project, and start the MCP server using the web transport. The server starts on the specified port. ```bash cd mcp-server npm install npm run build npm run start:web # Server starts on http://localhost:3000 # Test UI at http://localhost:3000 ``` -------------------------------- ### Run Stdio Server Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/transport-modes.md Install dependencies, build the project, and start the MCP server using the stdio transport. The server listens on stdin. ```bash cd mcp-server npm install npm run build npm start ``` -------------------------------- ### Basic Authentication Example .env Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/security-handling.md Example environment variables for basic authentication. ```bash BASIC_USERNAME_BASIC_AUTH=user@example.com BASIC_PASSWORD_BASIC_AUTH=secure_password_123 ``` -------------------------------- ### Install and Run Generated Server Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/README.md Navigate to the output directory, install dependencies, and run the generated server in different modes: stdio, web server, or StreamableHTTP. ```bash cd path/to/output/dir npm install # Run in stdio mode npm start # Run in web server mode npm run start:web # Run in StreamableHTTP mode npm run start:http ``` -------------------------------- ### Example .env.example Output Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/api-reference/generator-functions.md Example output for the `.env.example` file, showing typical configurations for API base URL and different types of security credentials. ```bash # API Configuration API_BASE_URL=https://api.example.com # Security Credentials API_KEY_PETSTORE_API_KEY=your-api-key-here BEARER_TOKEN_BEARER_AUTH=your-bearer-token-here BASIC_USERNAME_BASIC_AUTH=username BASIC_PASSWORD_BASIC_AUTH=password OAUTH_CLIENT_ID_OAUTH2_SCHEME=your-client-id OAUTH_CLIENT_SECRET_OAUTH2_SCHEME=your-client-secret OAUTH_SCOPES_OAUTH2_SCHEME=read:pets write:pets ``` -------------------------------- ### Web (SSE) GET Request Example Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/transport-modes.md Example of connecting to the Server-Sent Events stream via the GET /mcp/sse endpoint when using the Web (SSE) transport. ```http GET /mcp/sse HTTP/1.1 Host: localhost:3000 Response: 200 OK (streaming) Content-Type: text/event-stream data: {"jsonrpc":"2.0","method":"notification",...}\n\n data: {"jsonrpc":"2.0","method":"another",...}\n\n ``` -------------------------------- ### Build and Run Generated Server Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/configuration.md Commands to install dependencies, build the TypeScript code, and start the generated server. Supports different transport methods. ```bash cd generated-server-directory npm install npm run build ``` ```bash npm start # Or use specific transport: npm run start:web # For web transport npm run start:http # For streamable-http transport ``` -------------------------------- ### API Key Example .env Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/security-handling.md Example environment variable for an API key security scheme. ```bash API_KEY_API_KEY=sk-1234567890abcdef ``` -------------------------------- ### Missing Credentials Warning Example Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/security-handling.md This example shows the warning message logged when a tool requires security but the necessary credentials are not found in the environment. ```text Tool 'listPets' requires security: [api_key (scopes: )] OR [oauth2 (scopes: read:pets)], but no suitable credentials found. ``` -------------------------------- ### OAuth2 Example .env - Auto-Acquisition Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/security-handling.md Example environment variables for OAuth2 auto-acquisition using client credentials. ```bash # Auto-acquire token using client credentials OAUTH_CLIENT_ID_OAUTH2_PETSTORE=client_id_123 OAUTH_CLIENT_SECRET_OAUTH2_PETSTORE=client_secret_456 OAUTH_SCOPES_OAUTH2_PETSTORE=read:pets write:pets ``` -------------------------------- ### Set up environment variables Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/configuration.md Copy the example .env file and fill in your credentials. This sets up the environment for the generated server. ```bash cd generated-server cp .env.example .env # Edit .env with your credentials npm install npm start ``` -------------------------------- ### OAuth2 Example .env - Pre-Acquired Token Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/security-handling.md Example environment variable for using a pre-acquired OAuth2 token. ```bash ``` -------------------------------- ### Bearer Token Example .env Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/security-handling.md Example environment variable for a bearer token security scheme. ```bash BEARER_TOKEN_BEARER_AUTH=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... ``` -------------------------------- ### Install openapi-mcp-generator Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/README.md Install the CLI tool globally using npm, yarn, or pnpm. ```bash npm install -g openapi-mcp-generator ``` -------------------------------- ### Package.json Scripts Example Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/api-reference/generator-functions.md Example JSON object showing common npm scripts for building, testing, and running the generated server, including variations for different transport types. ```json { "start": "node build/index.js", "build": "tsc && shx chmod 755 build/index.js", "typecheck": "tsc --noEmit", "start:web": "node build/index.js --transport=web", "start:http": "node build/index.js --transport=streamable-http" } ``` -------------------------------- ### Example .env.example File Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/configuration.md A template .env.example file listing environment variables for API configuration and authentication schemes. Populate these with your specific credentials. ```bash # API Configuration API_BASE_URL=https://api.example.com # Authentication (populated based on OpenAPI spec) API_KEY_MYAPI=your-api-key-here BEARER_TOKEN_OAUTH2=your-bearer-token-here BASIC_USERNAME_BASICAUTH=username BASIC_PASSWORD_BASICAUTH=password ``` -------------------------------- ### Install OpenAPI MCP Generator Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/PROGRAMMATIC_API.md Install the package using npm. ```bash npm install openapi-mcp-generator ``` -------------------------------- ### Setup StreamableHTTP Server Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/api-reference/generateMcpServerCode.md Initializes a StreamableHTTP server. Ensure the `server` object is defined elsewhere in your application. ```typescript import { setupStreamableHttpServer } from "./streamable-http.js"; async function main() { try { await setupStreamableHttpServer(server, 3000); } catch (error) { console.error("Error setting up StreamableHTTP server:", error); process.exit(1); } } ``` -------------------------------- ### Cite Programmatic API Usage Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/INDEX.md Example of how to cite the programmatic API documentation for getToolsFromOpenApi. ```markdown See getToolsFromOpenApi (api-reference/getToolsFromOpenApi.md) for programmatic API usage. ``` -------------------------------- ### Web (SSE) POST Request Example Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/transport-modes.md Example of sending a JSON-RPC request to the server via the POST /mcp/messages endpoint when using the Web (SSE) transport. ```http POST /mcp/messages HTTP/1.1 Host: localhost:3000 Content-Type: application/json { "jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {} } Response: 200 OK { "jsonrpc": "2.0", "id": 1, "result": { "tools": [...] } } ``` -------------------------------- ### Query Parameter Example Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/api-reference/extractToolsFromApi.md This example shows how query parameters are defined in OpenAPI. They are optional by default but can be made required. The 'limit' parameter with a default value of 20 is illustrated. ```yaml parameters: - name: limit in: query schema: { type: integer } required: false ``` -------------------------------- ### Web Transport Setup (SSE) Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/api-reference/generateMcpServerCode.md Sets up the MCP server to use a web transport, specifically Server-Sent Events (SSE), listening on port 3000. Includes basic error handling for server setup. ```typescript import { setupWebServer } from "./web-server.js"; async function main() { try { await setupWebServer(server, 3000); } catch (error) { console.error("Error setting up web server:", error); process.exit(1); } } ``` -------------------------------- ### Input Schema Generation Example Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/api-reference/extractToolsFromApi.md This example demonstrates the structure of the merged JSON Schema for tool inputs. It includes path parameters, query parameters (with defaults), and the request body schema. Required fields are also indicated. ```typescript { type: 'object', properties: { // Path params userId: { type: 'string' }, // Query params limit: { type: 'integer', default: 20 }, // Request body (if present) requestBody: { type: 'object', properties: { ... } } }, required: ['userId'] // Required fields } ``` -------------------------------- ### OpenAPI Specification with x-mcp Examples Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/configuration.md Demonstrates how to use the x-mcp extension at different levels (root, path, operation) in an OpenAPI 3.0 specification to control tool inclusion. ```yaml openapi: 3.0.0 info: title: Example API version: 1.0.0 x-mcp: true # Include all by default paths: /public: x-mcp: true # Included get: operationId: getPublic # Uses root setting: x-mcp: true /admin: x-mcp: false # Exclude all under /admin get: operationId: getAdminStatus x-mcp: true # But include this one specifically post: operationId: adminAction # Uses path setting: x-mcp: false /user: get: operationId: getUser # Uses root setting: x-mcp: true ``` -------------------------------- ### Environment Variable Naming Examples Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/configuration.md Illustrates how OpenAPI scheme names are converted to environment variable names, replacing special characters with underscores. ```text OpenAPI Scheme: "petstore-api-key" Env Var: API_KEY_PETSTORE_API_KEY OpenAPI Scheme: "oauth2.github" Env Var: OAUTH_CLIENT_ID_OAUTH2_GITHUB OpenAPI Scheme: "api key" Env Var: API_KEY_API_KEY ``` -------------------------------- ### Debugging Security Issues with npm Start Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/security-handling.md Pipe the output of `npm start` to `grep` to filter and view security-related log messages. This helps in identifying and troubleshooting security application issues. ```bash npm start 2>&1 | grep -i security # Output examples: # Applied API key 'api_key' in header 'X-API-Key' # Applied Bearer token for 'bearer_auth' # Attempting to acquire OAuth token for 'oauth2_petstore' # Successfully acquired OAuth2 token for 'oauth2_petstore' (expires in 3600 seconds) # Tool 'listPets' requires security: [api_key], but no suitable credentials found. ``` -------------------------------- ### Tool Name Sanitization Example Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/api-reference/extractToolsFromApi.md This example illustrates the sanitization process for tool names. Dots are replaced with underscores, and all other non-alphanumeric characters are also converted to underscores to ensure compatibility with MCP naming conventions. ```yaml operationId: "get.users.by-id" Sanitized: "get_users_by_id" ``` -------------------------------- ### Stdio Transport Setup Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/api-reference/generateMcpServerCode.md Sets up the MCP server to use the Stdio transport, which is the default. This allows communication via standard input and output. ```typescript async function main() { const transport = new StdioServerTransport(); await server.connect(transport); console.error(`server-name MCP Server (v1.0.0) running on stdio...`); } ``` -------------------------------- ### No Security Example Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/security-handling.md This YAML snippet illustrates how to explicitly define that a specific operation requires no authentication. ```yaml paths: /status: get: operationId: getStatus security: [] ``` -------------------------------- ### Template String Generation Example Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/architecture.md Illustrates the use of template strings for generating server code, emphasizing careful escaping. ```typescript return `server.setRequestHandler(...) => { // Actual code }` ``` -------------------------------- ### Stdio Client Connection Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/transport-modes.md Example of how an MCP client can connect to a server using the Stdio transport. ```APIDOC ## Stdio Client Connection ### Description Connect an MCP client to a server using the Stdio transport. ### Code Example (TypeScript) ```typescript import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; const transport = new StdioClientTransport({ command: "node", args: ["build/index.js"] }); const client = new Client({ name: "client" }, { capabilities: {} }); await client.connect(transport); ``` ``` -------------------------------- ### Conditional Transport Setup in TypeScript Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/transport-modes.md Demonstrates how to conditionally set up different server transports (Stdio, Web, StreamableHTTP) in a TypeScript application. The Stdio transport is always included, while Web and StreamableHTTP require specific imports and setup functions based on build or runtime flags. ```typescript // Stdio transport (always included in main) const transport = new StdioServerTransport(); await server.connect(transport); // OR Web transport (if --transport=web) import { setupWebServer } from "./web-server.js"; await setupWebServer(server, 3000); // OR StreamableHTTP transport (if --transport=streamable-http) import { setupStreamableHttpServer } from "./streamable-http.js"; await setupStreamableHttpServer(server, 3000); ``` -------------------------------- ### Shell Script for Generation and Build Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/cli-reference.md A bash script demonstrating a complete workflow: generating an MCP server, installing dependencies, and building the project. Includes error handling with `set -e`. ```bash #!/bin/bash set -e # Generate MCP server openapi-mcp-generator \ --input ./api-spec.json \ --output ./generated-mcp \ --server-name my-api-mcp \ --transport web \ --port 3000 # Install and build cd generated-mcp npm install npm run build echo "MCP server generated and built successfully" ``` -------------------------------- ### Event Listeners and Connection Setup Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/examples/pet-store-sse/public/index.html Sets up event listeners for sending messages via button click or Enter key press. It also initiates the connection to the server on page load and ensures the connection is closed when the page is unloaded. ```javascript // Event listeners sendButton.addEventListener('click', sendMessage); userInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') sendMessage(); }); // Connect on page load appendMessage('system', 'Connecting to server...'); connect(); // Clean up on page unload window.addEventListener('beforeunload', () => { if (eventSource) eventSource.close(); }); ``` -------------------------------- ### Advanced Filtering Examples Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/PROGRAMMATIC_API.md Demonstrates various ways to filter the extracted tools using the `filterFn` option. ```APIDOC ## Advanced Filtering Examples ### Filter by HTTP Method ```typescript const getTools = await getToolsFromOpenApi(specUrl, { filterFn: (tool) => tool.method.toLowerCase() === 'get', }); ``` ### Filter by Security Requirements ```typescript const secureTools = await getToolsFromOpenApi(specUrl, { filterFn: (tool) => tool.securityRequirements.length > 0, }); ``` ### Filter by Path Pattern ```typescript const userTools = await getToolsFromOpenApi(specUrl, { filterFn: (tool) => tool.pathTemplate.includes('/user'), }); ``` ### Combining Multiple Filters ```typescript const safeUserTools = await getToolsFromOpenApi(specUrl, { excludeOperationIds: ['deleteUser', 'updateUser'], filterFn: (tool) => tool.pathTemplate.includes('/user') && tool.method.toLowerCase() === 'get', }); ``` ``` -------------------------------- ### Generate MCP Server Code Example Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/api-reference/generateMcpServerCode.md Demonstrates generating server code using `generateMcpServerCode` with SwaggerParser to dereference an OpenAPI spec. The generated code is then written to a file. ```typescript import SwaggerParser from '@apidevtools/swagger-parser'; import { generateMcpServerCode } from 'openapi-mcp-generator'; const api = await SwaggerParser.dereference('./petstore.json'); const serverCode = generateMcpServerCode( api, { input: './petstore.json', output: './petstore-mcp', transport: 'stdio' }, 'petstore-mcp-server', '1.0.0' ); // Write to file fs.writeFileSync('./src/index.ts', serverCode); ``` -------------------------------- ### Security Requirement Logic (OR/AND) Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/security-handling.md This YAML example illustrates the security requirement evaluation logic where requirements are evaluated with OR between them and AND within each requirement. ```yaml security: - api_key: [] # Requirement 1: api_key - oauth2: [read:pets] # Requirement 2: oauth2 with read:pets scope ``` -------------------------------- ### Display Version Information Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/cli-reference.md Show the currently installed version of the OpenAPI MCP Generator. This is useful for checking compatibility or reporting issues. ```bash openapi-mcp-generator --version ``` -------------------------------- ### Generate OAuth2 Documentation Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/api-reference/generator-functions.md Generates `docs/oauth2-configuration.md` with OAuth2 setup instructions. This function only creates the file if OAuth2 schemes are present in the OpenAPI specification. ```typescript export function generateOAuth2Docs( securitySchemes?: OpenAPIV3.ComponentsObject['securitySchemes'] ): string ``` -------------------------------- ### Example Output Messages Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/cli-reference.md Illustrates the typical status messages printed to stderr upon successful generation, including parsing, generation steps, and next steps. ```text Parsing OpenAPI spec: ./petstore.json OpenAPI spec parsed successfully. Generating server code... Generating package.json... ... MCP server project 'petstore-mcp' successfully generated at: ./out Next steps: 1. Navigate to the directory: cd ./out 2. Install dependencies: npm install 3. Build the TypeScript code: npm run build 4. Run the server: npm start ``` -------------------------------- ### Verify Node.js Version Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/configuration.md Check if your Node.js installation meets the requirement of v20 or later. The generated server requires Node.js v20 or higher to function correctly. ```bash node --version # Should output v20.x.x or higher ``` -------------------------------- ### Error Handling Example Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/api-reference/getToolsFromOpenApi.md Illustrates how to catch errors thrown by getToolsFromOpenApi during parsing or extraction using a try-catch block. ```typescript try { const tools = await getToolsFromOpenApi('./spec.json'); } catch (error) { // Error: Failed to extract tools from OpenAPI: {original message} // The error has a 'cause' property containing the original error } ``` -------------------------------- ### StreamableHTTP Session Management Example Flow Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/transport-modes.md Illustrates the client-side JavaScript flow for managing sessions with StreamableHTTP. It shows how to obtain a session ID from the first response and use it in subsequent requests. ```javascript // Request 1: Initialize session const resp1 = await fetch('http://localhost:3000/mcp', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }) }); const sessionId = resp1.headers.get('X-MCP-Session'); // "session-abc123" // Request 2: Use existing session const resp2 = await fetch('http://localhost:3000/mcp', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-MCP-Session': sessionId // Include session }, body: JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: {...} }) }); ``` -------------------------------- ### Environment Variable Naming Convention Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/security-handling.md Examples of how security scheme names are converted into environment variable names, following specific rules for uppercase conversion and special character replacement. ```text Scheme: "petstore-api-key" Variable: API_KEY_PETSTORE_API_KEY Scheme: "oauth2.github" Variable: OAUTH_CLIENT_ID_OAUTH2_GITHUB Scheme: "api_key" Variable: API_KEY_API_KEY ``` -------------------------------- ### Tool Name Generation from Method and Path Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/api-reference/extractToolsFromApi.md If 'operationId' is not present, the tool name is generated from the HTTP method and the path. For example, 'GET /users/{userId}/posts' becomes 'GetUsersPosts'. If the last path parameter is an ID, 'By' is appended, as in 'DELETE /items/{id}' becoming 'DeleteItemsById'. ```text Method: GET Path: /users/{userId}/posts Generated: GetUsersPosts (if no operationId) Method: DELETE Path: /items/{id} Generated: DeleteItemsById (appends "By" for final path param) ``` -------------------------------- ### Generated .env.example Template Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/security-handling.md This bash snippet shows a template for a `.env.example` file generated by the tool, including placeholders for various security scheme credentials. ```bash # For a spec with API key, Bearer, OAuth2 # API Configuration API_BASE_URL=https://api.example.com # Security: API Key API_KEY_API_KEY=your-api-key-here # Security: Bearer Token BEARER_TOKEN_BEARER_AUTH=your-bearer-token-here # Security: OAuth2 OAUTH_CLIENT_ID_OAUTH2_PETSTORE=your-client-id OAUTH_CLIENT_SECRET_OAUTH2_PETSTORE=your-client-secret OAUTH_SCOPES_OAUTH2_PETSTORE=read:pets write:pets OAUTH_TOKEN_OAUTH2_PETSTORE=your-pre-acquired-token-optional # Security: Basic Auth BASIC_USERNAME_BASIC_AUTH=username BASIC_PASSWORD_BASIC_AUTH=password ``` -------------------------------- ### Display Help Information Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/cli-reference.md Show all available command-line options and their descriptions. This is useful for discovering available commands and their parameters. ```bash openapi-mcp-generator --help ``` ```bash openapi-mcp-generator -h ``` -------------------------------- ### Generate .env.example File Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/api-reference/generator-functions.md Generates a `.env.example` file to document required environment variables. It includes placeholders for API base URL and various security credentials based on the provided OpenAPI security schemes. ```typescript export function generateEnvExample( securitySchemes?: OpenAPIV3.ComponentsObject['securitySchemes'] ): string ``` -------------------------------- ### Troubleshoot: Missing Security Credentials Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/README.md Steps to resolve missing security credentials at runtime. This involves checking the .env file, copying a template if it doesn't exist, filling in credentials, and restarting the server. ```bash # Check .env file cat .env # Copy template cp .env.example .env # Fill in credentials # Then restart server npm start ``` -------------------------------- ### Specify Output Directory Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/cli-reference.md Use the --output or -o flag to define the directory where the generated MCP server project will be created. The directory must not exist unless --force is used. ```bash openapi-mcp-generator --input spec.json --output ./petstore-mcp ``` ```bash openapi-mcp-generator -i spec.json -o ../generated-servers/my-api ``` ```bash openapi-mcp-generator --input spec.json --output /absolute/path/to/server ``` -------------------------------- ### Custom Tool Filtering Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/architecture.md Example of how to apply custom filtering logic when retrieving tools from an OpenAPI specification. ```typescript const tools = await getToolsFromOpenApi(spec, { filterFn: (tool) => /* custom logic */ }); ``` -------------------------------- ### Client Implementation with WebSockets Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/transport-modes.md Demonstrates how to connect a client using the WebClientTransport. Ensure the server is running and accessible at the specified URL. ```typescript import { WebClientTransport } from "@modelcontextprotocol/sdk/client/web.js"; const transport = new WebClientTransport({ url: "http://localhost:3000" }); const client = new Client({ name: "client" }, { capabilities: {} }); await client.connect(transport); // Use client normally const tools = await client.listTools(); const result = await client.callTool("listPets", { limit: 10 }); ``` -------------------------------- ### List Available Tools Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/examples/pet-store-streamable-http/public/index.html Fetches the list of available tools from the server using the 'listTools' method. Requires an active session ID and makes a POST request to '/mcp'. ```javascript async function listTools() { try { const requestBody = { jsonrpc: '2.0', id: messageId++, method: 'listTools', params: {}, }; log('REQUEST', JSON.stringify(requestBody)); const response = await fetch('http://localhost:3000/mcp', { method: 'POST', headers: { 'Content-Type': 'application/json', 'mcp-session-id': sessionId, }, body: JSON.stringify(requestBody), }); if (!response.ok) { const errorText = await response.text(); log( 'ERROR', `Error listing tools: ${response.status} ${response.statusText} ${errorText}` ); return; } const data = await response.json(); log('TOOLS', JSON.stringify(data)); if (data.result?.tools && Array.isArray(data.result.tools)) { appendMessage( 'system', `Available tools: ${data.result.tools.map((t) => t.name).join(', ')}` ); } } catch (error) { log('ERROR', `Error listing tools: ${error.message}`); } } ``` -------------------------------- ### Set Basic Authentication Environment Variables Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/configuration.md Configures basic authentication for the generated MCP server by setting BASIC_USERNAME_ and BASIC_PASSWORD_ environment variables. ```bash export BASIC_USERNAME_MYAPI=user@example.com export BASIC_PASSWORD_MYAPI=secure_password_123 npm start ``` -------------------------------- ### Troubleshoot: Output Directory Exists Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/README.md Use these commands to either specify a new output directory or force overwrite an existing one when encountering the 'Output directory already exists' error. ```bash # Option 1: Choose different directory openapi-mcp-generator --input spec.json --output ./new-dir # Option 2: Force overwrite openapi-mcp-generator --input spec.json --output ./existing --force ``` -------------------------------- ### Basic CLI Invocation Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/cli-reference.md The tool can be invoked directly or using npx. ```bash openapi-mcp-generator [OPTIONS] ``` -------------------------------- ### CLI Layer Orchestration Flow Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/architecture.md Illustrates the main steps executed by the CLI entry point when running the generator. ```text CLI Layer (index.ts) ↓ Parser Layer (parser/extract-tools.ts) ↓ Code Generation Layer (generator/*) ↓ Output (filesystem) ↓ Generated Project (executable MCP server) ``` -------------------------------- ### Global Security Example Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/security-handling.md This YAML snippet shows how to define a security requirement that applies to all operations in an OpenAPI specification, unless explicitly overridden at the operation level. ```yaml security: - api_key: [] ``` -------------------------------- ### Runtime Security Flow Diagram Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/security-handling.md This text outlines the step-by-step process of how the generated server applies security requirements when a tool is invoked, from argument validation to HTTP request execution. ```text 1. User calls tool with arguments ↓ 2. Arguments validated with Zod schema ↓ 3. Path/query/header parameters extracted ↓ 4. Security requirements evaluated ↓ 5. First matching requirement found ↓ 6. For each security scheme in requirement: a. Check if credentials available in environment b. If API key → add to header/query/cookie c. If Bearer → add to Authorization header d. If Basic → encode and add to Authorization header e. If OAuth2 → acquire or use cached token, add to Authorization header f. If OpenID → add token to Authorization header ↓ 7. HTTP request executed with applied security ↓ 8. Response returned to MCP client ``` -------------------------------- ### Operation-Level Security Example Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/security-handling.md This YAML snippet demonstrates how to define security requirements for a specific operation in an OpenAPI specification. It allows overriding global security settings. ```yaml paths: /pets: get: operationId: listPets security: - api_key: [] - bearer_auth: [] ``` -------------------------------- ### Basic Stdio Generation CLI Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/configuration.md Generates an MCP server project using stdio transport with input and output paths specified. ```bash openapi-mcp-generator --input ./petstore.json --output ./petstore-mcp-server ``` -------------------------------- ### StreamableHTTP POST /mcp Response Format Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/transport-modes.md Example of a successful JSON-RPC response from the /mcp endpoint using StreamableHTTP. The X-MCP-Session header is returned for maintaining the session. ```http HTTP/1.1 200 OK Content-Type: application/json X-MCP-Session: session-id-abc123 { "jsonrpc": "2.0", "id": 1, "result": { "tools": [...] } } ``` -------------------------------- ### StreamableHTTP POST /mcp Request Format Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/transport-modes.md Example of a JSON-RPC request sent to the /mcp endpoint using StreamableHTTP. Note the required Content-Type and optional X-MCP-Session headers. ```http POST /mcp HTTP/1.1 Host: localhost:3000 Content-Type: application/json X-MCP-Session: session-id-abc123 # (required for requests after init) { "jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {} } ``` -------------------------------- ### Set Server Version Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/cli-reference.md Use the --server-version or -v flag to set the semantic version for the generated server, used in package.json. ```bash openapi-mcp-generator --input spec.json --output ./out --server-version 2.0.0 ``` ```bash openapi-mcp-generator -i spec.json -o ./out -v 1.2.3-rc1 ``` -------------------------------- ### Header Parameter Example Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/api-reference/extractToolsFromApi.md Header parameters, though less common, are supported. This snippet shows the structure for defining a custom header parameter, 'X-Custom-Header', with a string schema. ```yaml parameters: - name: X-Custom-Header in: header schema: { type: string } ``` -------------------------------- ### Tool Name Generation from operationId Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/api-reference/extractToolsFromApi.md When an operation has an 'operationId', it is used as the base for the tool name and sanitized to be MCP-compatible. This example shows a valid 'operationId' that remains unchanged after sanitization. ```yaml operationId: listPetsV2 # Generated tool name: listPetsV2 → sanitized to: listPetsV2 (valid) ``` -------------------------------- ### Generate Stdio Server from Local Spec Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/cli-reference.md Generates a server project from a local OpenAPI specification file. Specifies input, output directory, server name, and version. ```bash openapi-mcp-generator \ --input ./apis/petstore-openapi.json \ --output ./servers/petstore-mcp \ --server-name petstore-mcp \ --server-version 1.0.0 ``` -------------------------------- ### generateMcpServerCode Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/INDEX.md Generates server code based on the MCP tool definition. This includes details on the generated code structure, request handlers, security code generation, and transport-specific setup. ```APIDOC ## generateMcpServerCode ### Description Generates server code for MCP applications based on provided tool definitions. This function creates the necessary files and logic for handling API requests. ### Function Signature (Details not provided in source) ### Generated Code Structure - 11 distinct components are generated. ### Request Handlers - Supports `ListTools` and `CallTool` operations. ### Security Code Generation - Generates code for handling various security schemes. ### Transport-Specific Setup - Includes setup for stdio, web (SSE), and streamable-http transports. ### Error Handling - Provides utility functions for error formatting (e.g., `formatApiError`). ``` -------------------------------- ### Web Server Generation CLI Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/configuration.md Generates an MCP server project for web transport, specifying port, server name, and version. ```bash openapi-mcp-generator \ --input https://petstore3.swagger.io/api/v3/openapi.json \ --output ./petstore-web \ --transport=web \ --port=8080 \ --server-name petstore-api \ --server-version 2.0.0 ``` -------------------------------- ### Set OpenID Connect Token Environment Variable Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/configuration.md Configures OpenID Connect authentication for the generated MCP server by setting the OPENID_TOKEN_ environment variable. ```bash export OPENID_TOKEN_MYSERVICE=id_token_abc123 npm start ``` -------------------------------- ### Generate Web Server Code Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/api-reference/generator-functions.md Generates `src/web-server.ts` for SSE-based transport. This includes Hono HTTP server setup, SSE endpoint, JSON-RPC routing, session management, CORS, and static file serving. ```typescript export function generateWebServerCode( port: number ): string ``` -------------------------------- ### Generate Streamable HTTP Code Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/api-reference/generator-functions.md Generates `src/streamable-http.ts` for StreamableHTTP transport. This includes Hono HTTP server setup, stateful HTTP POST endpoints, session management via headers, JSON-RPC handling, and CORS. ```typescript export function generateStreamableHttpCode( port: number ): string ``` -------------------------------- ### Security Handling Flow Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/architecture.md Describes the step-by-step process of handling security requirements for tool invocations in the generated server. ```text Tool invoked with arguments ↓ Validate against input schema (Zod) ↓ Extract and apply parameters (path, query, header) ↓ Check security requirements ↓ For each required security scheme: ├─ API Key → add to header/query/cookie ├─ Bearer → add to Authorization header ├─ Basic → encode and add to Authorization header ├─ OAuth2 → acquire token (or use cached), add to Authorization header └─ OpenID → add token to Authorization header ↓ Execute HTTP request with axios ↓ Format response (JSON/text/empty) ↓ Return to MCP client ``` -------------------------------- ### Request Body Processing Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/api-reference/extractToolsFromApi.md The request body is processed from the 'operation.requestBody' field. This example shows a required request body with JSON content, including its schema definition. The input schema generated will include a 'requestBody' field corresponding to this schema. ```yaml requestBody: required: true content: application/json: schema: { type: object, properties: { ... } } ``` -------------------------------- ### Generate MCP web server with SSE Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/README.md Generate an MCP server with web transport using Server-Sent Events (SSE). Specify the port for the server. ```bash openapi-mcp-generator --input path/to/openapi.json --output path/to/output/dir --transport=web --port=3000 ``` -------------------------------- ### OpenAPI Spec with Multiple Security Schemes Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/security-handling.md Define multiple security schemes (apiKey, oauth2, bearer) in the components section and apply them globally or per-path. This example shows global application of 'api_key' or 'oauth2' for '/pets' and a specific 'oauth2' scope for '/admin/pets'. ```yaml openapi: 3.0.0 info: title: Pet Store API version: 1.0.0 components: securitySchemes: api_key: type: apiKey name: X-API-Key in: header oauth2: type: oauth2 flows: clientCredentials: tokenUrl: https://auth.example.com/token scopes: read:pets: Read pets write:pets: Write pets bearer: type: http scheme: bearer security: - api_key: [] - oauth2: [read:pets] paths: /pets: get: operationId: listPets # Uses global security (api_key OR oauth2) /admin/pets: post: operationId: createPet security: - oauth2: [write:pets] # Override: requires oauth2 with write:pets scope ``` -------------------------------- ### Environment Variables for Security Credentials Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/README.md Credentials for various authentication methods are loaded at runtime from environment variables. Ensure these variables are set correctly for the chosen authentication method. ```bash API_KEY_MYAPI=sk-123456 BEARER_TOKEN_OAUTH2=eyJ... BASIC_USERNAME_AUTH=user BASIC_PASSWORD_AUTH=pass OAUTH_CLIENT_ID_OAUTH2=client_id OAUTH_CLIENT_SECRET_OAUTH2=secret ``` -------------------------------- ### Specify Input OpenAPI File Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/cli-reference.md Use the --input or -i flag to specify the path to a local OpenAPI file or a URL to a remote specification. ```bash openapi-mcp-generator --input ./petstore.json --output ./out ``` ```bash openapi-mcp-generator -i /path/to/api-spec.yaml -o ./generated ``` ```bash openapi-mcp-generator --input https://petstore3.swagger.io/api/v3/openapi.json --output ./out ``` -------------------------------- ### Environment Variables for Generated Server Configuration Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/README.md The generated server can be configured using environment variables. These variables allow overriding settings like the API base URL and providing credentials for various authentication methods. ```bash API_BASE_URL=https://api.example.com # Override API base URL API_KEY_*=... # API key credentials BEARER_TOKEN_*=... # Bearer token BASIC_USERNAME_*, BASIC_PASSWORD_*=... # Basic auth OAUTH_CLIENT_ID_*, OAUTH_CLIENT_SECRET_*=... # OAuth2 OAUTH_SCOPES_*, OAUTH_TOKEN_*=... # OAuth2 options OPENID_TOKEN_*=... # OpenID Connect ``` -------------------------------- ### Secure .env File Configuration Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/security-handling.md Ensure your .env file is secure by adding it to .gitignore and restricting file permissions to the owner. This prevents accidental exposure of credentials. ```bash # Add to .gitignore echo ".env" >> .gitignore chmod 600 .env # Restrict to owner ``` -------------------------------- ### Generate MCP server (stdio transport) Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/README.md Generate an MCP server using the default stdio transport. Requires input OpenAPI spec and output directory. ```bash openapi-mcp-generator --input path/to/openapi.json --output path/to/output/dir ``` -------------------------------- ### Generated Server Directory Structure Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/README.md Illustrates the typical directory structure of a server generated by the openapi-mcp-generator. It includes main server files, optional transport-specific files, configuration, and documentation. ```bash / ├── src/ │ ├── index.ts # Main MCP server │ ├── web-server.ts # (optional) Web/SSE transport │ └── streamable-http.ts # (optional) StreamableHTTP transport ├── public/ │ └── index.html # (optional) Browser test client ├── package.json # Node.js dependencies ├── tsconfig.json # TypeScript config ├── .env.example # Environment variable template └── docs/ └── oauth2-configuration.md # (optional) OAuth2 setup guide ``` -------------------------------- ### Basic Authentication Runtime Implementation Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/security-handling.md Applies basic authentication at runtime using BASIC_USERNAME_ and BASIC_PASSWORD_ environment variables. Encodes credentials in base64. ```typescript const username = process.env.BASIC_USERNAME_BASIC_AUTH; const password = process.env.BASIC_PASSWORD_BASIC_AUTH; if (username && password) { const credentials = Buffer.from(`${username}:${password}`).toString('base64'); headers['authorization'] = `Basic ${credentials}`; } ``` -------------------------------- ### Client Implementation with StreamableHTTP Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/transport-modes.md Shows how to connect a client using the StreamableHTTPClientTransport. The URL should point to the /mcp endpoint of your StreamableHTTP server. ```typescript import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/http.js"; const transport = new StreamableHTTPClientTransport({ url: "http://localhost:3000/mcp" }); const client = new Client({ name: "client" }, { capabilities: {} }); await client.connect(transport); // Use client normally const tools = await client.listTools(); const result = await client.callTool("listPets", { limit: 10 }); ``` -------------------------------- ### Generate StreamableHTTP Server with Custom Base URL Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/cli-reference.md Generates a server using the `streamable-http` transport, allowing for custom base URLs and ports. Includes server versioning. ```bash openapi-mcp-generator \ --input ./spec.yaml \ --output ./mcp-server-stateless \ --transport streamable-http \ --base-url https://api.production.example.com \ --port 8080 \ --server-version 2.0.0 ``` -------------------------------- ### StreamableHTTP Server Generation CLI Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/configuration.md Generates an MCP server project using streamable-http transport, overriding the base URL and specifying a port. ```bash openapi-mcp-generator \ --input ./api-spec.yaml \ --output ./mcp-server \ --transport=streamable-http \ --base-url https://api.production.example.com \ --port 4000 ``` -------------------------------- ### Combine Multiple getToolsFromOpenApi Options Source: https://github.com/harsha-iiiv/openapi-mcp-generator/blob/main/_autodocs/api-reference/getToolsFromOpenApi.md Demonstrates using multiple options simultaneously, including baseUrl, dereference, excludeOperationIds, and a custom filterFn. ```typescript const tools = await getToolsFromOpenApi('spec.json', { baseUrl: 'https://api.example.com', dereference: true, excludeOperationIds: ['adminOnly'], filterFn: (tool) => tool.pathTemplate.includes('/user') && tool.method.toLowerCase() === 'get' }); ```