API Reference
Complete API reference including TypeScript interfaces, method signatures, and library usage patterns.
Package Exports
The OpenAPI MCP Server exports a comprehensive set of classes, interfaces, and utilities for building custom MCP servers:
🏗️ Core Classes
import {
OpenAPIServer, // Main server implementation
validateConfig, // Configuration validation
DEFAULT_CONFIG // Default configuration values
} from "@lucid-spark/openapi-mcp-server";
🔐 Authentication
import {
StaticAuthProvider, // Static header authentication
isAuthError // Authentication error detection
} from "@lucid-spark/openapi-mcp-server";
🛠️ Tool Management
import {
createToolFromOperation, // Create tools from OpenAPI operations
createMetaTools, // Create meta-tools for API exploration
ToolsManager // Tool filtering and management
} from "@lucid-spark/openapi-mcp-server";
🔧 Utilities
import {
generateToolId, // Generate tool IDs
parseToolId, // Parse tool IDs
generateToolName, // Generate tool names
ApiClient, // HTTP client for API requests
logger // Logging utilities
} from "@lucid-spark/openapi-mcp-server";
OpenAPIServer Class
The main server class that orchestrates OpenAPI specification loading, tool generation, and MCP protocol communication.
Constructor
class OpenAPIServer {
constructor(config: IOpenAPIServerConfig)
}
Creates a new OpenAPI MCP Server instance with the provided configuration.
| Parameter | Type | Description |
|---|---|---|
config |
IOpenAPIServerConfig |
Server configuration object |
Methods
start()
async start(): Promise
Starts the MCP server, initializes transport, loads OpenAPI specification, and generates tools.
Returns: Promise that resolves when server is ready
Throws: Error if configuration is invalid or server fails to start
stop()
async stop(): Promise
Gracefully stops the MCP server and cleans up resources.
getStats()
getStats(): ServerStats
Returns server statistics including tool counts and OpenAPI information.
interface ServerStats {
tools: {
total: number;
endpointTools: number;
metaTools: number;
};
openapi: {
version: string;
paths: number;
operations: number;
};
filtering?: {
applied: boolean;
includedTags?: string[];
includedOperations?: string[];
};
}
testConnection()
async testConnection(): Promise
Tests connectivity to the configured API endpoint.
Returns: Promise resolving to true if connection successful
Configuration Interface
The complete TypeScript interface for server configuration:
interface IOpenAPIServerConfig {
// Required Configuration
apiBaseUrl: string; // Base URL for API endpoints
// OpenAPI Specification
openApiSpec?: string; // Path, URL, or inline content
specInputMethod?: SpecInputMethod; // 'url' | 'file' | 'stdin' | 'inline'
// Server Identity
name?: string; // Server name (default: 'openapi-mcp-server')
version?: string; // Server version (default: '1.0.0')
namespace?: string; // Namespace for the MCP server tools
// Authentication (choose one)
headers?: Record; // Static headers
authProvider?: IAuthProvider; // Dynamic authentication
// Transport Configuration
transportType?: TransportType; // 'stdio' | 'http' (default: 'stdio')
httpPort?: number; // HTTP port (default: 3000)
httpHost?: string; // HTTP host (default: '127.0.0.1')
endpointPath?: string; // HTTP endpoint (default: '/mcp')
// Tool Management
toolsMode?: ToolsMode; // 'all' | 'dynamic' | 'explicit'
includeTools?: string[]; // Specific tools to include
includeTags?: string[]; // OpenAPI tags to include
includeResources?: string[]; // Resource paths to include
includeOperations?: string[]; // HTTP methods to include
// Options
disableAbbreviation?: boolean; // Disable tool name abbreviation
debug?: boolean; // Enable debug logging
}
Related Types
type SpecInputMethod = 'url' | 'file' | 'stdin' | 'inline';
type TransportType = 'stdio' | 'http';
type ToolsMode = 'all' | 'dynamic' | 'explicit';
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
Authentication Interfaces
IAuthProvider Interface
interface IAuthProvider {
/**
* Get authentication headers for the current request
* Called before each API request to get fresh headers
*/
getAuthHeaders(): Promise>;
/**
* Handle authentication errors from API responses
* Called when the API returns 401 or 403 errors
* Return true to retry the request, false otherwise
*/
handleAuthError(error: AxiosError): Promise;
}
StaticAuthProvider Class
class StaticAuthProvider implements IAuthProvider {
constructor(headers: Record);
async getAuthHeaders(): Promise>;
async handleAuthError(error: AxiosError): Promise;
}
A built-in implementation for static header authentication.
Authentication Utilities
/**
* Check if an error is authentication-related
*/
function isAuthError(error: any): boolean;
// Usage example
try {
await apiRequest();
} catch (error) {
if (isAuthError(error)) {
// Handle authentication failure
await refreshToken();
}
}
Tool Management APIs
Tool Creation Functions
createToolFromOperation
function createToolFromOperation(
path: string,
method: string,
operation: IOperation,
disableAbbreviation?: boolean
): ITool;
Creates an MCP tool from an OpenAPI operation.
| Parameter | Type | Description |
|---|---|---|
path |
string |
OpenAPI path (e.g., "/users/{id}") |
method |
string |
HTTP method (GET, POST, etc.) |
operation |
IOperation |
OpenAPI operation object |
disableAbbreviation |
boolean |
Skip name abbreviation (optional) |
createMetaTools
function createMetaTools(): ITool[];
Creates the three built-in meta-tools for API exploration.
Returns: Array containing:
list-api-endpoints- List available endpointsget-api-endpoint-schema- Get endpoint schemainvoke-api-endpoint- Invoke endpoint dynamically
ToolsManager Class
class ToolsManager {
constructor(config: IToolsFilter, openApiSpec: any);
generateTools(disableAbbreviation?: boolean): ITool[];
filterTools(tools: ITool[]): ITool[];
getToolById(toolId: string): ITool | undefined;
getStats(): ToolsStats;
}
Manages tool generation and filtering from OpenAPI specifications.
Tool Utility Functions
Tool ID Functions
generateToolId(method: string, path: string): string;
parseToolId(toolId: string): { method: string; path: string };
isValidToolId(toolId: string): boolean;
Tool Name Functions
generateToolName(input: string, disableAbbreviation?: boolean): string;
isValidToolName(name: string): boolean;
Validation Functions
isValidHttpMethod(method: string): method is HttpMethod;
extractResourceName(path: string): string | undefined;
Constants
const HTTP_METHODS: HttpMethod[];
// ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']
Type Definitions
Core Types
ITool Interface
interface ITool {
name: string; // Tool name (≤64 chars, [a-z0-9-]+)
description: string; // Human-readable description
inputSchema: any; // JSON schema for input parameters
tags?: string[]; // OpenAPI tags
method: string; // HTTP method
resourceName?: string; // Extracted resource name
toolId: string; // Unique tool identifier
}
IOperation Interface
interface IOperation {
operationId?: string; // OpenAPI operation ID
summary?: string; // Operation summary
description?: string; // Operation description
tags?: string[]; // OpenAPI tags
parameters?: IParameter[]; // Operation parameters
requestBody?: any; // Request body schema
responses?: any; // Response schemas
security?: any[]; // Security requirements
}
IParameter Interface
interface IParameter {
name: string; // Parameter name
in: 'path' | 'query' | 'header' | 'cookie'; // Parameter location
required?: boolean; // Whether parameter is required
schema?: any; // Parameter schema
description?: string; // Parameter description
}
Transport Types
interface ITransportConfig {
transportType: TransportType;
httpPort?: number;
httpHost?: string;
endpointPath?: string;
}
abstract class BaseTransportHandler {
constructor(server: Server);
abstract start(): Promise;
abstract stop(): Promise;
}
Filter Types
interface IToolsFilter {
toolsMode: ToolsMode;
includeTools?: string[];
includeTags?: string[];
includeResources?: string[];
includeOperations?: string[];
}
ApiClient Class
HTTP client for making authenticated requests to OpenAPI endpoints.
Constructor
class ApiClient {
constructor(
baseUrl: string,
authProvider?: IAuthProvider,
headers?: Record
);
}
Methods
request()
async request(
method: HttpMethod,
path: string,
params?: Record,
headers?: Record
): Promise;
Makes an authenticated HTTP request to the specified endpoint.
testConnection()
async testConnection(): Promise;
Tests connectivity to the base URL.
Configuration Validation
validateConfig Function
function validateConfig(config: IOpenAPIServerConfig): IOpenAPIServerConfig;
Validates and normalizes server configuration, applying defaults where needed.
Returns: Validated configuration object
Throws: Error if configuration is invalid
Usage Example
import { validateConfig } from "@lucid-spark/openapi-mcp-server";
try {
const config = validateConfig({
apiBaseUrl: "https://api.example.com",
openApiSpec: "./api-spec.yaml",
transportType: "stdio"
});
console.log("Configuration is valid:", config);
} catch (error) {
console.error("Configuration error:", error.message);
}
DEFAULT_CONFIG Constant
const DEFAULT_CONFIG: Partial = {
name: "openapi-mcp-server",
version: "1.0.0",
specInputMethod: "url",
transportType: "stdio",
httpPort: 3000,
httpHost: "127.0.0.1",
endpointPath: "/mcp",
toolsMode: "all",
disableAbbreviation: false,
debug: false
};
Error Handling
Common Error Types
Configuration Errors
Thrown when configuration validation fails
// Missing required apiBaseUrl
throw new Error("apiBaseUrl is required");
// Invalid transport type
throw new Error("transportType must be 'stdio' or 'http'");
OpenAPI Loading Errors
Thrown when OpenAPI specification cannot be loaded
// File not found
throw new Error("OpenAPI spec file not found: ./api-spec.yaml");
// Invalid JSON/YAML
throw new Error("Invalid OpenAPI specification format");
Authentication Errors
Thrown when API authentication fails
// Token expired
throw new Error("Authentication token expired");
// Invalid credentials
throw new Error("API authentication failed: Invalid credentials");
Network Errors
Thrown when network requests fail
// Connection refused
throw new Error("Connection refused: Check API endpoint");
// Timeout
throw new Error("Request timeout: API did not respond");
Error Handling Best Practices
import { OpenAPIServer, isAuthError } from "@lucid-spark/openapi-mcp-server";
async function startServer() {
try {
const server = new OpenAPIServer(config);
await server.start();
console.log("Server started successfully");
} catch (error) {
if (error.message.includes("apiBaseUrl")) {
console.error("Configuration error:", error.message);
} else if (error.message.includes("OpenAPI")) {
console.error("Specification error:", error.message);
} else if (isAuthError(error)) {
console.error("Authentication error:", error.message);
} else {
console.error("Unexpected error:", error.message);
}
process.exit(1);
}
}
Complete API Examples
Basic Server Setup
import { OpenAPIServer, validateConfig } from "@lucid-spark/openapi-mcp-server";
async function createBasicServer() {
const config = validateConfig({
apiBaseUrl: "https://api.example.com",
openApiSpec: "https://api.example.com/openapi.json",
headers: {
"Authorization": "Bearer your-token",
"Accept": "application/json"
}
});
const server = new OpenAPIServer(config);
// Start server
await server.start();
// Get statistics
const stats = server.getStats();
console.log(`Server running with ${stats.tools.total} tools`);
// Test API connection
const connected = await server.testConnection();
console.log(`API connection: ${connected ? 'OK' : 'Failed'}`);
}
Custom Authentication Provider
import { OpenAPIServer, IAuthProvider } from "@lucid-spark/openapi-mcp-server";
import { AxiosError } from "axios";
class OAuth2AuthProvider implements IAuthProvider {
private accessToken: string;
private refreshToken: string;
private tokenExpiry: Date;
constructor(accessToken: string, refreshToken: string, expiresIn: number) {
this.accessToken = accessToken;
this.refreshToken = refreshToken;
this.tokenExpiry = new Date(Date.now() + expiresIn * 1000);
}
async getAuthHeaders(): Promise> {
if (this.isTokenExpiring()) {
await this.refreshAccessToken();
}
return {
Authorization: `Bearer ${this.accessToken}`
};
}
async handleAuthError(error: AxiosError): Promise {
if (error.response?.status === 401) {
try {
await this.refreshAccessToken();
return true; // Retry request
} catch (refreshError) {
throw new Error("Token refresh failed");
}
}
return false;
}
private isTokenExpiring(): boolean {
const bufferTime = 60 * 1000; // 60 seconds
return this.tokenExpiry.getTime() <= (Date.now() + bufferTime);
}
private async refreshAccessToken(): Promise {
// Implementation depends on your OAuth provider
const response = await fetch("https://oauth.example.com/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "refresh_token",
refresh_token: this.refreshToken
})
});
const data = await response.json();
this.accessToken = data.access_token;
this.refreshToken = data.refresh_token || this.refreshToken;
this.tokenExpiry = new Date(Date.now() + data.expires_in * 1000);
}
}
// Usage
const authProvider = new OAuth2AuthProvider(
"access_token",
"refresh_token",
3600
);
const server = new OpenAPIServer({
apiBaseUrl: "https://api.example.com",
openApiSpec: "./api-spec.yaml",
authProvider: authProvider
});
Tool Management
import {
generateToolId,
parseToolId,
generateToolName,
createToolFromOperation
} from "@lucid-spark/openapi-mcp-server";
// Generate tool ID
const toolId = generateToolId("GET", "/users/{id}");
console.log(toolId); // "GET::users__---id"
// Parse tool ID
const { method, path } = parseToolId(toolId);
console.log(method, path); // "GET", "/users/{id}"
// Generate tool name
const toolName = generateToolName("getUserDetailsByIdentifier");
console.log(toolName); // "get-usr-dtls-by-idntfr"
// Create tool from OpenAPI operation
const operation = {
operationId: "getUser",
summary: "Get user by ID",
parameters: [
{
name: "id",
in: "path",
required: true,
schema: { type: "string" }
}
]
};
const tool = createToolFromOperation("/users/{id}", "GET", operation);
console.log(tool.name); // "get-user"