Skip to content

Conversation

@gunpal5
Copy link
Owner

@gunpal5 gunpal5 commented Nov 8, 2025

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced Model Context Protocol (MCP) server integration, enabling Gemini models to connect with MCP servers
    • Support for multiple transport types: stdio, HTTP/SSE, and custom configurations
    • Connect multiple MCP servers simultaneously to a single model instance
    • Built-in auto-reconnection with configurable retry behavior and timeout settings
  • Documentation

    • Added comprehensive MCP integration guide with transport examples and best practices
    • Included sample project demonstrating real-world MCP integration patterns

gunpal5 and others added 5 commits November 5, 2025 14:02
Implements easy-to-integrate MCP server support using the official C# SDK,
allowing Gemini models to use tools from any MCP server.

Key Features:
- McpTool class implementing IFunctionTool interface
- Auto-discovery of tools from MCP servers
- Support for multiple concurrent MCP servers
- Automatic reconnection and error handling
- Comprehensive configuration options

Implementation:
- McpServerConfig: Configure server connections (command, args, env vars)
- McpToolOptions: Control behavior (auto-reconnect, error handling)
- McpTool: Main class that bridges MCP servers with Google Generative AI
- Async/await pattern with proper IDisposable/IAsyncDisposable support
- Converts MCP tools to Google's FunctionDeclaration format
- Forwards function calls to MCP servers and converts responses

Example Usage:
var config = new McpServerConfig
{
    Name = "my-server",
    Command = "npx",
    Arguments = new List<string> { "-y", "@modelcontextprotocol/server-everything" }
};

using var mcpTool = await McpTool.CreateAsync(config);
var model = new GenerativeModel(apiKey, "gemini-2.0-flash-exp");
model.AddFunctionTool(mcpTool);

Files Added:
- src/GenerativeAI.Tools/Mcp/McpServerConfig.cs
- src/GenerativeAI.Tools/Mcp/McpTool.cs
- src/GenerativeAI.Tools/Mcp/README.md
- samples/McpIntegrationDemo/ (complete example project)
- MCP_INTEGRATION_SUMMARY.md

Dependencies:
- Added ModelContextProtocol v0.4.0-preview.3 NuGet package
Major update to MCP integration to support ALL transport protocols
using the official MCP SDK's native transport classes.

BREAKING CHANGE: McpTool now accepts IClientTransport directly instead
of custom McpServerConfig. Use McpTransportFactory for easy creation.

New Features:
- Support for ALL MCP transport types (stdio, HTTP/SSE, custom)
- Native integration with MCP SDK's IClientTransport interface
- McpTransportFactory with helper methods for common configurations
- HTTP/SSE transport support for remote MCP servers
- HTTP authentication support (Bearer tokens, custom headers)
- Transport factory pattern for auto-reconnection
- Mix and match different transport types in single application

Transport Types Supported:
1. Stdio Transport - Launch MCP servers as subprocesses
2. HTTP/SSE Transport - Connect to remote MCP servers via HTTP
3. Custom Transports - Any IClientTransport implementation

Implementation Changes:
- McpServerConfig.cs: Redesigned with McpTransportFactory class
  - CreateStdioTransport() - For stdio with full options
  - CreateHttpTransport() - For HTTP/SSE connections
  - CreateHttpTransportWithAuth() - HTTP with Bearer auth
  - CreateHttpTransportWithHeaders() - HTTP with custom headers

- McpTool.cs: Now accepts IClientTransport
  - CreateAsync(IClientTransport) - Use any transport
  - CreateAsync(Func<IClientTransport>) - Auto-reconnection support
  - CreateMultipleAsync(IEnumerable<IClientTransport>) - Multiple servers
  - Improved reconnection logic with transport factories

Examples Updated:
- Example 1: Stdio transport (launch as subprocess)
- Example 2: HTTP/SSE transport (connect to remote server)
- Example 3: Multiple servers with different transports
- Example 4: Custom configuration (env vars, headers, auth)
- Example 5: Auto-reconnection with transport factory

Migration Guide:
Old (v1):
  var config = new McpServerConfig { Name = "s", Command = "npx", ... };
  using var tool = await McpTool.CreateAsync(config);

New (v2):
  var transport = McpTransportFactory.CreateStdioTransport("s", "npx", ...);
  using var tool = await McpTool.CreateAsync(transport);

Benefits:
- ✅ Full protocol support (not just stdio)
- ✅ Native MCP SDK integration
- ✅ Extensible for future transports
- ✅ Better separation of concerns
- ✅ Direct access to all SDK features
- ✅ Future-proof architecture

Documentation:
- Updated MCP_INTEGRATION_SUMMARY.md with all transport types
- Updated Program.cs with comprehensive examples
- Added transport factory documentation
- Set proper git author: Gunpal Jain <gunpal5@gmail.com>
- Define branch naming conventions (no 'claude' prefix)
- Document project structure and coding standards
- Ensure all future sessions use correct identity
- Remove standalone markdown files (MCP_INTEGRATION_SUMMARY.md, samples/McpIntegrationDemo/README.md, src/GenerativeAI.Tools/Mcp/README.md)
- Add MCP Server Integration section to main README
- Include examples for stdio, HTTP/SSE, and multiple servers
- Update table of contents
- Keep documentation concise and centralized
- Introduced comprehensive integration tests for MCP tools and Gemini models, validating end-to-end functionality and user workflows.
- Added ModelContextProtocol.Core dependency (v0.4.0-preview.3) to support MCP tool features.
- Updated internal handling of MCP tools with `McpClientTool` for better tool representation and usability.
- Improved transport creation methods with enhanced options for stdio, HTTP, authentication, and custom headers.
- Verified proper handling of function calls, connection management, and error responses in tools.
@coderabbitai
Copy link

coderabbitai bot commented Nov 8, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This PR introduces Model Context Protocol (MCP) integration to the Gemini SDK, enabling seamless tool interaction with MCP servers via multiple transports (stdio, HTTP/SSE). It includes new MCP tool implementation, configuration options, transport factories, comprehensive tests, documentation updates, and a sample demo program illustrating integration patterns.

Changes

Cohort / File(s) Summary
Documentation
CLAUDE.md, README.md
Added Git conventions guide (CLAUDE.md) and MCP Server Integration section to README with transport examples (stdio, HTTP/SSE, multiple servers) and feature overview
Configuration & Dependencies
src/GenerativeAI.Tools/GenerativeAI.Tools.csproj, samples/McpIntegrationDemo/McpIntegrationDemo.csproj
Added ModelContextProtocol and ModelContextProtocol.Core NuGet package dependencies; created new sample project targeting .NET 8.0 with project references to GenerativeAI libraries
MCP Core Implementation
src/GenerativeAI.Tools/Mcp/McpServerConfig.cs, src/GenerativeAI.Tools/Mcp/McpTool.cs
Introduced McpToolOptions configuration class with timeout, reconnection, and error-handling settings; implemented McpTool class with multi-transport support, auto-reconnection, tool discovery, and Gemini integration capabilities
Transport Factory
src/GenerativeAI.Tools/Mcp/McpServerConfig.cs
Added McpTransportFactory static utility for creating stdio and HTTP transports with optional authentication and custom headers
Sample Demo
samples/McpIntegrationDemo/Program.cs
Created comprehensive MCP integration demo program demonstrating stdio transport, HTTP/SSE transport, multi-server scenarios, custom configuration, and auto-reconnection workflows
Integration Tests
tests/GenerativeAI.IntegrationTests/McpTool_Tests.cs, tests/GenerativeAI.IntegrationTests/McpTool_RealCalls_Tests.cs
Added extensive test suite covering transport factory creation, MCP server connection, tool discovery, function invocation, Gemini model integration, error handling, and complex multi-turn workflows

Sequence Diagram(s)

sequenceDiagram
    participant App as Application
    participant MT as McpTool
    participant MCP as MCP Server
    participant Gemini as Gemini Model

    App->>MT: CreateAsync(transport, options)
    MT->>MCP: Connect & Initialize
    MCP-->>MT: Server Capabilities
    MT->>MCP: ListTools()
    MCP-->>MT: Tool Definitions
    MT->>MT: Generate FunctionDeclarations

    App->>MT: AsTool()
    App->>Gemini: AttachTool(mcpTool)

    App->>Gemini: GenerateContent(prompt)
    Gemini->>App: FunctionCall
    App->>MT: CallAsync(functionCall)
    
    Note over MT: Auto-reconnect if needed
    MT->>MCP: Call Tool
    MCP-->>MT: Result
    MT->>MT: Convert to FunctionResponse
    MT-->>App: FunctionResponse
    App->>Gemini: SubmitFunctionResult()
    Gemini-->>App: Content

    App->>MT: DisposeAsync()
    MT->>MCP: Disconnect
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

  • McpTool.cs: Dense async/await logic with connection state management, auto-reconnection with configurable retries and timeouts, and bidirectional format conversion (MCP ↔ Gemini FunctionResponse)
  • Error handling and resilience: Multiple error paths with configurable throw/detailed-error behaviors; reconnection logic requires careful verification
  • Resource disposal: Complex IDisposable/IAsyncDisposable patterns with underlying MCP client lifecycle management
  • Test coverage: Extensive but homogeneous test patterns; requires validation that real MCP server interactions (stdio subprocess spawning, HTTP connectivity) work as expected
  • Integration points: Ensure McpTool properly inherits GoogleFunctionTool and integrates with existing Gemini model function-calling infrastructure

Poem

🐰 Hops of joy, MCP now flows!
Tools from servers, wherever one goes.
Stdio, HTTP, reconnection's grace,
Gemini's functions find their place.
A protocol bridge, swift and neat,
Making context integration complete! 🎉

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch claude/understand-tools-integration-011CUprRcsWXCWW9e1gbYNf9

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a5a0d85 and 1c41b53.

📒 Files selected for processing (9)
  • CLAUDE.md (1 hunks)
  • README.md (2 hunks)
  • samples/McpIntegrationDemo/McpIntegrationDemo.csproj (1 hunks)
  • samples/McpIntegrationDemo/Program.cs (1 hunks)
  • src/GenerativeAI.Tools/GenerativeAI.Tools.csproj (1 hunks)
  • src/GenerativeAI.Tools/Mcp/McpServerConfig.cs (1 hunks)
  • src/GenerativeAI.Tools/Mcp/McpTool.cs (1 hunks)
  • tests/GenerativeAI.IntegrationTests/McpTool_RealCalls_Tests.cs (1 hunks)
  • tests/GenerativeAI.IntegrationTests/McpTool_Tests.cs (1 hunks)

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@gunpal5 gunpal5 merged commit 8354991 into main Nov 8, 2025
2 of 3 checks passed
@gunpal5 gunpal5 deleted the claude/understand-tools-integration-011CUprRcsWXCWW9e1gbYNf9 branch November 8, 2025 09:13
@gunpal5 gunpal5 restored the claude/understand-tools-integration-011CUprRcsWXCWW9e1gbYNf9 branch November 8, 2025 09:13
@gunpal5 gunpal5 deleted the claude/understand-tools-integration-011CUprRcsWXCWW9e1gbYNf9 branch November 8, 2025 09:14
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