-
Notifications
You must be signed in to change notification settings - Fork 3
feat: Add support for logger in OpenAPI adapter and enhance security #109
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
WalkthroughAdds logger injection and multi-stage transforms to the OpenAPI adapter, introduces x-frontmcp extension validation, per-scheme security control, request/response size and timeout limits, prototype-pollution/SSRF/header protections, many new types, and extensive tests (total 193). Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Adapter as OpenAPI Adapter
participant Generator as mcp-from-openapi
participant Validator as x-frontmcp Validator
participant Transformer as Transform Pipeline
participant Tool as Generated Tool
participant Logger
User->>Adapter: init(spec, options { logger, transforms, timeouts })
Adapter->>Logger: setLogger(child)
Adapter->>Generator: createOpenApiTool(spec, options, logger)
Generator->>Validator: validateFrontMcpExtension(x-frontmcp)
Validator-->>Generator: validated frontmcp + warnings
Generator->>Transformer: apply descriptionMode & toolTransforms
Transformer-->>Generator: enriched metadata
Generator->>Generator: attach inputTransforms & metadata (with logger)
Generator-->>Adapter: return runnable Tool (logger wired)
User->>Tool: execute(input)
Tool->>Transformer: run input transforms (safeInject, timeout)
Tool->>Tool: buildRequest (validate baseURL, headers, cookies, collision checks)
Tool->>Tool: fetch (with AbortController timeout, maxRequestSize)
Tool->>Tool: parseResponse (Content-Length checks, maxResponseSize, JSON fallback)
Tool-->>User: result or sanitized error
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Areas to focus on:
Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro 📒 Files selected for processing (2)
🧰 Additional context used📓 Path-based instructions (3)**/*.ts📄 CodeRabbit inference engine (CLAUDE.md)
Files:
libs/{sdk,adapters,plugins,cli}/src/**/*.ts📄 CodeRabbit inference engine (CLAUDE.md)
Files:
libs/**⚙️ CodeRabbit configuration file
Files:
🧠 Learnings (5)📚 Learning: 2025-12-01T00:33:33.644ZApplied to files:
📚 Learning: 2025-12-01T00:33:33.644ZApplied to files:
📚 Learning: 2025-12-01T00:33:33.644ZApplied to files:
📚 Learning: 2025-12-01T00:33:33.644ZApplied to files:
📚 Learning: 2025-12-01T00:33:33.644ZApplied to files:
🧬 Code graph analysis (1)libs/adapters/src/openapi/openapi.security.ts (1)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
🔇 Additional comments (13)
Comment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 6
🧹 Nitpick comments (17)
libs/adapters/src/openapi/openapi.types.ts (1)
640-662: Consider narrowing theobjecttype for spec field.While using
objectenables seamless JSON imports, it's very permissive. A runtime validation would catch invalid specs, but a slightly more constrained type could help with IDE assistance.The current approach is pragmatic for developer experience. If desired, you could add a branded type or minimal shape:
// Optional: Add minimal shape constraint while keeping flexibility type OpenAPISpecLike = { openapi?: string; swagger?: string; paths?: unknown }; spec: OpenAPIV3.Document | OpenAPIV3_1.Document | (object & OpenAPISpecLike);This is a minor suggestion - the current implementation is functional and the broader
objecttype may be intentional for maximum compatibility with various JSON import patterns.libs/adapters/src/openapi/openapi.utils.ts (1)
68-78: Cookie name validation follows RFC 6265 token rules.The regex correctly validates cookie names as tokens. Consider whether the regex should also validate cookie values for control characters, similar to header validation.
libs/adapters/src/openapi/__tests__/fixtures.ts (1)
291-303: Consider removing the singletonmockLoggerto prevent test pollution.The
createMockLogger()factory is the correct approach, but the exportedmockLoggersingleton at line 303 could cause test interference if tests share state. Tests should always callcreateMockLogger()directly.export const createMockLogger = () => ({ verbose: jest.fn(), debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(), child: jest.fn().mockReturnThis(), }); - -export const mockLogger = createMockLogger();If
mockLoggeris needed for backward compatibility, consider adding a comment warning about test isolation, or ensure it's reset in a globalbeforeEach.libs/mcp-from-openapi/src/generator.ts (3)
219-221: Useunknowninstead ofanyfor error type.Per coding guidelines, avoid
anytypes. The catch clause already extracts the message safely viaerror.message.- } catch (error: any) { - console.warn(`Failed to generate tool for ${method.toUpperCase()} ${pathStr}:`, error.message); + } catch (error: unknown) { + const errorMessage = error instanceof Error ? error.message : String(error); + console.warn(`Failed to generate tool for ${method.toUpperCase()} ${pathStr}:`, errorMessage); }
298-327: Useunknowninstead ofanyfor theoperationparameter.Per coding guidelines, strict TypeScript mode requires avoiding
anytypes. Consider usingunknownor a more specific type fromopenapi-types.- private shouldIncludeOperation(operation: any, path: string, method: string, options: GenerateOptions): boolean { + private shouldIncludeOperation(operation: unknown, path: string, method: string, options: GenerateOptions): boolean { + const op = operation as { deprecated?: boolean; operationId?: string }; // Check deprecated - if (operation.deprecated && !options.includeDeprecated) { + if (op.deprecated && !options.includeDeprecated) { return false; } // Check operation ID filters - if (options.includeOperations && operation.operationId) { - if (!options.includeOperations.includes(operation.operationId)) { + if (options.includeOperations && op.operationId) { + if (!options.includeOperations.includes(op.operationId)) { return false; } } - if (options.excludeOperations && operation.operationId) { - if (options.excludeOperations.includes(operation.operationId)) { + if (options.excludeOperations && op.operationId) { + if (options.excludeOperations.includes(op.operationId)) { return false; } }
359-418: Multipleanytypes inextractMetadatamethod.The method uses
anyfor parameters and return type. Consider defining a proper interface or usingunknownwith type guards.At minimum, consider typing the return value to document the expected shape:
+interface ExtractedMetadata { + path: string; + method: HTTPMethod; + operationId?: string; + operationSummary?: string; + operationDescription?: string; + tags?: string[]; + deprecated?: boolean; + security?: SecurityRequirement[]; + servers?: Array<{ url: string; description?: string; variables?: unknown }>; + responseStatusCodes?: number[]; + externalDocs?: unknown; + frontmcp?: unknown; +} private extractMetadata( path: string, method: HTTPMethod, - operation: any, + operation: unknown, document: OpenAPIDocument, - outputSchema?: any, -): any { + outputSchema?: unknown, +): ExtractedMetadata {libs/adapters/src/openapi/__tests__/openapi-loading.spec.ts (1)
24-34: Consider removing unusedconsoleSpysetup.The
consoleSpyis set up and restored in each test but doesn't appear to be used for any assertions now that logging goes through the injectedmockLogger. Consider removing this boilerplate if it's no longer needed.describe('OpenapiAdapter - Loading', () => { - let consoleSpy: ReturnType<typeof spyOnConsole>; - beforeEach(() => { jest.clearAllMocks(); - consoleSpy = spyOnConsole(); - }); - - afterEach(() => { - consoleSpy.restore(); });libs/adapters/src/openapi/__tests__/openapi-security.spec.ts (1)
14-14: Consider typingmockSecurityResolverinstead ofany.Per coding guidelines, avoid
anytypes. Consider using a typed mock orunknownwith explicit casting where needed.- let mockSecurityResolver: any; + let mockSecurityResolver: { + resolve: jest.Mock; + };libs/adapters/src/openapi/__tests__/openapi-frontmcp-extension.spec.ts (1)
67-77: Consider removing unusedconsoleSpy.The console spy is set up and restored but not used for any assertions in this test file. Since logging goes through the injected
mockLogger, this boilerplate can be removed.describe('OpenapiAdapter - x-frontmcp Extension Support', () => { - let consoleSpy: ReturnType<typeof spyOnConsole>; - beforeEach(() => { jest.clearAllMocks(); - consoleSpy = spyOnConsole(); - }); - - afterEach(() => { - consoleSpy.restore(); });libs/adapters/src/openapi/openapi.security.ts (1)
300-304: Unused variablehasSecurityScheme.The variable
hasSecuritySchemeis declared on line 302 but never used. Consider removing it to avoid confusion.// Check if this tool requires security // A tool requires security ONLY if a mapper has security with required=true // Optional security schemes (required=false or undefined) should not block requests - const hasSecurityScheme = tool.mapper.some((m) => m.security); const hasRequiredSecurity = tool.mapper.some((m) => m.security && m.required === true); const requiresSecurity = hasRequiredSecurity;libs/adapters/src/openapi/__tests__/openapi-security-unit.spec.ts (1)
185-222: Consider adding assertion for apiKey routing.This test verifies that the first token wins for the
jwtfield, butScheme2withtype: 'apiKey'should route tocontext.apiKey. Consider asserting thatresult.apiKeyequals'token-from-scheme2'to fully validate the routing logic.}); // First token wins expect(result.jwt).toBe('token-from-scheme1'); + // apiKey scheme routes to apiKey field + expect(result.apiKey).toBe('token-from-scheme2'); });libs/adapters/src/openapi/openapi.frontmcp-schema.ts (1)
85-94: Consider usingz.unknown()instead ofz.any()for stricter type safety.Per coding guidelines,
unknownis preferred overanyfor generic type defaults. Whilez.any()works here for flexible example data,z.unknown()would provide stricter type safety at the cost of requiring explicit type assertions when accessing the data.export const FrontMcpExampleSchema = z.object({ /** Description of the example */ description: z.string(), /** Example input values */ - input: z.record(z.string(), z.any()), + input: z.record(z.string(), z.unknown()), /** Expected output (optional) */ - output: z.any().optional(), + output: z.unknown().optional(), });libs/adapters/src/openapi/openapi.adapter.ts (3)
303-314: Avoid usinganytype - preferunknownwith proper type narrowing.Per coding guidelines,
anytypes should be avoided without strong justification. Consider usingunknownwith type guards or defining a proper interface for adapter metadata.- metadata: { - ...tool.metadata, - adapter: { - ...((tool.metadata as any).adapter || {}), - toolTransform: transforms, - }, - }, + metadata: { + ...tool.metadata, + adapter: { + ...(((tool.metadata as Record<string, unknown>).adapter as Record<string, unknown>) || {}), + toolTransform: transforms, + }, + },
376-388: Sameanytype usage - apply consistent type handling.This is the same pattern as in
applyToolTransforms. Consider extracting a helper to safely access adapter metadata, ensuring consistent type handling across methods.- metadata: { - ...tool.metadata, - adapter: { - ...((tool.metadata as any).adapter || {}), - inputTransforms: transforms, - }, - }, + metadata: { + ...tool.metadata, + adapter: { + ...(((tool.metadata as Record<string, unknown>).adapter as Record<string, unknown>) || {}), + inputTransforms: transforms, + }, + },
438-449: Sameanytype pattern - consider a shared helper for metadata augmentation.This is the third occurrence. A helper like
getAdapterMetadata(tool)returning a typed object would eliminate repetition and enforce type safety.libs/adapters/src/openapi/openapi.tool.ts (2)
202-212: Consider making timeout constants configurable or documenting them.These defaults are reasonable, but consider exposing them in documentation or allowing override via options for edge cases with slow backends.
289-296: Consider usingz.ZodObject<z.ZodRawShape>for stricter typing.The
z.ZodObjecttype without generics may cause type inference issues. Per Zod 4 patterns, specifying the shape type improves type safety.interface SchemaConversionResult { - schema: z.ZodObject; + schema: z.ZodObject<z.ZodRawShape>; conversionFailed: boolean; error?: string; }
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
yarn.lockis excluded by!**/yarn.lock,!**/*.lock
📒 Files selected for processing (27)
docs/draft/blog/11-2025/openapi-mcp-security-nightmare.mdx(2 hunks)docs/draft/docs/adapters/openapi-adapter.mdx(4 hunks)docs/draft/docs/guides/add-openapi-adapter.mdx(2 hunks)libs/adapters/src/openapi/README.md(9 hunks)libs/adapters/src/openapi/__tests__/fixtures.ts(1 hunks)libs/adapters/src/openapi/__tests__/openapi-adapter.spec.ts(16 hunks)libs/adapters/src/openapi/__tests__/openapi-edge-cases.spec.ts(1 hunks)libs/adapters/src/openapi/__tests__/openapi-frontmcp-extension.spec.ts(1 hunks)libs/adapters/src/openapi/__tests__/openapi-loading.spec.ts(18 hunks)libs/adapters/src/openapi/__tests__/openapi-security-unit.spec.ts(1 hunks)libs/adapters/src/openapi/__tests__/openapi-security.spec.ts(14 hunks)libs/adapters/src/openapi/__tests__/openapi-tools.spec.ts(10 hunks)libs/adapters/src/openapi/__tests__/openapi-utils.spec.ts(2 hunks)libs/adapters/src/openapi/openapi.adapter.ts(4 hunks)libs/adapters/src/openapi/openapi.frontmcp-schema.ts(1 hunks)libs/adapters/src/openapi/openapi.security.ts(10 hunks)libs/adapters/src/openapi/openapi.tool.ts(1 hunks)libs/adapters/src/openapi/openapi.types.ts(3 hunks)libs/adapters/src/openapi/openapi.utils.ts(4 hunks)libs/mcp-from-openapi/SECURITY.md(31 hunks)libs/mcp-from-openapi/src/generator.ts(16 hunks)libs/mcp-from-openapi/src/index.ts(1 hunks)libs/mcp-from-openapi/src/types.ts(2 hunks)libs/sdk/package.json(0 hunks)libs/sdk/src/adapter/adapter.instance.ts(3 hunks)libs/sdk/src/common/interfaces/adapter.interface.ts(2 hunks)package.json(0 hunks)
💤 Files with no reviewable changes (2)
- libs/sdk/package.json
- package.json
🧰 Additional context used
📓 Path-based instructions (6)
**/*.ts
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.ts: Enable strict TypeScript mode with noanytypes without strong justification - useunknowninstead for generic type defaults
Avoid non-null assertions (!) - use proper error handling and throw specific errors instead
Use specific error classes with MCP error codes instead of generic errors
Use type parameters with constraints instead of unconstrained generics, and preferunknownoveranyfor generic type defaults
Follow the preset pattern for hierarchical configurations across the codebase
Files:
libs/mcp-from-openapi/src/index.tslibs/adapters/src/openapi/__tests__/openapi-security.spec.tslibs/mcp-from-openapi/src/generator.tslibs/sdk/src/adapter/adapter.instance.tslibs/sdk/src/common/interfaces/adapter.interface.tslibs/adapters/src/openapi/__tests__/openapi-security-unit.spec.tslibs/adapters/src/openapi/__tests__/openapi-frontmcp-extension.spec.tslibs/adapters/src/openapi/__tests__/openapi-edge-cases.spec.tslibs/adapters/src/openapi/__tests__/openapi-utils.spec.tslibs/adapters/src/openapi/__tests__/openapi-tools.spec.tslibs/adapters/src/openapi/openapi.utils.tslibs/mcp-from-openapi/src/types.tslibs/adapters/src/openapi/__tests__/fixtures.tslibs/adapters/src/openapi/openapi.frontmcp-schema.tslibs/adapters/src/openapi/openapi.tool.tslibs/adapters/src/openapi/__tests__/openapi-adapter.spec.tslibs/adapters/src/openapi/openapi.security.tslibs/adapters/src/openapi/__tests__/openapi-loading.spec.tslibs/adapters/src/openapi/openapi.adapter.tslibs/adapters/src/openapi/openapi.types.ts
libs/*/src/index.ts
📄 CodeRabbit inference engine (CLAUDE.md)
Use barrel exports (index.ts) to export all public API surface without legacy exports or aliases
Files:
libs/mcp-from-openapi/src/index.ts
libs/**
⚙️ CodeRabbit configuration file
libs/**: Contains publishable SDK libraries. Review for API correctness, breaking changes, and consistency with docs. When public APIs change, ensure there is a matching docs/draft/docs/** update (not direct edits under docs/docs/**).
Files:
libs/mcp-from-openapi/src/index.tslibs/adapters/src/openapi/__tests__/openapi-security.spec.tslibs/mcp-from-openapi/SECURITY.mdlibs/mcp-from-openapi/src/generator.tslibs/sdk/src/adapter/adapter.instance.tslibs/sdk/src/common/interfaces/adapter.interface.tslibs/adapters/src/openapi/__tests__/openapi-security-unit.spec.tslibs/adapters/src/openapi/__tests__/openapi-frontmcp-extension.spec.tslibs/adapters/src/openapi/__tests__/openapi-edge-cases.spec.tslibs/adapters/src/openapi/__tests__/openapi-utils.spec.tslibs/adapters/src/openapi/__tests__/openapi-tools.spec.tslibs/adapters/src/openapi/openapi.utils.tslibs/mcp-from-openapi/src/types.tslibs/adapters/src/openapi/__tests__/fixtures.tslibs/adapters/src/openapi/openapi.frontmcp-schema.tslibs/adapters/src/openapi/openapi.tool.tslibs/adapters/src/openapi/__tests__/openapi-adapter.spec.tslibs/adapters/src/openapi/openapi.security.tslibs/adapters/src/openapi/__tests__/openapi-loading.spec.tslibs/adapters/src/openapi/openapi.adapter.tslibs/adapters/src/openapi/openapi.types.tslibs/adapters/src/openapi/README.md
docs/**
⚙️ CodeRabbit configuration file
docs/**: Repository documentation for the SDK, using MDX and hosted by Mintlify. See more specific rules for: - docs/docs/** (latest rendered docs, automation-only) - docs/v/** (archived versions, read-only) - docs/draft/docs/** (human-editable drafts) - docs/blogs/** (blogs, human edited) - docs/docs.json (Mintlify navigation)
Files:
docs/draft/blog/11-2025/openapi-mcp-security-nightmare.mdxdocs/draft/docs/adapters/openapi-adapter.mdxdocs/draft/docs/guides/add-openapi-adapter.mdx
libs/{sdk,adapters,plugins,cli}/src/**/*.ts
📄 CodeRabbit inference engine (CLAUDE.md)
libs/{sdk,adapters,plugins,cli}/src/**/*.ts: Return strictly typed MCP protocol responses (GetPromptResult, ReadResourceResult, etc.) instead ofunknownforexecute()andread()methods
Validate URIs per RFC 3986 at metadata level using Zod validation with custom refinements
UsegetCapabilities()for dynamic capability exposure instead of hardcoding capabilities in adapters
UsechangeScopeinstead ofscopefor change event properties to avoid confusion with the Scope class
Validate hooks match their entry type and fail fast with InvalidHookFlowError for unsupported flows
Don't mutate rawInput in flows - use state.set() for managing flow state instead
Files:
libs/adapters/src/openapi/__tests__/openapi-security.spec.tslibs/sdk/src/adapter/adapter.instance.tslibs/sdk/src/common/interfaces/adapter.interface.tslibs/adapters/src/openapi/__tests__/openapi-security-unit.spec.tslibs/adapters/src/openapi/__tests__/openapi-frontmcp-extension.spec.tslibs/adapters/src/openapi/__tests__/openapi-edge-cases.spec.tslibs/adapters/src/openapi/__tests__/openapi-utils.spec.tslibs/adapters/src/openapi/__tests__/openapi-tools.spec.tslibs/adapters/src/openapi/openapi.utils.tslibs/adapters/src/openapi/__tests__/fixtures.tslibs/adapters/src/openapi/openapi.frontmcp-schema.tslibs/adapters/src/openapi/openapi.tool.tslibs/adapters/src/openapi/__tests__/openapi-adapter.spec.tslibs/adapters/src/openapi/openapi.security.tslibs/adapters/src/openapi/__tests__/openapi-loading.spec.tslibs/adapters/src/openapi/openapi.adapter.tslibs/adapters/src/openapi/openapi.types.ts
docs/draft/docs/**
⚙️ CodeRabbit configuration file
docs/draft/docs/**: This folder holds the draft/source docs that humans are expected to edit. When authors want to add or change documentation, they should do it here. The Codex workflow uses these drafts, together with the code diff, to generate the latest docs under docs/docs/. As a reviewer: - Encourage contributors to add/update content here instead of docs/docs/. - It is fine to do structural/content feedback here (clarity, examples, etc).
Files:
docs/draft/docs/adapters/openapi-adapter.mdxdocs/draft/docs/guides/add-openapi-adapter.mdx
🧠 Learnings (9)
📚 Learning: 2025-12-01T00:33:33.644Z
Learnt from: CR
Repo: agentfront/frontmcp PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-01T00:33:33.644Z
Learning: Use FrontMCP's TypeScript-first schema validation framework philosophy - all types should align with MCP protocol definitions
Applied to files:
libs/mcp-from-openapi/src/index.tsdocs/draft/blog/11-2025/openapi-mcp-security-nightmare.mdxlibs/adapters/src/openapi/__tests__/openapi-security.spec.tslibs/mcp-from-openapi/SECURITY.mdlibs/sdk/src/adapter/adapter.instance.tslibs/sdk/src/common/interfaces/adapter.interface.tslibs/adapters/src/openapi/__tests__/openapi-frontmcp-extension.spec.tslibs/mcp-from-openapi/src/types.tslibs/adapters/src/openapi/openapi.frontmcp-schema.tslibs/adapters/src/openapi/openapi.security.tslibs/adapters/src/openapi/openapi.types.tslibs/adapters/src/openapi/README.md
📚 Learning: 2025-12-01T00:33:33.644Z
Learnt from: CR
Repo: agentfront/frontmcp PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-01T00:33:33.644Z
Learning: Applies to libs/{sdk,adapters,plugins,cli}/src/**/*.ts : Return strictly typed MCP protocol responses (GetPromptResult, ReadResourceResult, etc.) instead of `unknown` for `execute()` and `read()` methods
Applied to files:
libs/mcp-from-openapi/src/index.tslibs/sdk/src/adapter/adapter.instance.tslibs/sdk/src/common/interfaces/adapter.interface.tslibs/mcp-from-openapi/src/types.tslibs/adapters/src/openapi/openapi.security.tslibs/adapters/src/openapi/openapi.types.ts
📚 Learning: 2025-12-01T00:33:33.644Z
Learnt from: CR
Repo: agentfront/frontmcp PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-01T00:33:33.644Z
Learning: Write comprehensive security documentation for packages
Applied to files:
docs/draft/blog/11-2025/openapi-mcp-security-nightmare.mdx
📚 Learning: 2025-11-26T15:23:04.965Z
Learnt from: CR
Repo: agentfront/frontmcp PR: 0
File: libs/ui/CLAUDE.md:0-0
Timestamp: 2025-11-26T15:23:04.965Z
Learning: Applies to libs/ui/src/**/*.test.ts : Test behavior across platform configurations (OpenAI, Claude, Gemini, ngrok) where applicable
Applied to files:
libs/adapters/src/openapi/__tests__/openapi-security.spec.tslibs/adapters/src/openapi/__tests__/openapi-security-unit.spec.tslibs/adapters/src/openapi/__tests__/openapi-frontmcp-extension.spec.tslibs/adapters/src/openapi/__tests__/openapi-edge-cases.spec.tslibs/adapters/src/openapi/__tests__/openapi-utils.spec.tslibs/adapters/src/openapi/__tests__/openapi-tools.spec.tslibs/adapters/src/openapi/__tests__/fixtures.tslibs/adapters/src/openapi/__tests__/openapi-adapter.spec.tslibs/adapters/src/openapi/__tests__/openapi-loading.spec.ts
📚 Learning: 2025-12-01T00:33:33.644Z
Learnt from: CR
Repo: agentfront/frontmcp PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-01T00:33:33.644Z
Learning: Applies to libs/*/src/common/records/**/*.ts : Centralize record types in common/records and import from there instead of from module-specific files
Applied to files:
libs/sdk/src/adapter/adapter.instance.ts
📚 Learning: 2025-12-01T00:33:33.644Z
Learnt from: CR
Repo: agentfront/frontmcp PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-01T00:33:33.644Z
Learning: Applies to libs/{sdk,adapters,plugins,cli}/src/**/*.ts : Use `getCapabilities()` for dynamic capability exposure instead of hardcoding capabilities in adapters
Applied to files:
libs/sdk/src/common/interfaces/adapter.interface.tslibs/adapters/src/openapi/__tests__/openapi-adapter.spec.ts
📚 Learning: 2025-12-01T00:33:33.644Z
Learnt from: CR
Repo: agentfront/frontmcp PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-01T00:33:33.644Z
Learning: Applies to **/*.test.ts : Test all code paths including errors, constructor validation, and error class `instanceof` checks
Applied to files:
libs/adapters/src/openapi/__tests__/openapi-edge-cases.spec.tslibs/adapters/src/openapi/__tests__/openapi-utils.spec.ts
📚 Learning: 2025-11-26T15:23:04.965Z
Learnt from: CR
Repo: agentfront/frontmcp PR: 0
File: libs/ui/CLAUDE.md:0-0
Timestamp: 2025-11-26T15:23:04.965Z
Learning: Applies to libs/ui/src/components/**/*.test.ts : Write validation tests covering invalid variant/options, unknown properties, and valid option acceptance
Applied to files:
libs/adapters/src/openapi/__tests__/openapi-edge-cases.spec.tslibs/adapters/src/openapi/__tests__/openapi-utils.spec.tslibs/adapters/src/openapi/__tests__/openapi-adapter.spec.ts
📚 Learning: 2025-12-01T00:33:33.644Z
Learnt from: CR
Repo: agentfront/frontmcp PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-01T00:33:33.644Z
Learning: Applies to libs/{sdk,adapters,plugins,cli}/src/**/*.ts : Validate URIs per RFC 3986 at metadata level using Zod validation with custom refinements
Applied to files:
libs/adapters/src/openapi/openapi.utils.tslibs/adapters/src/openapi/openapi.frontmcp-schema.ts
🧬 Code graph analysis (10)
libs/adapters/src/openapi/__tests__/openapi-security.spec.ts (3)
libs/adapters/src/openapi/__tests__/fixtures.ts (2)
mockLogger(303-303)createMockLogger(294-301)libs/mcp-from-openapi/src/types.ts (1)
McpOpenAPITool(157-189)libs/mcp-from-openapi/src/generator.ts (1)
OpenAPIToolGenerator(26-464)
libs/sdk/src/common/interfaces/adapter.interface.ts (1)
libs/testing/src/interceptor/interceptor-chain.ts (1)
logger(185-190)
libs/adapters/src/openapi/__tests__/openapi-security-unit.spec.ts (3)
libs/mcp-from-openapi/src/index.ts (2)
McpOpenAPITool(15-15)createSecurityContext(7-7)libs/mcp-from-openapi/src/types.ts (1)
McpOpenAPITool(157-189)libs/adapters/src/openapi/openapi.security.ts (1)
createSecurityContextFromAuth(34-143)
libs/adapters/src/openapi/__tests__/openapi-frontmcp-extension.spec.ts (3)
libs/mcp-from-openapi/src/index.ts (2)
FrontMcpExtensionData(18-18)McpOpenAPITool(15-15)libs/mcp-from-openapi/src/types.ts (2)
FrontMcpExtensionData(368-414)McpOpenAPITool(157-189)libs/adapters/src/openapi/openapi.tool.ts (1)
createOpenApiTool(27-200)
libs/adapters/src/openapi/__tests__/openapi-edge-cases.spec.ts (3)
libs/mcp-from-openapi/src/index.ts (1)
McpOpenAPITool(15-15)libs/mcp-from-openapi/src/types.ts (1)
McpOpenAPITool(157-189)libs/adapters/src/openapi/openapi.utils.ts (2)
buildRequest(89-197)validateBaseUrl(45-58)
libs/adapters/src/openapi/__tests__/openapi-utils.spec.ts (2)
libs/adapters/src/openapi/openapi.utils.ts (1)
parseResponse(231-273)libs/adapters/src/openapi/__tests__/fixtures.ts (1)
mockFetchError(261-269)
libs/adapters/src/openapi/__tests__/openapi-tools.spec.ts (2)
libs/adapters/src/openapi/__tests__/fixtures.ts (2)
mockLogger(303-303)createMockLogger(294-301)libs/adapters/src/openapi/openapi.tool.ts (1)
createOpenApiTool(27-200)
libs/mcp-from-openapi/src/types.ts (1)
libs/mcp-from-openapi/src/index.ts (1)
FrontMcpExtensionData(18-18)
libs/adapters/src/openapi/openapi.frontmcp-schema.ts (1)
libs/adapters/src/openapi/openapi.types.ts (1)
FrontMcpAnnotations(130-163)
libs/adapters/src/openapi/__tests__/openapi-adapter.spec.ts (1)
libs/adapters/src/openapi/__tests__/fixtures.ts (1)
createMockLogger(294-301)
🪛 Biome (2.1.2)
libs/adapters/src/openapi/openapi.utils.ts
[error] 140-140: Unexpected control character in a regular expression.
Control characters are unusual and potentially incorrect inputs, so they are disallowed.
(lint/suspicious/noControlCharactersInRegex)
libs/adapters/src/openapi/openapi.adapter.ts
[error] 195-195: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Safe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
🪛 Gitleaks (8.30.0)
libs/mcp-from-openapi/SECURITY.md
[high] 210-210: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
[high] 212-212: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
[high] 231-231: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
[high] 258-258: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
[high] 613-613: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
libs/adapters/src/openapi/__tests__/openapi-edge-cases.spec.ts
[high] 413-413: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
🔇 Additional comments (66)
docs/draft/docs/guides/add-openapi-adapter.mdx (2)
90-90: LGTM!The comment clarifies that direct JSON imports are now supported, which aligns with the broadened
spectype (OpenAPIV3.Document | OpenAPIV3_1.Document | object) inopenapi.types.ts.
225-227: Good addition of cross-reference to advanced documentation.The tip block effectively guides users to the comprehensive documentation for advanced features (
inputTransforms,toolTransforms,descriptionMode, andx-frontmcpextension).libs/sdk/src/adapter/adapter.instance.ts (2)
45-49: LGTM! Clean implementation of optional logger injection.The pattern correctly:
- Checks for
setLoggercapability before calling- Creates a namespaced child logger (
adapter:<name>) for clear log attribution- Injects before
fetch()as documented in the interface
47-48: [rewritten review comment]
[classification tag]libs/sdk/src/common/interfaces/adapter.interface.ts (1)
10-14: LGTM! Well-designed optional interface extension.The optional
setLoggermethod:
- Maintains backward compatibility with existing adapters
- Is clearly documented with its call timing (before
fetch())- Uses the properly typed
FrontMcpLoggerinterfaceThis follows the pattern from the coding guidelines for typed interfaces.
libs/mcp-from-openapi/SECURITY.md (3)
144-151: Excellent addition of Auth Type Routing documentation.This table clearly documents the automatic routing behavior between security scheme types and context fields, which is essential for users to understand how tokens are mapped.
448-458: Good clarification of SecurityContext with routing note.The added note about
authProviderMapperautomatic routing helps users understand the relationship between the type definitions and the runtime behavior documented in the Auth Type Routing section.
210-212: Static analysis false positive - example values in documentation.The Gitleaks alerts for "Generic API Key" on these lines are false positives. These are clearly placeholder example values (
sk-1234567890) in documentation demonstrating API usage patterns, not actual secrets.docs/draft/docs/adapters/openapi-adapter.mdx (4)
82-84: LGTM! Documentation accurately reflects broadened spec type.The updated description correctly explains that
specaccepts typed documents or plain objects from JSON imports, which aligns with the type definitionOpenAPIV3.Document | OpenAPIV3_1.Document | objectinopenapi.types.ts.
363-422: Comprehensive Input Schema Transforms documentation.The examples cover all three transform modes (global, per-tool, generator) with practical use cases. The security benefit callout at the end reinforces the value proposition.
497-541: Well-documented x-frontmcp OpenAPI extension.The YAML example and property table provide clear guidance for declarative configuration. The tip about precedence (adapter config overrides spec values) is helpful.
733-749: Excellent security documentation with defense-in-depth details.The protection table clearly lists built-in security measures (SSRF, header injection, prototype pollution, etc.) with brief descriptions. The Auth Type Routing summary and tip for implementation details are valuable additions.
libs/adapters/src/openapi/openapi.types.ts (6)
1-5: LGTM! Clean imports organization.The imports are well-organized, pulling in the necessary types from
openapi-types,mcp-from-openapi, and@frontmcp/sdkto support the new type definitions.
13-20: Well-designed InputTransformContext interface.The context provides appropriate access to authentication info, environment, and tool metadata for runtime value injection. Using
NodeJS.ProcessEnvfor env access is appropriate.
33-38: Good use ofunknownfor inject return type.Per coding guidelines, using
unknowninstead ofanyfor the inject return type is correct. This allows flexibility while maintaining type safety at the call site.
186-221: Comprehensive FrontMcpExtension interface.The extension interface covers all necessary configuration aspects (annotations, cache, codecall, tags, examples) with clear JSDoc documentation. The structure mirrors the documented YAML extension format.
356-371: Well-structured ExtendedToolMetadata for adapter-specific fields.The
adapternamespace cleanly separates adapter-specific runtime configuration from base metadata. Including bothsecuritySchemesInInputandsecuritySchemesFromContextenables the hybrid authentication pattern documented in the PR.
616-637: Good addition of request/response size limit options.These options (
requestTimeoutMs,maxRequestSize,maxResponseSize) provide important security controls with sensible defaults (30s timeout, 10MB limits). The JSDoc clearly explains when each check is performed.libs/adapters/src/openapi/openapi.utils.ts (5)
21-36: LGTM! Type-safe coercion with location-aware handling.The function properly handles arrays for query parameters (common use case) while rejecting objects/arrays in other locations where they can't be safely represented. Good defensive programming.
45-58: Good SSRF protection via protocol validation.Validating against
http:andhttps:protocols prevents dangerous schemes likefile://,javascript:, ordata:. The error re-throw pattern correctly preserves specific protocol errors.
136-147: Header injection protection is correctly implemented.The regex on line 140 intentionally uses literal control characters (
\r\n\x00\f\v) to detect header injection attacks. This is the correct approach—the static analysis warning is a false positive since these characters are the actual attack vectors being blocked.
168-178: Security parameter collision detection prevents ambiguous configurations.Throwing on collision is the safer choice over silent override. This helps catch configuration mistakes early.
234-238: Good security practice: error responses don't leak body content.Only exposing the status code prevents potential information disclosure from error response bodies.
libs/mcp-from-openapi/src/index.ts (1)
18-18: LGTM! New type export follows barrel pattern.The
FrontMcpExtensionDatatype is correctly added to the public API surface alongside related MCP types.libs/adapters/src/openapi/__tests__/openapi-adapter.spec.ts (2)
36-48: LGTM! Logger consistently injected across all adapter tests.The mock logger is properly passed to all
OpenapiAdapterconstructor calls, ensuring tests exercise the new logger-aware code paths.
257-266: Error handling test correctly validates the error message.The test properly uses
as anyto bypass TypeScript for testing invalid configurations, and the error message assertion matches the implementation.libs/adapters/src/openapi/__tests__/openapi-utils.spec.ts (3)
183-186: Test correctly validates the improved error message format.The regex
/Required.*parameter.*'id'.*is missing/properly matches the new descriptive error message that includes the quoted parameter name.
309-328: HTTP error tests validate security-conscious error handling.The comments appropriately document why
statusTextis excluded from error messages (to prevent sensitive info leakage). Tests correctly verify the sanitized format.
295-307: Invalid JSON handling test verifies silent fallback.The test confirms that invalid JSON is returned as text without console logging, matching the production-appropriate behavior in
parseResponse.libs/mcp-from-openapi/src/generator.ts (1)
413-416: LGTM — FrontMCP extension passthrough.Clean implementation that conditionally adds the
x-frontmcpextension data to metadata when present.docs/draft/blog/11-2025/openapi-mcp-security-nightmare.mdx (2)
339-352: Good documentation of defense-in-depth protections.The new section clearly documents automatic security protections. The link to implementation details in
openapi.executor.tsis helpful for users who want to verify the claims.
509-526: LGTM — Updated test coverage metrics.The test count update to 193 and addition of defense-in-depth coverage in the bullet points accurately reflects the expanded test suite.
libs/adapters/src/openapi/__tests__/openapi-loading.spec.ts (1)
45-62: LGTM — Logger injection pattern is consistent.The test correctly injects a mock logger into the adapter and verifies the expected behavior without testing logger output in this loading-focused test file.
libs/adapters/src/openapi/__tests__/openapi-tools.spec.ts (1)
395-421: Good edge case test for null input schema.Testing
inputSchema: null as anyensures the tool creation handles edge cases gracefully. This defensive test is valuable for robustness.libs/adapters/src/openapi/__tests__/openapi-security.spec.ts (3)
78-95: Good migration from console to logger assertions.The test correctly verifies that security risk information is now logged via the injected logger with appropriate messages.
444-515: Comprehensive test forsecuritySchemesInInputfiltering.This test validates the new per-scheme security control feature, ensuring:
includeSecurityInInput: trueis passed to the generator- Only specified schemes appear in input
- Logger outputs appropriate info messages
Well-structured test case.
517-573: Good negative test case for missing mappings.This test verifies that when
securitySchemesInInputexcludes a scheme but no mapping is provided for it, the adapter correctly throws an error. Important for validating fail-fast behavior.libs/adapters/src/openapi/__tests__/openapi-frontmcp-extension.spec.ts (1)
27-65: LGTM — Well-structured helper function.The
createMockToolhelper cleanly encapsulates test tool creation with optional frontmcp and toolTransform parameters. Good use of conditional property assignment.libs/adapters/src/openapi/openapi.security.ts (2)
61-116: Well-structured validation and error handling for authProviderMapper.The try-catch block properly validates return types, rejects empty strings with guidance, and routes tokens based on scheme type. The error wrapping distinguishes between validation errors and other errors appropriately.
220-244: Good implementation of per-scheme security validation with proper filtering.The logic correctly skips schemes that will be provided via input when validating mappings, and appropriately adjusts the risk score for hybrid authentication scenarios.
libs/mcp-from-openapi/src/types.ts (2)
317-362: Well-structured additions to ToolMetadata.The new
operationSummary,operationDescription, andfrontmcpfields are properly typed and documented, enabling richer metadata propagation through the tool generation pipeline.
364-414: LGTM - FrontMcpExtensionData interface is well-defined.The interface provides comprehensive typing for the x-frontmcp extension data with proper optional fields and documentation. The use of
unknownforoutputfollows TypeScript best practices.libs/adapters/src/openapi/__tests__/openapi-security-unit.spec.ts (2)
9-19: Good mock setup for mcp-from-openapi.The mock properly stubs
SecurityResolverandcreateSecurityContextto isolate the unit under test. The mock returns the context directly, allowing tests to verify the context building logic.
393-431: Excellent test coverage for multiple auth type routing.This test properly validates that different security scheme types are routed to their correct context fields simultaneously, ensuring the multi-auth support works as expected.
libs/adapters/src/openapi/README.md (2)
319-394: Comprehensive documentation for hybrid authentication.The new "Approach 4: Hybrid Authentication" section clearly explains the use case, provides practical examples, and documents the priority order for auth resolution. This will help users understand the per-scheme control feature.
953-965: Good documentation of security protections.The security protections table clearly communicates the defense-in-depth measures implemented, including SSRF prevention, header injection protection, and prototype pollution guards. This transparency helps users understand the security posture.
libs/adapters/src/openapi/__tests__/openapi-edge-cases.spec.ts (2)
411-436: Good test for error message security - static analysis flag is a false positive.The test correctly verifies that sensitive information from response bodies and statusText is not leaked in error messages. The "generic API key" flagged by static analysis at line 413 (
sk_live_123456) is intentional test data used to verify secrets are not exposed in errors - this is not a real credential.
761-813: Excellent SSRF protection test coverage.These tests verify critical security behavior: rejecting dangerous protocols from OpenAPI spec server URLs, proper precedence of validated server URLs over baseUrl, and correct fallback when servers array is empty.
libs/adapters/src/openapi/openapi.frontmcp-schema.ts (2)
171-215: Well-implemented validation function with graceful degradation.The function properly handles edge cases (null, undefined, non-objects), validates the schema version, and extracts only valid fields while collecting warnings. This approach ensures API stability even with malformed extension data.
437-451: The localZodIssueinterface cannot be directly replaced with Zod's exported type.Zod 4 exports
ZodIssueas a discriminated union with a requiredcodefield (e.g., "invalid_type", "custom", "too_small") and type-specific properties. The local interface is a deliberate simplification containing onlypathandmessage. Importing Zod's type would require handling thecodefield and lose flexibility (e.g.,PropertyKey[]supports symbols; Zod's path is limited to(string|number)[]). The local definition is appropriate for this use case.libs/adapters/src/openapi/openapi.adapter.ts (6)
7-20: LGTM!The console logger fallback is well-implemented with proper log level routing and child logger support.
31-43: LGTM!The constructor properly initializes the logger with a fallback, and
setLoggerallows SDK injection post-instantiation.
51-74: LGTM!The per-scheme security control logic correctly determines when to include security in input and filters schemes appropriately.
79-95: Good structured logging for security analysis.The conditional log level selection based on message prefix is a nice touch for surfacing warnings and errors appropriately.
119-141: LGTM!The multi-stage transformation pipeline is well-ordered: description mode → tool transforms → input transforms. Logger is correctly passed to
createOpenApiTool.
395-410: LGTM - Robust security scheme filtering with clear separation of concerns.The logic correctly identifies which security schemes to remove from input and tracks them for context-based resolution. Good defensive programming.
libs/adapters/src/openapi/openapi.tool.ts (10)
27-50: LGTM!Good extraction of transforms and metadata with proper type casting. The frontmcp extension validation and schema conversion are well-structured.
52-56: Good debugging metadata for schema conversion failures.Tracking conversion failures in metadata aids debugging without breaking functionality.
125-137: Good error handling for headersMapper.The try-catch with descriptive error messages helps with debugging mapper failures.
155-174: LGTM - Robust body serialization with size limits.Good handling of serialization errors with informative messages about potential causes (circular refs, BigInt). Size limit enforcement is a solid defense-in-depth measure.
176-198: LGTM - Proper timeout handling with cleanup.The AbortController pattern with
finallycleanup prevents memory leaks. The timeout error message is clear and actionable.
222-246: LGTM - Well-implemented timeout-protected transform injection.The Promise.race pattern with proper cleanup is correct. Error messages include the input key for debugging.
272-284: Excellent prototype pollution protection.The RESERVED_KEYS check effectively prevents prototype pollution attacks via malicious inputKey values. This is a critical security safeguard.
306-329: LGTM - Graceful degradation with permissive schema on conversion failure.Using
z.looseObject({})as fallback ensures tools remain functional even with schema issues, while logging warns about potential API-level failures.
263-268: Consider handling empty transforms array before spreading input.Minor optimization: when
transforms.length === 0, the function correctly returns early, but it creates a copy first. The current logic is correct but could short-circuit earlier.async function injectTransformedValues( input: unknown, transforms: InputTransform[], ctx: InputTransformContext, ): Promise<Record<string, unknown>> { + if (transforms.length === 0) { + if (!isPlainObject(input)) { + throw new Error(`Invalid input type: expected object, got ${input === null ? 'null' : typeof input}`); + } + return input; + } + // Validate input is a plain object to prevent prototype pollution if (!isPlainObject(input)) { throw new Error(`Invalid input type: expected object, got ${input === null ? 'null' : typeof input}`); } - if (transforms.length === 0) return input; - const result = { ...input };Actually, the current order is fine since validation should happen regardless. Disregard this suggestion.
102-113: No action needed. TheauthInfoproperty is required in the execution context and is guaranteed to be provided by the SDK framework. Thectxparameter passed to the tool handler is typed asToolContext, which extendsExecutionContextBasewith a requiredreadonly authInfo: AuthInfoproperty. There is no risk of undefinedauthInfo.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
♻️ Duplicate comments (1)
libs/adapters/src/openapi/__tests__/openapi-frontmcp-extension.spec.ts (1)
72-95: Tests lack meaningful assertions on extension data application.All tests in this file only verify
expect(result).toBeDefined()andexpect(typeof result).toBe('function'). This confirms tool creation but doesn't verify the x-frontmcp extension data was actually applied to tool metadata.Consider verifying the extension data is present, for example by checking logger calls or exposing metadata for inspection.
🧹 Nitpick comments (3)
libs/adapters/src/openapi/__tests__/openapi-frontmcp-extension.spec.ts (1)
86-86: Avoidas any- useunknownor a minimal typed stub instead.Per coding guidelines,
anyshould be avoided without strong justification. The empty spec object could be typed more safely.- spec: {} as any, + spec: {} as Record<string, unknown>,This pattern appears in many tests throughout this file (lines 86, 111, 134, 156, 177, 204, 227, 250, 274, 297, 320, 343, 366, 387, 408, 428, 449, 469, 496, 528, 554, 598, 633, 659, 686, 712, 741, 760, 782, 805, 828, 849, 867, 888, 908, 930, 952). Consider creating a helper constant or using a typed minimal spec in the fixtures file.
libs/mcp-from-openapi/src/generator.ts (1)
423-427: The type assertion for x-frontmcp does not validate the data—consider validating during extraction.The x-frontmcp extension is cast as
ToolMetadata['frontmcp']without schema validation. WhilevalidateFrontMcpExtensioninopenapi.tool.tsprovides comprehensive downstream Zod validation before the data is used, the type assertion at extraction time does not catch malformed data. Aligning with the codebase's "metadata level validation" pattern (noted in the learning guidelines), consider applying Zod validation directly during extraction inextractMetadatarather than relying solely on downstream validation. This would catch invalid extension data earlier and prevent unvalidated intermediate states.libs/adapters/src/openapi/openapi.security.ts (1)
57-107: Clarify comment to reflect multi-type routing behavior.The comment states "first matching token is used for jwt" but the code actually implements "first matching token per auth type" (jwt, apiKey, basic, oauth2Token). Each type gets its own first-wins assignment.
Consider updating the comment:
- // Process all schemes - first matching token is used for jwt + // Process all schemes - first matching token for each auth type (jwt, apiKey, basic, oauth2Token)
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (8)
docs/draft/docs/adapters/openapi-adapter.mdx(4 hunks)libs/adapters/src/openapi/__tests__/fixtures.ts(1 hunks)libs/adapters/src/openapi/__tests__/openapi-frontmcp-extension.spec.ts(1 hunks)libs/adapters/src/openapi/__tests__/openapi-loading.spec.ts(18 hunks)libs/adapters/src/openapi/openapi.adapter.ts(4 hunks)libs/adapters/src/openapi/openapi.security.ts(10 hunks)libs/adapters/src/openapi/openapi.utils.ts(4 hunks)libs/mcp-from-openapi/src/generator.ts(18 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- libs/adapters/src/openapi/tests/fixtures.ts
🧰 Additional context used
📓 Path-based instructions (5)
**/*.ts
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.ts: Enable strict TypeScript mode with noanytypes without strong justification - useunknowninstead for generic type defaults
Avoid non-null assertions (!) - use proper error handling and throw specific errors instead
Use specific error classes with MCP error codes instead of generic errors
Use type parameters with constraints instead of unconstrained generics, and preferunknownoveranyfor generic type defaults
Follow the preset pattern for hierarchical configurations across the codebase
Files:
libs/adapters/src/openapi/__tests__/openapi-frontmcp-extension.spec.tslibs/adapters/src/openapi/openapi.adapter.tslibs/adapters/src/openapi/__tests__/openapi-loading.spec.tslibs/adapters/src/openapi/openapi.utils.tslibs/adapters/src/openapi/openapi.security.tslibs/mcp-from-openapi/src/generator.ts
libs/{sdk,adapters,plugins,cli}/src/**/*.ts
📄 CodeRabbit inference engine (CLAUDE.md)
libs/{sdk,adapters,plugins,cli}/src/**/*.ts: Return strictly typed MCP protocol responses (GetPromptResult, ReadResourceResult, etc.) instead ofunknownforexecute()andread()methods
Validate URIs per RFC 3986 at metadata level using Zod validation with custom refinements
UsegetCapabilities()for dynamic capability exposure instead of hardcoding capabilities in adapters
UsechangeScopeinstead ofscopefor change event properties to avoid confusion with the Scope class
Validate hooks match their entry type and fail fast with InvalidHookFlowError for unsupported flows
Don't mutate rawInput in flows - use state.set() for managing flow state instead
Files:
libs/adapters/src/openapi/__tests__/openapi-frontmcp-extension.spec.tslibs/adapters/src/openapi/openapi.adapter.tslibs/adapters/src/openapi/__tests__/openapi-loading.spec.tslibs/adapters/src/openapi/openapi.utils.tslibs/adapters/src/openapi/openapi.security.ts
libs/**
⚙️ CodeRabbit configuration file
libs/**: Contains publishable SDK libraries. Review for API correctness, breaking changes, and consistency with docs. When public APIs change, ensure there is a matching docs/draft/docs/** update (not direct edits under docs/docs/**).
Files:
libs/adapters/src/openapi/__tests__/openapi-frontmcp-extension.spec.tslibs/adapters/src/openapi/openapi.adapter.tslibs/adapters/src/openapi/__tests__/openapi-loading.spec.tslibs/adapters/src/openapi/openapi.utils.tslibs/adapters/src/openapi/openapi.security.tslibs/mcp-from-openapi/src/generator.ts
docs/draft/docs/**
⚙️ CodeRabbit configuration file
docs/draft/docs/**: This folder holds the draft/source docs that humans are expected to edit. When authors want to add or change documentation, they should do it here. The Codex workflow uses these drafts, together with the code diff, to generate the latest docs under docs/docs/. As a reviewer: - Encourage contributors to add/update content here instead of docs/docs/. - It is fine to do structural/content feedback here (clarity, examples, etc).
Files:
docs/draft/docs/adapters/openapi-adapter.mdx
docs/**
⚙️ CodeRabbit configuration file
docs/**: Repository documentation for the SDK, using MDX and hosted by Mintlify. See more specific rules for: - docs/docs/** (latest rendered docs, automation-only) - docs/v/** (archived versions, read-only) - docs/draft/docs/** (human-editable drafts) - docs/blogs/** (blogs, human edited) - docs/docs.json (Mintlify navigation)
Files:
docs/draft/docs/adapters/openapi-adapter.mdx
🧠 Learnings (7)
📚 Learning: 2025-11-26T15:23:04.965Z
Learnt from: CR
Repo: agentfront/frontmcp PR: 0
File: libs/ui/CLAUDE.md:0-0
Timestamp: 2025-11-26T15:23:04.965Z
Learning: Applies to libs/ui/src/**/*.test.ts : Test behavior across platform configurations (OpenAI, Claude, Gemini, ngrok) where applicable
Applied to files:
libs/adapters/src/openapi/__tests__/openapi-frontmcp-extension.spec.tslibs/adapters/src/openapi/__tests__/openapi-loading.spec.ts
📚 Learning: 2025-12-01T00:33:33.644Z
Learnt from: CR
Repo: agentfront/frontmcp PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-01T00:33:33.644Z
Learning: Use FrontMCP's TypeScript-first schema validation framework philosophy - all types should align with MCP protocol definitions
Applied to files:
libs/adapters/src/openapi/__tests__/openapi-frontmcp-extension.spec.tslibs/adapters/src/openapi/openapi.security.tslibs/mcp-from-openapi/src/generator.ts
📚 Learning: 2025-11-26T15:23:04.965Z
Learnt from: CR
Repo: agentfront/frontmcp PR: 0
File: libs/ui/CLAUDE.md:0-0
Timestamp: 2025-11-26T15:23:04.965Z
Learning: Applies to libs/ui/src/components/**/*.test.ts : Write validation tests covering invalid variant/options, unknown properties, and valid option acceptance
Applied to files:
libs/adapters/src/openapi/__tests__/openapi-frontmcp-extension.spec.ts
📚 Learning: 2025-12-01T00:33:33.644Z
Learnt from: CR
Repo: agentfront/frontmcp PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-01T00:33:33.644Z
Learning: Applies to **/*.test.ts : Test all code paths including errors, constructor validation, and error class `instanceof` checks
Applied to files:
libs/adapters/src/openapi/__tests__/openapi-frontmcp-extension.spec.ts
📚 Learning: 2025-12-01T00:33:33.644Z
Learnt from: CR
Repo: agentfront/frontmcp PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-01T00:33:33.644Z
Learning: Applies to libs/{sdk,adapters,plugins,cli}/src/**/*.ts : Use `getCapabilities()` for dynamic capability exposure instead of hardcoding capabilities in adapters
Applied to files:
libs/adapters/src/openapi/__tests__/openapi-loading.spec.ts
📚 Learning: 2025-12-01T00:33:33.644Z
Learnt from: CR
Repo: agentfront/frontmcp PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-01T00:33:33.644Z
Learning: Applies to libs/{sdk,adapters,plugins,cli}/src/**/*.ts : Validate URIs per RFC 3986 at metadata level using Zod validation with custom refinements
Applied to files:
libs/adapters/src/openapi/openapi.utils.ts
📚 Learning: 2025-12-01T00:33:33.644Z
Learnt from: CR
Repo: agentfront/frontmcp PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-01T00:33:33.644Z
Learning: Applies to libs/{sdk,adapters,plugins,cli}/src/**/*.ts : Return strictly typed MCP protocol responses (GetPromptResult, ReadResourceResult, etc.) instead of `unknown` for `execute()` and `read()` methods
Applied to files:
libs/adapters/src/openapi/openapi.security.tslibs/mcp-from-openapi/src/generator.ts
🧬 Code graph analysis (3)
libs/adapters/src/openapi/__tests__/openapi-frontmcp-extension.spec.ts (2)
libs/mcp-from-openapi/src/types.ts (2)
FrontMcpExtensionData(368-414)McpOpenAPITool(157-189)libs/adapters/src/openapi/openapi.tool.ts (1)
createOpenApiTool(27-200)
libs/adapters/src/openapi/openapi.security.ts (1)
libs/adapters/src/openapi/openapi.types.ts (1)
OpenApiAdapterOptions(672-672)
libs/mcp-from-openapi/src/generator.ts (2)
libs/mcp-from-openapi/src/types.ts (8)
GenerateOptions(533-592)McpOpenAPITool(157-189)SecurityRequirement(419-460)OperationObject(33-33)OperationWithContext(525-528)OpenAPIDocument(15-15)ToolMetadata(301-362)ServerObject(43-43)libs/mcp-from-openapi/src/errors.ts (1)
LoadError(22-26)
🪛 Biome (2.1.2)
libs/adapters/src/openapi/openapi.utils.ts
[error] 140-140: Unexpected control character in a regular expression.
Control characters are unusual and potentially incorrect inputs, so they are disallowed.
(lint/suspicious/noControlCharactersInRegex)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: build
🔇 Additional comments (17)
libs/adapters/src/openapi/__tests__/openapi-loading.spec.ts (1)
1-311: LGTM! Logger injection is consistently applied across all test cases.The test file properly injects the mock logger into all
OpenapiAdapterinstantiations, ensuring the new logger functionality is exercised during tests. The consistent use ofcreateMockLogger()from fixtures maintains test isolation.docs/draft/docs/adapters/openapi-adapter.mdx (2)
126-128: LGTM! Logger parameter documentation is accurate.The logger parameter is correctly documented as optional, with clear explanation that the SDK auto-injects it via
setLogger()and that standalone usage can provide one or let it default to console-based logging.
363-561: LGTM! New transformation and extension documentation is comprehensive.The new sections for Input Schema Transforms, Tool Transforms, x-frontmcp OpenAPI Extension, and Description Mode are well-documented with clear examples and tables. The security protections section provides valuable guidance on the built-in safeguards.
libs/mcp-from-openapi/src/generator.ts (1)
368-430: LGTM! Metadata extraction is well-structured.The
extractMetadatamethod properly extracts operation summary, description, and x-frontmcp extension data with appropriate type handling. The new fields (operationSummary,operationDescription,frontmcp) align with theToolMetadatainterface.libs/adapters/src/openapi/openapi.utils.ts (4)
136-147: LGTM! Header injection protection is correctly implemented.The regex at line 140 intentionally includes control characters (
\r,\n,\x00,\f,\v) to detect and prevent header injection attacks. The static analysis warning is a false positive - this is a security validation pattern, not accidental control character usage.
251-263: Response size check limitation is properly documented.The comment at lines 252-256 now explicitly acknowledges that the post-read size check is defense-in-depth and does not protect against memory exhaustion for responses without Content-Length headers. This addresses the concern from the past review by documenting the trade-off.
168-178: Query parameter collision detection enhances security.The collision detection between user-provided and security query parameters is a good security addition that prevents potential misconfiguration. Throwing an error rather than silently overwriting ensures issues are caught during development.
45-58: LGTM! URL validation prevents SSRF attacks.The
validateBaseUrlfunction properly enforces http/https protocols and throws clear errors for invalid or unsupported URLs. This is an important security control.libs/adapters/src/openapi/openapi.adapter.ts (4)
7-20: LGTM! Console logger fallback is well-implemented.The
createConsoleLoggerfunction provides a clean fallback for standalone usage outside the SDK context. Thechild()method maintains the hierarchical prefix pattern, enabling scoped logging contexts.
194-202: Block scope correctly applied to switch case.The
case 'full':now properly wraps its declarations in a block ({ }), preventing accidental access from other switch clauses. This addresses the static analysis issue from past reviews.
353-393: Input transform application correctly modifies schema and stores metadata.The
applyInputTransformsmethod properly:
- Collects transforms from global, per-tool, and generator sources
- Removes transformed keys from
inputSchema.properties- Filters
requiredarray to exclude transformed keys- Stores transforms in metadata for runtime injection
400-457: Security scheme filtering logic is sound.The
filterSecuritySchemesmethod correctly identifies which security schemes should be removed from user input (resolved from context instead). The implementation properly updates both the inputSchema and metadata to track which schemes are user-provided vs context-resolved.libs/adapters/src/openapi/openapi.security.ts (5)
61-77: Excellent validation logic!The explicit type validation and empty string rejection with clear guidance improves robustness and developer experience.
79-107: Token routing logic is correct.The scheme type lookup and conditional routing correctly handles multiple auth types with appropriate guards. The optional chaining safely handles missing scheme information.
120-129: Improved fallback logic with comprehensive validation.The enhanced check for all auth fields (not just jwt) and the type validation for
authInfo.tokencorrectly prevents premature fallback and ensures type safety.
220-245: Per-scheme input handling implemented correctly.The logic to skip validation for schemes provided via input, along with the appropriate risk scoring adjustment, is sound. The informational warnings help users understand the security model.
300-322: Improved security requirement logic and error messaging.The updated logic correctly differentiates between required and optional security schemes, only blocking requests when
required === true. The error message enhancements with stable scheme lists and clear solution examples improve developer experience.
…inst reserved keys
Summary by CodeRabbit
New Features
Documentation
Tests
✏️ Tip: You can customize this high-level summary in your review settings.