Skip to content

Conversation

@kym6464
Copy link

@kym6464 kym6464 commented Jun 3, 2025

Fixes a bug where Path Item-level parameters are not considered.

Sample OpenAPI spec
openapi: 3.0.0
info:
  title: Minimal Parameter Override Example
  version: 1.0.0

paths:
  /items/{itemId}:
    # Path Item Level Parameter
    parameters:
      - name: itemId
        in: path
        required: true
        description: "Path Item Level: The ID of the item."
        schema:
          type: string
          format: uuid
    get:
      summary: Get an item by its ID
      operationId: getItemById
      # Operation Level Parameter (overrides the one at Path Item level)
      parameters:
        - name: itemId # Same name and 'in' location
          in: path
          required: true
          description: "Operation Level: The unique identifier (UUID) for the specific item to retrieve." # Different description
          schema:
            type: string
            format: uuid # Schema could also be different, but description is enough to show override
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: string
                    format: uuid
                  name:
                    type: string
                  retrievedWithDescription:
                    type: string # To show which description would be theoretically used
    put:
      summary: Update an item by its ID
      operationId: updateItemById
      # This operation does NOT override 'itemId', so it inherits the Path Item Level definition.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name:
                  type: string
      responses:
        '200':
          description: Item updated successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: string
                    format: uuid
                  name:
                    type: string
                  updatedWithDescription:
                    type: string # To show which description would be theoretically used

components: {}

Also makes some additional changes to aid local development:

  • Updates src/index.ts to support direct execution so that you can run the program using tsx without having to compile (VS Code's JavaScript Debug terminal lets you step through the Typescript code which is handy)
  • Improves type imports to support tsx

Summary by CodeRabbit

  • New Features

    • The CLI now runs automatically when executed directly, streamlining command-line usage.
  • Refactor

    • Improved handling of OpenAPI path-level and operation-level parameters to ensure accurate input schema generation.
    • Updated type exports to clearly separate runtime and type-only exports.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 3, 2025

Walkthrough

The changes introduce type-only imports and exports for specific TypeScript types, clarify separation between runtime and type exports, and update CLI invocation logic in the entry point. Additionally, parameter handling in OpenAPI tool extraction is enhanced to merge path-level and operation-level parameters, allowing proper overriding and schema generation.

Changes

File(s) Change Summary
src/api.ts Changed McpToolDefinition import to a type-only import; no functional changes.
src/index.ts Split exports into runtime and type-only; added CLI auto-invocation logic using a conditional block.
src/parser/extract-tools.ts Updated parameter merging: path-level parameters now included and can be overridden by operation-level; function signature updated.

Sequence Diagram(s)

sequenceDiagram
    participant CLI User
    participant index.ts
    participant CLI Program

    CLI User->>index.ts: Executes script directly
    index.ts->>CLI Program: Calls parse() method
    CLI Program-->>CLI User: Runs CLI logic
Loading
sequenceDiagram
    participant extractToolsFromApi
    participant generateInputSchemaAndDetails

    extractToolsFromApi->>generateInputSchemaAndDetails: Pass operation + path-level parameters
    generateInputSchemaAndDetails->>generateInputSchemaAndDetails: Merge path-level, then operation-level parameters
    generateInputSchemaAndDetails-->>extractToolsFromApi: Return input schema and details
Loading

Poem

In the warren of code, types hop with delight,
Imports and exports now clearly in sight.
Parameters merge, both path and op,
The CLI springs forward with a bunny hop.
With schemas more wise and boundaries defined,
This patch leaves no rabbit behind! 🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-06-03T19_33_32_734Z-debug-0.log

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/parser/extract-tools.ts (1)

101-112: LGTM! Correct implementation of parameter precedence.

The parameter merging logic correctly implements the OpenAPI specification behavior:

  1. Path Item-level parameters are processed first
  2. Operation-level parameters are processed second, allowing them to override path-level parameters with the same name
  3. The Array.isArray checks provide proper safety for optional parameters

This implementation aligns perfectly with the PR objectives and the provided sample OpenAPI specification example where operation-level parameters override path-level ones.

Consider a minor type safety improvement:

-    allParameters.push(...pathParameters.map((p) => p as OpenAPIV3.ParameterObject));
+    allParameters.push(...pathParameters.filter(p => !('$ref' in p)) as OpenAPIV3.ParameterObject[]);
-    allParameters.push(...operation.parameters.map((p) => p as OpenAPIV3.ParameterObject));
+    allParameters.push(...operation.parameters.filter(p => !('$ref' in p)) as OpenAPIV3.ParameterObject[]);

This would properly handle any unresolved references, though after dereferencing they should already be resolved.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2c6c059 and 22b1bcc.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • src/api.ts (1 hunks)
  • src/index.ts (2 hunks)
  • src/parser/extract-tools.ts (3 hunks)
🔇 Additional comments (6)
src/api.ts (1)

9-9: LGTM! Good TypeScript practice improvement.

Converting to a type-only import clarifies that McpToolDefinition is used solely for typing purposes and won't be included in the emitted JavaScript code. This improves tree-shaking and aligns with the type-only exports introduced in src/index.ts.

src/index.ts (2)

35-36: LGTM! Proper separation of runtime and type exports.

Converting McpToolDefinition and GetToolsOptions to type-only exports while keeping getToolsFromOpenApi as a runtime export correctly separates types from runtime functionality. This aligns with the type-only import changes in src/api.ts and improves code clarity.


88-91: LGTM! Enables direct execution for improved development experience.

The conditional block correctly detects when the file is executed directly and automatically invokes the CLI program. This supports the PR objective of enabling direct execution with the tsx tool for better debugging and development workflow.

src/parser/extract-tools.ts (3)

25-25: LGTM! Correctly captures Path Item-level parameters.

This properly extracts the path-level parameters from the pathItem, which is essential for implementing the Path Item-level parameter inheritance described in the PR objectives.


53-56: LGTM! Proper parameter passing to schema generation.

The function call correctly passes both the operation and the newly captured pathParameters to generateInputSchemaAndDetails, enabling the parameter merging logic.


90-93: LGTM! Function signature correctly updated.

The optional pathParameters parameter is properly typed and documented, maintaining backward compatibility while enabling the new Path Item-level parameter functionality.

@harsha-iiiv
Copy link
Owner

@kym6464 @coderabbitai

  • Adding path-level parameters first and then operation-level parameters does not, by itself, ensure that the operation-level parameter will “override” the path-level one in the resulting array.
  • Without deduplication (by name and location), both will remain in the merged array, which is not correct per the OpenAPI spec.
  • The correct behavior is to ensure that if both exist, only the operation-level parameter is kept.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 8, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

@harsha-iiiv You're absolutely correct! The current implementation may not handle parameter deduplication properly according to the OpenAPI specification. Let me examine the actual implementation to verify this concern.


🏁 Script executed:

#!/bin/bash
# Examine the parameter handling implementation in extract-tools.ts
cat src/parser/extract-tools.ts

Length of output: 7907


You're absolutely right! Looking at the current implementation, I can confirm there are several issues with the parameter handling:

Issues in Current Implementation

  1. No proper deduplication: The allParameters array contains both path-level and operation-level parameters, even when they have the same name and in values.

  2. Potential duplicate entries in required array: If both a path parameter and operation parameter with the same name are marked as required, the name gets added twice to the required array.

  3. Returned parameters array is incorrect: The function returns allParameters which contains duplicates, violating the OpenAPI specification.

The Correct Approach

According to the OpenAPI 3.0 specification, parameters are uniquely identified by the combination of name and in (location). Operation-level parameters should completely override path-level parameters with matching name and in values.

Here's how the deduplication should work:

// Proper deduplication logic
const parameterMap = new Map<string, OpenAPIV3.ParameterObject>();

// Add path-level parameters first
if (Array.isArray(pathParameters)) {
  pathParameters.forEach(p => {
    const param = p as OpenAPIV3.ParameterObject;
    const key = `${param.name}:${param.in}`;
    parameterMap.set(key, param);
  });
}

// Add operation-level parameters (these override path-level ones)
if (Array.isArray(operation.parameters)) {
  operation.parameters.forEach(p => {
    const param = p as OpenAPIV3.ParameterObject;
    const key = `${param.name}:${param.in}`;
    parameterMap.set(key, param); // This overwrites any path-level parameter
  });
}

const allParameters = Array.from(parameterMap.values());

This ensures that:

  • Only unique parameters (by name + location) are kept
  • Operation-level parameters properly override path-level ones
  • The returned parameters array is spec-compliant
  • No duplicate entries in the required array

Would you like me to create a follow-up issue to track this parameter deduplication fix?


✏️ Learnings added
Learnt from: harsha-iiiv
URL: https://github.com/harsha-iiiv/openapi-mcp-generator/pull/20

Timestamp: 2025-06-08T17:37:22.197Z
Learning: In OpenAPI specifications, parameters are uniquely identified by the combination of `name` and `in` (location) values. Operation-level parameters should completely override path-level parameters with matching name and location, requiring proper deduplication logic rather than simple array concatenation.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@harsha-iiiv harsha-iiiv self-requested a review June 8, 2025 18:06
Copy link
Owner

@harsha-iiiv harsha-iiiv left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@harsha-iiiv
Copy link
Owner

@kym6464 Hi, are you still interested in completing this pull request?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants