MCP OpenAPI Server

repository·main·Indexed 43 days ago

https://github.com/ivo-toby/mcp-openapi-server

An MCP (Model Context Protocol) server that automatically converts OpenAPI specifications into MCP tools, prompts, and resources, enabling LLMs to interact with REST APIs. It provides a library and CLI for creating servers, featuring a flexible AuthProvider interface with implementations like RefreshableAuthProvider, ManualTokenAuthProvider, and ApiKeyAuthProvider to handle complex authentication scenarios including OAuth2 token refresh and manual token updates.

Tokens
42.1K
Snippets
106
Records
165
Agent score
53%

What's inside mcp-openapi-server

  1. What is the AuthProvider interface and when to use it

    main

    The AuthProvider interface in @ivotoby/openapi-mcp-server is used to handle complex authentication scenarios that static headers cannot address. Use it when your target API requires more than a fixed string in a header, such as:

    • Token Expiration: Automatically detecting and handling expired tokens.
    • Token Refresh: Automatically refreshing tokens (e.g., OAuth2) before they expire.
    • Manual Token Updates: Handling APIs that require manual renewal (e.g., copying a token from browser dev tools).
    • API Key Management: Managing API keys with specific validation logic.
    • Custom Authentication: Implementing any proprietary authentication pattern.

    By using an AuthProvider, headers are fetched fresh for each request, allowing for runtime token updates and automatic detection of 401/403 errors.

  2. What is the Model Context Protocol (MCP)?

    main

    The Model Context Protocol (MCP) is a standardized way for applications to provide context to Large Language Models (LLMs). It separates the concern of context provision from the LLM interaction itself.

    Key capabilities provided by the SDK include:

    • Clients: Connect to any MCP server.
    • Servers: Expose resources, prompts, and tools.
    • Transports: Support standard communication methods like stdio and SSE (Server-Sent Events).
    • Lifecycle Management: Handles all protocol messages and lifecycle events automatically.
  3. How custom primitives work in OpenAPIServer

    main

    OpenAPIServer allows you to combine OpenAPI-generated primitives with custom ones in a single instance. This enables a unified MCP server that provides:

    1. Tools: OpenAPI endpoints + custom utility tools (via registerTool or extraTools).
    2. Resources: OpenAPI data + custom dynamic resources (via registerResource or extraResources).
    3. Prompts: Templated workflows that can compose multiple API calls (via registerPrompt or extraPrompts).

    This approach eliminates the need to run separate MCP servers for custom logic when working with an OpenAPI-backed server.

  4. Filter tools using includeTools, includeOperations, includeResources, and includeTags

    main

    The ToolsManager applies filters in a specific order of precedence to determine which tools are exposed.

    Filter Precedence

    1. includeTools (Highest Priority): If toolsMode is set to explicit, only tools matching the IDs or names in this list are loaded. This overrides all other filters.
    2. Remaining Filters (AND logic): If not in explicit mode, the following filters are applied sequentially as AND operations:
      • includeOperations
      • includeResources
      • includeTags

    Note: Empty filter arrays result in no filtering being applied for that specific category.

    Resource Name Extraction

    The system extracts resource names from paths (e.g., GET::api-v1-user-profile-settings extracts settings). It supports paths containing hyphens, underscores, and special characters.

  5. How custom tools, resources, and prompts are managed

    main

    The OpenAPIServer manages custom primitives using internal Maps to ensure efficient lookup and prevent duplicates:

    • Tools: Stored in customTools (Map keyed by tool name).
    • Resources: Stored in customResources (Map keyed by URI).
    • Prompts: Stored in customPrompts (Map keyed by prompt name).

    Execution Logic

    • Tool Execution: When a tools/call request is received, the server first checks the OpenAPI-generated tools. If no match is found, it checks the customTools map and executes the corresponding handler.
    • Resource Access: For resources/read requests, the server performs a direct lookup in the customResources map using the provided URI.
    • Prompt Retrieval: For prompts/get requests, the server looks up the prompt by name, validates the required arguments, and executes the handler.

    Duplicate Handling

    The server enforces uniqueness. Attempting to register a tool, resource, or prompt with a name or URI that already exists will throw an error:

    • Error: Tool with name '${name}' already exists
    • Error: Resource with URI '${uri}' already exists
    • Error: Prompt with name '${name}' already exists
  6. Understand the OpenAPI MCP Server architecture

    main

    The @ivotoby/openapi-mcp-server is composed of several interacting components that manage the lifecycle of an OpenAPI specification being served via the Model Context Protocol (MCP):

    • OpenAPIServer: Handles server setup, transport management (Stdio/HTTP), and request routing.
    • ToolsManager: Responsible for tool filtering, tool lookup, and managing tool metadata.
    • OpenAPISpecLoader: Handles parsing the OpenAPI specification, creating tools, and processing schemas.
    • ApiClient: Manages HTTP requests to the target API, including parameter handling.
    • AuthProvider: Manages dynamic authentication, including token refresh and error recovery.
    • Tool ID Utils: Provides utilities for generating and parsing unique tool IDs.
  7. How OpenAPI parameter inheritance works

    main

    The OpenAPISpecLoader supports parameter inheritance from the path level to the operation level.

    • Inheritance: Parameters defined at a pathItem level are automatically inherited by all operations within that path.
    • Overriding: If an operation defines a parameter with the same name and in (location) as a path-level parameter, the operation-level parameter takes precedence.
    • Merging: If an operation defines different parameters than the path-level ones, the resulting set is a merge of both.
  8. Understand Tool ID generation and parsing logic

    main

    The project uses a specific convention for generating toolIds to ensure that API paths containing hyphens (e.g., /api/user-profile/items) can be correctly reconstructed without ambiguity.

    Generation Rules:

    • The toolId is composed of the HTTP method and the path part, separated by ::.
    • Slashes (/) in the original OpenAPI path are converted to double underscores (__).
    • Legitimate hyphens (-) within the original path segments are preserved as-is.
    • Example Format: GET::api__v1__users__user-id (where user-id is a literal segment and __ represents the path separators).

    Parsing Rules:

    • parseToolId splits the string at :: to separate the method from the path.
    • It then replaces all occurrences of __ with / to reconstruct the original API path.

    This system ensures that toolIds are unambiguous and that the original URL structure is preserved for API calls.

    // Example toolId structure:
    GET::api__v1__users__user-id
    
    // Reconstructed path:
    /api/v1/users/user-id
  9. How tools are filtered in ToolsManager

    main

    The ToolsManager provides mechanisms to control which tools are exposed to the MCP client.

    Filter Precedence

    Filters are applied in a specific order of priority:

    1. includeTools: This has the highest priority. If tools are listed here, only these tools are loaded.
    2. Other Filters: If includeTools is not used (or used in conjunction with other modes), filters for tags, resources, and operations are applied using AND logic.

    Tools Modes

    • explicit mode: When toolsMode is set to "explicit", the manager only loads the tools specifically listed in includeTools, ignoring all other specification entries and filters.
  10. How the Tool ID System works

    main

    Tool IDs uniquely identify API endpoints using the format METHOD::pathPart. To handle complex paths and preserve legitimate hyphens, the system uses a double underscore (__) as a separator for path segments.

    Path Separation Rules

    • Slashes (/) are replaced with double underscores (__).
    • Legitimate hyphens (-) within path segments are preserved.
    • Leading/trailing underscores and hyphens are trimmed.
    • Sequences of three or more underscores are collapsed to __.

    Examples

    Original PathTool ID
    /usersGET::users
    /api/v1/usersGET::api__v1__users
    /api/resource-name/itemsGET::api__resource-name__items
    /user-profile/dataGET::user-profile__data
    /a_b/c-d/e_f-gGET::a_b__c-d__e_f-g
  11. Configure outbound HTTPS behavior with mTLS

    main

    When mTLS is enabled, the server uses an HTTPS agent to manage outbound requests to your apiBaseUrl.

    Key Behaviors:

    • mTLS Activation: Requires both a client certificate path and a client key path.
    • Private CA Support: Providing a custom CA certificate path via --ca-cert or CA_CERT_PATH allows the server to trust certificates signed by that specific CA.
    • Encrypted Keys: If your client key is encrypted, provide the passphrase via --client-key-passphrase or CLIENT_KEY_PASSPHRASE.
    • Disabling TLS Verification: Set rejectUnauthorized to false (via --reject-unauthorized or REJECT_UNAUTHORIZED) to allow self-signed or untrusted server certificates.
    • Requirement: TLS settings are only valid for apiBaseUrl values using the https:// protocol. Providing TLS settings for an http:// URL will result in a configuration error.
  12. How server capabilities are declared for custom primitives

    main

    The OpenAPIServer automatically updates its initialize response capabilities based on which custom primitives you have registered:

    • Resources: If at least one custom resource is registered, the server includes capabilities.resources with list: true.
    • Prompts: If at least one custom prompt is registered, the server includes capabilities.prompts with list: true.
    • Default: If no custom resources or prompts are registered, the capabilities object will only include the tools capability, and resources/prompts will be omitted.