Skip to content

fix(core): remove unsafe type assertions in mcp and code_assist (Phase 7)#19860

Open
ktk-07 wants to merge 10 commits intogoogle-gemini:mainfrom
ktk-07:fix/unsafe-type-assertions-in-Core-MCP-and-Code-assist-19735
Open

fix(core): remove unsafe type assertions in mcp and code_assist (Phase 7)#19860
ktk-07 wants to merge 10 commits intogoogle-gemini:mainfrom
ktk-07:fix/unsafe-type-assertions-in-Core-MCP-and-Code-assist-19735

Conversation

@ktk-07
Copy link
Copy Markdown

@ktk-07 ktk-07 commented Feb 21, 2026

Summary

This PR Removes @typescript-eslint/no-unsafe-type-assertion suppressions in:

  • packages/core/src/mcp/
  • packages/core/src/code_assist/

Changes include:

  • Replacing "as any" and "as Error" assertions with proper type guards
  • Validating parsed JSON using Zod schemas
  • Improving error handling to avoid unsafe narrowing
  • Relaxing issuer validation in OAuthAuthorizationServerMetadataSchema to keep existing unit tests passing

This improves type safety and aligns with the ESLint @typescript-eslint/no-unsafe-type-assertion rules enforced by CI.

Details

Removal of Unsafe Type Assertions

Replaced unsafe assertions such as:

  • error as Error
  • error as NodeJS.ErrnoException
  • JSON.parse(...) as SomeType

with:

  • Type guards (instanceof Error, custom isErrnoException)
  • Zod validation schemas for parsed JSON
  • Safe error wrapping patterns: errors.push(error instanceof Error ? error : new Error(String(error)));

Important Note: OAuth Metadata Strictness Adjustment

While adding Zod validation for OAuthAuthorizationServerMetadata, I discovered that three existing unit tests use minimal metadata mocks that omit the issuer field.

Per RFC 8414, issuer is required in Authorization Server Metadata. However, enforcing this strictly in the schema caused existing tests to fail.

To keep this PR focused on removing unsafe type assertions and avoid expanding scope:

  • issuer was made optional in both the Zod schema and TypeScript interface.
  • No test files were modified.

If strict RFC 8414 compliance is preferred, we could follow up by:

  • Updating the affected test mocks to include issuer
  • Making issuer required again in both the schema and interface

This implementation could be in this pr or another pr.
Happy to adjust based on maintainer preference.

Related Issues

Fixes #19735
Parent issuse #19708

How to Validate

From repository root:

npm run preflight

Expected results:

  • No ESLint @typescript-eslint/no-unsafe-* violations
  • Typecheck passes
  • Unit tests pass

Manually verify:

  • OAuth credential load/save still works
  • OAuth metadata discovery still functions
  • No regression in MCP OAuth flows

Pre-Merge Checklist

  • Updated relevant documentation and README (if needed)
  • Added/updated tests (if needed)
  • Noted breaking changes (if any)
  • Validated on required platforms/methods:
    • MacOS
      • npm run
      • npx
      • Docker
      • Podman
      • Seatbelt
    • Windows
      • npm run
      • npx
      • Docker
    • Linux
      • npm run
      • npx
      • Docker

@ktk-07 ktk-07 requested a review from a team as a code owner February 21, 2026 21:26
@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @ktk-07, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the type safety and robustness of the core MCP (Managed Control Plane) and code assist modules by eliminating unsafe type assertions. It achieves this by integrating Zod for runtime validation of JSON data, implementing custom type guards for error handling and network address information, and refining existing type definitions. The changes aim to align the codebase with stricter ESLint rules and improve overall code quality and maintainability.

Highlights

  • Enhanced Type Safety: Removed numerous @typescript-eslint/no-unsafe-type-assertion suppressions by replacing direct type assertions (as any, as Error) with robust type guards and Zod schemas for runtime validation.
  • Zod Schema Integration: Introduced Zod schemas for validating parsed JSON responses, including OAuth token responses, client registration responses, and OAuth authorization server metadata, ensuring data integrity and type correctness at runtime.
  • Improved Error Handling: Refactored error handling to use instanceof Error checks and custom type guards (e.g., isErrnoException, isAddressInfo) to safely narrow error types and prevent unsafe type assertions.
  • OAuth Metadata Flexibility: Adjusted the issuer field in OAuthAuthorizationServerMetadata to be optional in both the TypeScript interface and Zod schema to maintain compatibility with existing unit tests, while noting that strict RFC 8414 compliance could be re-enabled in a follow-up.
Changelog
  • packages/core/src/mcp/oauth-provider.ts
    • Imported Zod library for schema validation.
    • Defined OAuthTokenResponseSchema and OAuthClientRegistrationResponseSchema using Zod.
    • Added isAddressInfo type guard to safely check network address types.
    • Replaced direct type assertions with Zod parsing for OAuth client registration and token responses.
    • Updated server address handling to use isAddressInfo type guard, improving error handling for port determination.
  • packages/core/src/mcp/oauth-token-storage.ts
    • Imported Zod and OAuthCredentialsSchema.
    • Defined OAuthCredentialsArraySchema for validating arrays of credentials.
    • Added isErrnoException type guard for safer error handling.
    • Replaced direct type assertions with Zod parsing when loading OAuth credentials from file.
    • Updated error handling for file operations to use isErrnoException.
  • packages/core/src/mcp/oauth-utils.ts
    • Imported Zod library.
    • Made the issuer property optional in the OAuthAuthorizationServerMetadata interface.
    • Defined OAuthAuthorizationServerMetadataSchema and OAuthProtectedResourceMetadataSchema using Zod, with issuer as optional.
    • Replaced direct type assertions with Zod parsing for fetching protected resource and authorization server metadata.
  • packages/core/src/mcp/sa-impersonation-provider.ts
    • Updated error handling in getAuthToken to safely wrap caught exceptions as Error objects.
  • packages/core/src/mcp/token-storage/file-token-storage.ts
    • Imported Zod and OAuthCredentialsSchema.
    • Defined OAuthCredentialsRecordSchema for validating records of credentials.
    • Added isErrnoException type guard.
    • Replaced direct type assertions with Zod parsing when reading encrypted token files.
    • Improved error handling for file operations, including ENOENT and corrupted data, using isErrnoException and explicit error wrapping.
  • packages/core/src/mcp/token-storage/keychain-token-storage.ts
    • Imported Zod and OAuthCredentialsSchema.
    • Replaced direct type assertions with Zod parsing when retrieving single OAuth credentials from keychain.
    • Replaced direct type assertions with Zod parsing when retrieving all OAuth credentials from keychain.
    • Updated error handling in clearAll to safely wrap caught exceptions as Error objects.
  • packages/core/src/mcp/token-storage/types.ts
    • Imported Zod library.
    • Defined OAuthTokenSchema and OAuthCredentialsSchema using Zod for robust type validation.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

The pull request significantly improves type safety by removing many unsafe type assertions and introducing Zod validation for OAuth-related data structures. This aligns well with the project's goal of moving towards stricter TypeScript enforcement. I have identified a few areas for improvement, including a redundant type assertion in a new type guard, a naming convention violation, code duplication for error handling, and a schema weakening that deviates from RFC 8414, which also goes against the principle of 'fail-closed' security checks.

Comment thread packages/core/src/mcp/oauth-provider.ts Outdated
Comment thread packages/core/src/mcp/oauth-token-storage.ts Outdated
Comment thread packages/core/src/mcp/oauth-token-storage.ts Outdated
Comment thread packages/core/src/mcp/oauth-utils.ts Outdated
Comment thread packages/core/src/mcp/oauth-utils.ts Outdated
@gemini-cli gemini-cli Bot added the area/core Issues related to User Interface, OS Support, Core Functionality label Feb 21, 2026
@ktk-07
Copy link
Copy Markdown
Author

ktk-07 commented Feb 22, 2026

As mentioned in my initial pull request under "Important Note section", i initially took the approach of relaxing issuer in TypeScript interface and the Zod schema so that the unit tests passed. Because keeping it both required in TypeScript interface and the Zod schema, causes a few unit tests to fail in oauth-provider.test.ts as their mocked auth server metadata omitted issuer.

Since gemini-code-assist bot reinforces the need for RFC 8414 requires issuer, I’m keeping it required in both the TypeScript interface and the Zod schema.

I will be updating those mocks in packages/core/src/mcp/oauth-provider.test.ts to include a valid issuer string so the tests match the spec and the stricter runtime validation.

I will also be making the necessary changes like removing redundant assertion, fixing camelCase naming and removing code duplication

@ktk-07
Copy link
Copy Markdown
Author

ktk-07 commented Feb 22, 2026

I addressed code review feedback (recent changes):

  • RFC 8414 / issuer: Enforced required issuer in OAuth authorization server metadata (Zod schema) and updated the three discovery test mocks to include issuer: 'https://discovered.auth.com' so tests align with the spec.
  • Style / assertions: Removed a redundant type assertion and fixed camelCase naming in the touched code.
  • Shared type guard: Define the function isErrnoException() in utils/errors.ts (supports both Error and plain objects with string code, e.g. test mocks) and added unit tests for it; MCP token storage now uses this guard instead of local checks or unsafe casts.
  • Verification: Confirmed all 5005 core tests pass and lint is clean.

@ktk-07 ktk-07 force-pushed the fix/unsafe-type-assertions-in-Core-MCP-and-Code-assist-19735 branch from dcc5837 to df6da1a Compare March 3, 2026 16:51
@gemini-cli gemini-cli Bot added priority/p2 Important but can be addressed in a future release. 🔒 maintainer only ⛔ Do not contribute. Internal roadmap item. labels Mar 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/core Issues related to User Interface, OS Support, Core Functionality 🔒 maintainer only ⛔ Do not contribute. Internal roadmap item. priority/p2 Important but can be addressed in a future release.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fix unsafe type assertions in Core MCP & Code Assist (Phase 7)

1 participant