Skip to content

Conversation

forehalo
Copy link
Member

@forehalo forehalo commented Jul 23, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a new endpoint for MCP (Model Context Protocol) server interaction under /api/workspaces/:workspaceId/mcp, enabling advanced document reading and search capabilities within workspaces.
    • Added support for semantic and keyword search tools, as well as document reading through the MCP server, with user access control and input validation.
  • Improvements

    • Enhanced metadata handling in semantic search results for improved clarity.
    • Streamlined internal imports and refactored utility functions for better maintainability.
  • Chores

    • Added a new SDK dependency to the backend server package.

Copy link
Contributor

coderabbitai bot commented Jul 23, 2025

Warning

Rate limit exceeded

@forehalo has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 14 minutes and 15 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between c769279 and 4cb6d9e.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (9)
  • packages/backend/server/package.json (1 hunks)
  • packages/backend/server/src/plugins/copilot/context/resolver.ts (1 hunks)
  • packages/backend/server/src/plugins/copilot/index.ts (2 hunks)
  • packages/backend/server/src/plugins/copilot/mcp/controller.ts (1 hunks)
  • packages/backend/server/src/plugins/copilot/mcp/provider.ts (1 hunks)
  • packages/backend/server/src/plugins/copilot/tools/doc-semantic-search.ts (1 hunks)
  • packages/backend/server/src/plugins/copilot/types.ts (0 hunks)
  • packages/backend/server/src/plugins/copilot/utils.ts (2 hunks)
  • packages/backend/server/src/plugins/copilot/workspace/resolver.ts (1 hunks)

Walkthrough

This change introduces a new Model Context Protocol (MCP) integration into the backend server. It adds a new dependency, defines provider and controller classes for MCP functionality, registers new tools for document access and search, and refactors utility functions for embedding chunk processing. Import statements and constant definitions are updated accordingly.

Changes

File(s) Change Summary
Dependency Update
packages/backend/server/package.json
Added @modelcontextprotocol/sdk dependency.
Module Registration
packages/backend/server/src/plugins/copilot/index.ts
Added WorkspaceMcpController to controllers and WorkspaceMcpProvider to providers in CopilotModule.
MCP Controller Implementation
packages/backend/server/src/plugins/copilot/mcp/controller.ts
Introduced new WorkspaceMcpController class with POST endpoint handling MCP server transport and error responses.
MCP Provider Implementation
packages/backend/server/src/plugins/copilot/mcp/provider.ts
Added WorkspaceMcpProvider class that creates MCP server instances with registered tools for document access and search.
Utility Refactor
packages/backend/server/src/plugins/copilot/utils.ts
Added MAX_EMBEDDABLE_SIZE constant and clearEmbeddingChunk function; updated imports accordingly.
Import Consolidation
packages/backend/server/src/plugins/copilot/context/resolver.ts
Consolidated imports to source MAX_EMBEDDABLE_SIZE from ../utils.
Import Update
packages/backend/server/src/plugins/copilot/workspace/resolver.ts
Updated import of MAX_EMBEDDABLE_SIZE to use ../utils.
Semantic Search Tool Refactor
packages/backend/server/src/plugins/copilot/tools/doc-semantic-search.ts
Replaced local clearEmbeddingChunk with import from ../utils.
Type Cleanup
packages/backend/server/src/plugins/copilot/types.ts
Removed export and definition of MAX_EMBEDDABLE_SIZE.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant WorkspaceMcpController
    participant WorkspaceMcpProvider
    participant McpServer
    participant StreamableHTTPServerTransport

    Client->>WorkspaceMcpController: POST /api/workspaces/:workspaceId/mcp
    WorkspaceMcpController->>WorkspaceMcpProvider: for(userId, workspaceId)
    WorkspaceMcpProvider->>McpServer: create instance, register tools
    WorkspaceMcpProvider-->>WorkspaceMcpController: return McpServer
    WorkspaceMcpController->>StreamableHTTPServerTransport: create instance
    WorkspaceMcpController->>McpServer: connect(transport)
    WorkspaceMcpController->>StreamableHTTPServerTransport: handleRequest(req, res, body)
    Note right of WorkspaceMcpController: On response close, clean up resources
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • fengmk2
  • pengx17

Poem

In the warren where code does hop,
A new MCP server makes a stop!
With tools for search and docs to read,
And cleaner chunks for every need.
Refactored imports, dependencies new—
This backend’s got a shiny view!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 61/mcp

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests 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

codecov bot commented Jul 23, 2025

Codecov Report

❌ Patch coverage is 26.52330% with 205 lines in your changes missing coverage. Please review.
✅ Project coverage is 57.29%. Comparing base (feb42e3) to head (4cb6d9e).
⚠️ Report is 2 commits behind head on canary.

Files with missing lines Patch % Lines
...backend/server/src/plugins/copilot/mcp/provider.ts 11.76% 150 Missing ⚠️
...ckend/server/src/plugins/copilot/mcp/controller.ts 43.47% 39 Missing ⚠️
...ckages/backend/server/src/plugins/copilot/utils.ts 50.00% 16 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           canary   #13298      +/-   ##
==========================================
- Coverage   57.37%   57.29%   -0.09%     
==========================================
  Files        2712     2714       +2     
  Lines      133675   133918     +243     
  Branches    20756    20757       +1     
==========================================
+ Hits        76698    76728      +30     
+ Misses      55313    54986     -327     
- Partials     1664     2204     +540     
Flag Coverage Δ
server-test 79.41% <26.52%> (-0.27%) ⬇️
unittest 32.12% <ø> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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 (2)
packages/backend/server/src/plugins/copilot/mcp/provider.ts (2)

148-153: Consider returning structured data instead of JSON strings

Each document is individually JSON stringified, which requires clients to parse each string separately. Consider returning structured data or stringifying the entire array.

 return {
   content: docs.map(doc => ({
     type: 'text',
-    text: JSON.stringify(pick(doc, 'docId', 'title', 'createdAt')),
+    text: `${doc.title} (ID: ${doc.docId}, Created: ${doc.createdAt})`,
   })),
 };

Or if JSON is required:

 return {
-  content: docs.map(doc => ({
-    type: 'text',
-    text: JSON.stringify(pick(doc, 'docId', 'title', 'createdAt')),
-  })),
+  content: [{
+    type: 'text',
+    text: JSON.stringify(docs.map(doc => pick(doc, 'docId', 'title', 'createdAt'))),
+  }],
 };

84-128: Consider consistent AbortSignal support across tools

The Semantic Search tool accepts and uses an AbortSignal (line 102), but the Keyword Search tool doesn't. For consistency and better cancellation support, consider adding signal support to all tools.

-      async ({ query }) => {
+      async ({ query }, req) => {
         query = query.trim();
         if (!query) {
           return {
             isError: true,
             content: [
               {
                 type: 'text',
                 text: 'Query is required for keyword search.',
               },
             ],
           };
         }

-        let docs = await this.indexer.searchDocsByKeyword(workspaceId, query);
+        let docs = await this.indexer.searchDocsByKeyword(workspaceId, query, req.signal);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ff9a4f4 and b8d86e2.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (9)
  • packages/backend/server/package.json (1 hunks)
  • packages/backend/server/src/plugins/copilot/context/resolver.ts (1 hunks)
  • packages/backend/server/src/plugins/copilot/index.ts (2 hunks)
  • packages/backend/server/src/plugins/copilot/mcp/controller.ts (1 hunks)
  • packages/backend/server/src/plugins/copilot/mcp/provider.ts (1 hunks)
  • packages/backend/server/src/plugins/copilot/tools/doc-semantic-search.ts (1 hunks)
  • packages/backend/server/src/plugins/copilot/types.ts (0 hunks)
  • packages/backend/server/src/plugins/copilot/utils.ts (2 hunks)
  • packages/backend/server/src/plugins/copilot/workspace/resolver.ts (1 hunks)
🧬 Code Graph Analysis (2)
packages/backend/server/src/plugins/copilot/utils.ts (1)
packages/backend/server/src/models/common/copilot.ts (1)
  • ChunkSimilarity (96-100)
packages/backend/server/src/plugins/copilot/mcp/provider.ts (3)
packages/backend/server/src/plugins/copilot/context/index.ts (1)
  • CopilotContextService (2-2)
packages/backend/server/src/plugins/indexer/index.ts (1)
  • IndexerService (28-28)
packages/backend/server/src/plugins/copilot/utils.ts (1)
  • clearEmbeddingChunk (63-79)
💤 Files with no reviewable changes (1)
  • packages/backend/server/src/plugins/copilot/types.ts
🧰 Additional context used
🧬 Code Graph Analysis (2)
packages/backend/server/src/plugins/copilot/utils.ts (1)
packages/backend/server/src/models/common/copilot.ts (1)
  • ChunkSimilarity (96-100)
packages/backend/server/src/plugins/copilot/mcp/provider.ts (3)
packages/backend/server/src/plugins/copilot/context/index.ts (1)
  • CopilotContextService (2-2)
packages/backend/server/src/plugins/indexer/index.ts (1)
  • IndexerService (28-28)
packages/backend/server/src/plugins/copilot/utils.ts (1)
  • clearEmbeddingChunk (63-79)
⏰ 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). (53)
  • GitHub Check: y-octo binding test on x86_64-unknown-linux-gnu
  • GitHub Check: fuzzing
  • GitHub Check: y-octo binding test on x86_64-pc-windows-msvc
  • GitHub Check: y-octo binding test on aarch64-apple-darwin
  • GitHub Check: y-octo binding test on aarch64-unknown-linux-gnu
  • GitHub Check: y-octo binding test on x86_64-apple-darwin
  • GitHub Check: y-octo binding test on aarch64-pc-windows-msvc
  • GitHub Check: E2E Mobile Test (5)
  • GitHub Check: E2E Mobile Test (3)
  • GitHub Check: E2E Mobile Test (4)
  • GitHub Check: Run native tests
  • GitHub Check: E2E Mobile Test (1)
  • GitHub Check: E2E Mobile Test (2)
  • GitHub Check: Build @affine/electron renderer
  • GitHub Check: E2E BlockSuite Cross Browser Test (2, chromium)
  • GitHub Check: E2E BlockSuite Cross Browser Test (1, firefox)
  • GitHub Check: E2E Test (7)
  • GitHub Check: Lint Rust
  • GitHub Check: E2E BlockSuite Cross Browser Test (2, webkit)
  • GitHub Check: E2E Test (9)
  • GitHub Check: E2E BlockSuite Cross Browser Test (2, firefox)
  • GitHub Check: E2E BlockSuite Cross Browser Test (1, chromium)
  • GitHub Check: E2E BlockSuite Cross Browser Test (1, webkit)
  • GitHub Check: E2E BlockSuite Test (2)
  • GitHub Check: E2E Test (10)
  • GitHub Check: E2E Test (8)
  • GitHub Check: Build Server native
  • GitHub Check: E2E Test (6)
  • GitHub Check: E2E Test (1)
  • GitHub Check: E2E Test (2)
  • GitHub Check: E2E BlockSuite Test (9)
  • GitHub Check: E2E Test (5)
  • GitHub Check: E2E Test (4)
  • GitHub Check: E2E BlockSuite Test (8)
  • GitHub Check: E2E BlockSuite Test (10)
  • GitHub Check: E2E BlockSuite Test (7)
  • GitHub Check: E2E Test (3)
  • GitHub Check: E2E BlockSuite Test (3)
  • GitHub Check: E2E BlockSuite Test (6)
  • GitHub Check: E2E BlockSuite Test (1)
  • GitHub Check: loom thread test
  • GitHub Check: E2E BlockSuite Test (5)
  • GitHub Check: E2E BlockSuite Test (4)
  • GitHub Check: Build AFFiNE native (x86_64-pc-windows-msvc)
  • GitHub Check: Build AFFiNE native (aarch64-pc-windows-msvc)
  • GitHub Check: Analyze (typescript, affine)
  • GitHub Check: Build AFFiNE native (x86_64-apple-darwin)
  • GitHub Check: Build AFFiNE native (aarch64-apple-darwin)
  • GitHub Check: Build AFFiNE native (x86_64-unknown-linux-gnu)
  • GitHub Check: Analyze (typescript, blocksuite)
  • GitHub Check: Analyze (javascript, affine)
  • GitHub Check: Typecheck
  • GitHub Check: Analyze (javascript, blocksuite)
🔇 Additional comments (12)
packages/backend/server/src/plugins/copilot/workspace/resolver.ts (1)

30-30: LGTM: Import consolidation looks good.

The import path change from ../types to ../utils for MAX_EMBEDDABLE_SIZE aligns with the refactoring effort to consolidate utility constants.

packages/backend/server/package.json (1)

43-43: Confirmed latest version and security status

  • npm view @modelcontextprotocol/sdk reports 1.16.0 as the current release.
  • An isolated npm audit on a clean install of v1.16.0 shows zero vulnerabilities.

No further action needed—this dependency addition is up to date and has no known NPM‐level issues.

packages/backend/server/src/plugins/copilot/context/resolver.ts (1)

53-53: LGTM: Clean import consolidation.

The consolidation of imports from separate modules (../types and ../utils) into a single import from ../utils improves code organization and is consistent with the refactoring pattern across the codebase.

packages/backend/server/src/plugins/copilot/tools/doc-semantic-search.ts (1)

10-10: LGTM: Good refactoring to use shared utility function.

Replacing the local clearEmbeddingChunk definition with an import from the shared ../utils module promotes code reuse and consistency across the codebase.

packages/backend/server/src/plugins/copilot/index.ts (3)

20-21: LGTM: Proper import additions for MCP integration.

The new imports for WorkspaceMcpController and WorkspaceMcpProvider are correctly added to support the MCP functionality.


83-84: LGTM: Correct provider registration.

The WorkspaceMcpProvider is properly added to the providers array with appropriate commenting for organization.


86-86: LGTM: Proper controller registration.

The WorkspaceMcpController is correctly added to the controllers array alongside the existing CopilotController.

packages/backend/server/src/plugins/copilot/mcp/controller.ts (1)

21-24: Confirm Stateless Configuration for MCP Transport

Setting sessionIdGenerator to undefined disables session‐ID generation and switches the transport into fully stateless mode. In this mode, the server will:

  • Not track or resume client sessions
  • Treat each request as independent (no context is carried over)
  • Lose features that rely on session state (e.g., resumability, client-specific data handling)

Please verify that you intend to operate in stateless mode. If you require stateful behavior—such as session resumption or per-client context—you should provide a valid sessionIdGenerator function instead of undefined.

File to review:

  • packages/backend/server/src/plugins/copilot/mcp/controller.ts (around line 23)
packages/backend/server/src/plugins/copilot/utils.ts (1)

63-79: LGTM! Well-implemented chunk cleaning function

The function correctly removes metadata lines while preserving immutability and handling edge cases.

packages/backend/server/src/plugins/copilot/mcp/provider.ts (3)

22-28: Good security practice with permission check

The method properly validates user access before creating the MCP server instance.


30-76: Well-implemented tool with proper access control

The Read Document tool correctly:

  • Validates access permissions before reading
  • Returns consistent error messages that don't leak access information
  • Handles both not found and permission denied cases uniformly

113-119: Verify CallToolResult.content structure

File: packages/backend/server/src/plugins/copilot/mcp/provider.ts
Lines: 113–119

return {
  content: docs.map(doc => ({
    type: 'text',
    text: clearEmbeddingChunk(doc).content,
  })),
};

Ensure this object shape matches the CallToolResult interface imported from @modelcontextprotocol/sdk/types.js. In particular, confirm that each item in content uses the exact property names and includes any required fields (e.g., metadata, source identifiers) as defined by CallToolResult. Adjust the mapping if additional properties are expected.

Copy link

perfsee bot commented Jul 23, 2025

affine-toeverything

Bundle main

diff ------------------- Bundle Size Diff -------------------------

@@                       EntryPoint: index                       @@
##                     canary         61/mcp                 +/- ##
===================================================================
> Bundle              27.8 MB        27.8 MB     -7.7 kB(-0.03%)   
> Initial JS          13.2 MB        13.2 MB     -8.1 kB(-0.06%)   
= Initial CSS          346 kB         346 kB                       
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
= Assets                   95             95                       
= Chunks                   93             93                       
= Packages                269            269                       
= Duplicates                5              5                       
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Warnings ~~~~~~~~~~~~~~~~~~~~~~~~~~~#
! Deduplicate versions of libraries                                
! Separate mixed content assets files                              
! Avoid cache wasting                                              

@forehalo forehalo force-pushed the 61/mcp branch 2 times, most recently from 73348a1 to cadb17a Compare July 28, 2025 08:43
@forehalo forehalo force-pushed the 61/mcp branch 2 times, most recently from 579f384 to c769279 Compare July 31, 2025 05:40
@forehalo forehalo added this pull request to the merge queue Jul 31, 2025
Merged via the queue into canary with commit 8d889fc Jul 31, 2025
109 checks passed
@forehalo forehalo deleted the 61/mcp branch July 31, 2025 06:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: No status
Development

Successfully merging this pull request may close these issues.

2 participants