Skip to content

Add InProcessTransport #189

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

Merged
merged 1 commit into from
Apr 22, 2025
Merged

Conversation

dugenkui03
Copy link
Collaborator

@dugenkui03 dugenkui03 commented Apr 22, 2025

Summary by CodeRabbit

  • New Features
    • Added support for in-process client-server communication, enabling direct interaction between the client and server without network overhead.
  • Tests
    • Introduced comprehensive tests to verify in-process client functionality, including initialization, error handling, and all major operations.

More details in #185

Copy link
Contributor

coderabbitai bot commented Apr 22, 2025

Walkthrough

This change introduces an in-process transport mechanism for the MCP client-server architecture in Go. A new InProcessTransport type is added to the transport package, enabling direct, in-memory JSON-RPC communication with a server instance, bypassing network layers. A corresponding NewInProcessClient function is provided in the client package to create clients using this transport. Comprehensive unit tests are included to verify the correct behavior of the in-process client across initialization, error handling, and all major MCP operations, ensuring functional coverage and correctness of the new in-process communication path.

Changes

File(s) Change Summary
client/inprocess.go Adds NewInProcessClient, a function to create a client using an in-process transport linked directly to an MCPServer instance.
client/inprocess_test.go Introduces comprehensive unit tests for the in-process client, covering initialization, error handling, and all major MCP operations.
client/transport/inprocess.go Implements the InProcessTransport type, providing direct, in-memory JSON-RPC request/notification handling with an embedded MCPServer. Includes methods for sending requests/notifications, setting notification handlers, and start/close (as no-ops).
✨ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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: 2

🧹 Nitpick comments (4)
client/inprocess.go (1)

8-12: Implementation looks good but consider return type adjustment.

The function signature returns an error, but the implementation always returns nil for the error. Consider either:

  1. Adjusting the return type to just *Client since this function doesn't currently fail, or
  2. Adding a comment explaining why the error is part of the return value (e.g., for future-proofing)
-// NewInProcessClient connect directly to a mcp server object in the same process
-func NewInProcessClient(server *server.MCPServer) (*Client, error) {
+// NewInProcessClient connects directly to a mcp server object in the same process
+func NewInProcessClient(server *server.MCPServer) *Client {
 	inProcessTransport := transport.NewInProcessTransport(server)
-	return NewClient(inProcessTransport), nil
+	return NewClient(inProcessTransport)
}
client/transport/inprocess.go (2)

30-49: Consider optimizing the marshaling/unmarshaling flow.

The current implementation marshals the request to JSON, passes it to the server's HandleMessage, then marshals and unmarshals the response again. This approach works but introduces potential inefficiencies and error points through multiple serialization steps.

If server.MCPServer provides a method that can accept structured requests directly (or could be extended to do so), consider using that approach to eliminate the redundant marshaling/unmarshaling steps:

func (c *InProcessTransport) SendRequest(ctx context.Context, request JSONRPCRequest) (*JSONRPCResponse, error) {
-	requestBytes, err := json.Marshal(request)
-	if err != nil {
-		return nil, fmt.Errorf("failed to marshal request: %w", err)
-	}
-	requestBytes = append(requestBytes, '\n')
-
-	respMessage := c.server.HandleMessage(ctx, requestBytes)
-	respByte, err := json.Marshal(respMessage)
-	if err != nil {
-		return nil, fmt.Errorf("failed to marshal response message: %w", err)
-	}
-	rpcResp := JSONRPCResponse{}
-	err = json.Unmarshal(respByte, &rpcResp)
-	if err != nil {
-		return nil, fmt.Errorf("failed to unmarshal response message: %w", err)
-	}
-
-	return &rpcResp, nil
+	// If server could be extended with a method like HandleStructuredRequest
+	respMessage, err := c.server.HandleStructuredRequest(ctx, request)
+	if err != nil {
+		return nil, fmt.Errorf("failed to handle request: %w", err)
+	}
+	
+	return respMessage, nil
}

If modifying the server interface isn't possible, the current implementation is correct but less efficient.


51-60: Notification response is discarded without checks.

The server's response to the notification is discarded without any verification. While this follows the JSON-RPC specification (notifications don't expect responses), it might be worth adding a comment explaining this behavior to avoid confusion.

func (c *InProcessTransport) SendNotification(ctx context.Context, notification mcp.JSONRPCNotification) error {
	notificationBytes, err := json.Marshal(notification)
	if err != nil {
		return fmt.Errorf("failed to marshal notification: %w", err)
	}
	notificationBytes = append(notificationBytes, '\n')
-	c.server.HandleMessage(ctx, notificationBytes)
+	// Per JSON-RPC spec, notifications don't expect responses, so we discard the result
+	_ = c.server.HandleMessage(ctx, notificationBytes)

	return nil
}
client/inprocess_test.go (1)

160-406: Consider reducing test duplication with setup helper.

Each test repeats similar setup code for creating, starting, and initializing the client. This leads to significant code duplication across the test functions.

Consider refactoring to use a helper function that handles the common setup and returns an initialized client:

+func setupInitializedClient(t *testing.T, mcpServer *server.MCPServer) *Client {
+	client, err := NewInProcessClient(mcpServer)
+	if err != nil {
+		t.Fatalf("Failed to create client: %v", err)
+	}
+	
+	if err := client.Start(context.Background()); err != nil {
+		t.Fatalf("Failed to start client: %v", err)
+	}
+	
+	// Initialize
+	initRequest := mcp.InitializeRequest{}
+	initRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION
+	initRequest.Params.ClientInfo = mcp.Implementation{
+		Name:    "test-client",
+		Version: "1.0.0",
+	}
+	
+	_, err = client.Initialize(context.Background(), initRequest)
+	if err != nil {
+		t.Fatalf("Failed to initialize: %v", err)
+	}
+	
+	return client
+}

Then use this helper in each test:

t.Run("ListTools", func(t *testing.T) {
-	client, err := NewInProcessClient(mcpServer)
-	if err != nil {
-		t.Fatalf("Failed to create client: %v", err)
-	}
-	defer client.Close()
-
-	if err := client.Start(context.Background()); err != nil {
-		t.Fatalf("Failed to start client: %v", err)
-	}
-
-	// Initialize
-	initRequest := mcp.InitializeRequest{}
-	initRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION
-	initRequest.Params.ClientInfo = mcp.Implementation{
-		Name:    "test-client",
-		Version: "1.0.0",
-	}
-
-	_, err = client.Initialize(context.Background(), initRequest)
-	if err != nil {
-		t.Fatalf("Failed to initialize: %v", err)
-	}
+	client := setupInitializedClient(t, mcpServer)
+	defer client.Close()

	request := mcp.ListToolsRequest{}
	result, err := client.ListTools(context.Background(), request)
	if err != nil {
		t.Errorf("ListTools failed: %v", err)
	}

	if len(result.Tools) != 1 {
		t.Errorf("Expected 1 tool, got %d", len(result.Tools))
	}
})

This would significantly reduce code duplication and make the tests more maintainable.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9f39a43 and fad89b2.

📒 Files selected for processing (3)
  • client/inprocess.go (1 hunks)
  • client/inprocess_test.go (1 hunks)
  • client/transport/inprocess.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
client/inprocess.go (2)
client/client.go (2)
  • Client (16-24)
  • NewClient (34-38)
client/transport/inprocess.go (1)
  • NewInProcessTransport (20-24)
client/transport/inprocess.go (1)
mcp/types.go (1)
  • JSONRPCNotification (192-195)
🔇 Additional comments (3)
client/inprocess_test.go (3)

11-83: Good test setup with comprehensive server configuration.

The test setup is thorough and well-structured, establishing a complete test environment with tools, resources, and prompts. This provides excellent coverage for testing the in-process client's integration with the server.


85-139: Comprehensive initialization and basic functionality test.

This test effectively verifies the client initialization and basic functionality, including the verification of tool annotations.


141-158: Good error case testing.

The test properly verifies that the client behaves as expected when trying to make requests before initialization. Testing error cases is an important aspect of robust test coverage.

@ezynda3 ezynda3 merged commit 6760d87 into mark3labs:main Apr 22, 2025
2 checks passed
wangchaodeyuzhou pushed a commit to wangchaodeyuzhou/mcp-go that referenced this pull request Apr 23, 2025
adlternative pushed a commit to adlternative/mcp-go that referenced this pull request May 20, 2025
@coderabbitai coderabbitai bot mentioned this pull request Jun 7, 2025
16 tasks
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