Skip to content

Conversation

@Maidang1
Copy link
Contributor

@Maidang1 Maidang1 commented Apr 11, 2025

Summary by CodeRabbit

  • Documentation

    • Updated guides now include details on a new MCP plugin.
    • Added a dedicated resource explaining setup and development commands for a Farm + React template.
  • New Features

    • Introduced a sample Farm + React project featuring interactive UI elements.
    • Enhanced integration with the MCP plugin to streamline development workflows.

@coderabbitai
Copy link

coderabbitai bot commented Apr 11, 2025

Walkthrough

This pull request integrates a new "mcp" plugin into the Farm ecosystem. It updates the main documentation and adds a complete Farm + React example project with configuration files, HTML, scripts, styles, and TypeScript support. In addition, a dedicated plugin package is provided under the js-plugins/mcp directory, including build configurations, server functionalities with SSE support, route setup, and utility functions for workspace management.

Changes

File(s) Change Summary
README.md Updated documentation with a new entry for the "mcp" plugin inspired by nuxt-mcp.
examples/mcp/... Added a new Farm + React template including README, configuration (farm.config.ts), HTML, JS, CSS, TSX files, TypeScript typings, and configuration files (tsconfig.json, tsconfig.node.json) for project setup and development.
js-plugins/mcp/... Introduced a new MCP plugin package with a dedicated .gitignore, configuration (farm.config.ts), package metadata, and source files (connect.ts, index.ts, search-root.ts, server.ts, types.ts) along with its TypeScript configuration (tsconfig.json), enabling plugin functionality.

Sequence Diagram(s)

sequenceDiagram
  participant Dev as Developer
  participant FDS as Farm Dev Server
  participant MCP as farmPluginMcp Plugin
  participant MS as McpServer
  participant SR as SetupRoutes

  Dev ->> FDS: Start Dev Server
  FDS ->> MCP: Initialize plugin with options
  MCP ->> MS: Create default MCP server (createMcpDefaultServer)
  MCP ->> SR: Setup middleware routes (setupRoutes)
  SR ->> MS: Establish SSE & POST endpoints
  MCP -->> FDS: Update configurations and log URL
Loading

Poem

In my burrow, code sprouts anew,
With mcp plugins shining through!
Farm and React in fields of dreams,
Where configs flow like crystal streams.
I hop with joy, my whiskers sing,
Celebrating harvests that coding brings!

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ 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 plan to trigger planning for file edits and PR creation.
  • @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

@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: 17

🧹 Nitpick comments (32)
examples/mcp/index.html (1)

1-15: HTML structure is well formed but review script source handling.

The document is correctly structured with necessary meta tags, a favicon, and a designated root element for your React application. However, the <script src="./src/index.tsx"></script> element directly references a TypeScript file. Please ensure your build/bundler configuration supports in-browser TS transpilation or update the reference to point to a precompiled JavaScript bundle for production use.

examples/mcp/README.md (2)

1-4: Add context about what MCP plugin is used for

While the README provides good setup instructions, it doesn't explain what the MCP plugin is or what it does. Consider adding a brief description about the purpose of this example and what capabilities the MCP plugin provides.


27-28: Improve wording of preview section heading

The phrase "Preview the Production build product" sounds a bit awkward. Consider rewording to something clearer like "Preview the production build".

examples/mcp/farm.config.ts (1)

4-16: Document empty MCP plugin configuration object

The MCP plugin is initialized with an empty object ({}). If there are configurable options for this plugin, consider documenting them with comments or adding them as examples, even if you're using defaults. This would help future developers understand what can be configured.

js-plugins/mcp/package.json (3)

4-4: Add a meaningful description

The description field is empty. Add a concise description of what the MCP plugin does to help users understand its purpose.


21-21: Consider using pnpm consistently

The prepublishOnly script uses npm run build while the example project uses pnpm. Consider using pnpm consistently throughout the codebase, changing this to pnpm run build for consistency.


23-25: Add keywords and author information

Adding relevant keywords will improve discoverability of the package. Also, consider adding author information for proper attribution.

examples/mcp/src/index.tsx (1)

5-6: Remove extra empty lines

There are two consecutive empty lines here. Consider removing one to maintain consistent formatting.

examples/mcp/src/main.tsx (1)

7-7: Remove or conditionally use console.log statement

Console logs should generally be avoided in production code as they can impact performance and expose implementation details to users.

Consider using a development-only console log or removing it entirely:

-  console.log("rendering Main component")
+  if (process.env.NODE_ENV === 'development') {
+    console.log("rendering Main component")
+  }

Or simply remove it if it's not needed for debugging.

js-plugins/mcp/src/types.ts (2)

29-31: Fix typo in JSDoc comment

There's a small typo in the JSDoc comment.

-   * The MCP server info. Ingored when `mcpServer` is provided
+   * The MCP server info. Ignored when `mcpServer` is provided
    */

53-55: Update default server name in JSDoc comments

The JSDoc comments refer to "vite" as the default server name, but this appears to be a Farm plugin. Consider updating the references to reflect the correct default value.

    /**
-     * The name of the MCP server, default is `vite`
+     * The name of the MCP server, default is `farm`
     */

And:

    /**
-     * The name of the MCP server, default is `vite`
+     * The name of the MCP server, default is `farm`
     */

Also applies to: 67-69

examples/mcp/src/index.css (1)

1-69: Clean and well-structured CSS with consistent styling

The CSS file provides a comprehensive set of global styles with good organization and separation of concerns. It properly handles both dark and light color schemes and includes appropriate accessibility considerations like focus states.

However, consider using CSS variables for colors to improve maintainability:

 :root {
   font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
   line-height: 1.5;
   font-weight: 400;

   color-scheme: light dark;
+  --primary-color: #9f1a8f;
   color: rgba(255, 255, 255, 0.87);
   background-color: #242424;
   
   /* ... other properties ... */
 }

 a {
   font-weight: 500;
-  color: #9f1a8f;
+  color: var(--primary-color);
   text-decoration: inherit;
 }
 a:hover {
-  color: #9f1a8f;
+  color: var(--primary-color);
 }

 /* ... other rules ... */

 button:hover {
-  border-color: #9f1a8f;
+  border-color: var(--primary-color);
 }

 /* ... media query ... */
 a:hover {
-  color: #9F1A8F;
+  color: var(--primary-color);
 }
js-plugins/mcp/farm.config.ts (2)

18-24: Consider making the test pattern more specific

The current regex pattern [.+] in enforceResources might be too broad and could potentially match more files than intended.

 partialBundling: {
   enforceResources: [
     {
       name: 'index',
-      test: ['.+']
+      test: ['^\\./src/.+'] // More specific pattern targeting only src files
     }
   ]
 },

7-41: The configuration is well-structured but lacks documentation

The Farm configuration contains all necessary settings but could benefit from some inline documentation to explain the purpose of different sections, especially for maintainers who are not familiar with Farm.

Consider adding comments to explain the purpose of key configuration sections like partialBundling, persistentCache, etc.

js-plugins/mcp/src/server.ts (3)

19-33: Consider using proper typing for tool return values

The tool function returns a content object with a specific structure, but there's no type definition for this return value, which could lead to inconsistencies.

Consider defining an interface for the return value structure to ensure consistency across all tool implementations.


41-41: Use const instead of let for variables that aren't reassigned

The variable resource is declared with let but never reassigned, so it should use const instead.

- let resource = compiler.resourcesMap[filepath as keyof typeof compiler.resourcesMap] as Resource
+ const resource = compiler.resourcesMap[filepath as keyof typeof compiler.resourcesMap] as Resource
🧰 Tools
🪛 Biome (1.9.4)

[error] 41-41: This let declares a variable that is only assigned once.

'resource' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


8-59: Add a return type annotation to the exported function

The createMcpDefaultServer function doesn't have an explicit return type annotation, which would improve code readability and maintainability.

- export const createMcpDefaultServer = async (options: FarmMcpOptions, compiler: Compiler) => {
+ export const createMcpDefaultServer = async (options: FarmMcpOptions, compiler: Compiler): Promise<McpServer> => {
🧰 Tools
🪛 Biome (1.9.4)

[error] 41-41: This let declares a variable that is only assigned once.

'resource' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)

js-plugins/mcp/tsconfig.json (1)

5-6: Consider enabling stricter TypeScript linting rules

The settings noUnusedParameters and noUnusedLocals are set to false, which allows unused variables and parameters in the codebase. This can lead to code quality issues and make maintenance more difficult.

I recommend enabling these checks to maintain a cleaner codebase:

-    "noUnusedParameters": false,
-    "noUnusedLocals": false,
+    "noUnusedParameters": true,
+    "noUnusedLocals": true,
examples/mcp/package.json (2)

14-15: Pin React version for reproducible builds

React version is specified only as "18" without an exact patch version, which could lead to inconsistent behavior if the latest 18.x.x version changes.

For more reproducible builds, consider using a specific version:

-    "react": "18",
-    "react-dom": "18",
+    "react": "^18.2.0",
+    "react-dom": "^18.2.0",

22-24: Match React types version with React runtime version

For better type safety, the TypeScript definitions for React should match the React version being used.

-    "@types/react": "18",
-    "@types/react-dom": "18",
+    "@types/react": "^18.2.0",
+    "@types/react-dom": "^18.2.0",
js-plugins/mcp/src/index.ts (4)

26-26: Use const for variables that aren't reassigned

The farmConfig variable is declared with let but is never reassigned. Use const for better code clarity.

-  let farmConfig: ResolvedUserConfig = {}
+  const farmConfig: ResolvedUserConfig = {}
🧰 Tools
🪛 Biome (1.9.4)

[error] 26-26: This let declares a variable that is only assigned once.

'farmConfig' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


38-38: Remove commented out code

There's a commented out line that should be removed.

-      // const config = 

36-36: Remove redundant fallback value

The mcpPath parameter already has a default value when destructured from options, making the fallback here redundant.

-      setupRoutes(mcpPath || '/__mcp', mcp, server);
+      setupRoutes(mcpPath, mcp, server);

71-75: Consider explaining the setTimeout usage

There's a 300ms delay before printing the URL, but it's not clear why this delay is necessary.

Consider adding a comment explaining the reason for the delay:

       if (printUrl) {
+        // Delay printing to ensure it appears after other startup logs
         setTimeout(() => {
           console.log(`${p.yellow(`  ➜  MCP: Server is running at ${sseUrl}`)}`)
         }, 300)
       }
js-plugins/mcp/src/connect.ts (1)

10-24: Improve structure of the first middleware function

The middleware function has unnecessary whitespace and could be structured better.

   farmServer.applyMiddlewares([() => {
-
     return async (ctx: Context, next: Next) => {
       if (!ctx.url.includes(`${base}/sse`)) {
         return next()
       }
       const transport = new SSEServerTransport(`${base}/messages`, ctx.res);
       transports.set(transport.sessionId, transport);
       ctx.res.on('close', () => {
         transports.delete(transport.sessionId);
       });
       await mcpServer.connect(transport)
     }
-
   }])
js-plugins/mcp/src/search-root.ts (7)

1-1: Fix typo in attribution comment.

There's a typographical error in the first line: "copy form vite" should be "copy from vite".

-// copy form vite https://github.com/vitejs/vite/blob/e360f0a65426f576cd25f14cafbd6005df78dbf0/packages/vite/src/node/server/searchRoot.ts#L63
+// copy from vite https://github.com/vitejs/vite/blob/e360f0a65426f576cd25f14cafbd6005df78dbf0/packages/vite/src/node/server/searchRoot.ts#L63

5-12: Make the return value in catch block explicit.

The function currently has an implicit undefined return in the catch block. For better readability, consider making this explicit.

export function tryStatSync(file: string): fs.Stats | undefined {
  try {
    // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist
    return fs.statSync(file, { throwIfNoEntry: false })
  } catch {
    // Ignore errors
+    return undefined
  }
}

31-46: Consider adding explanations for commented-out files.

Several potential root files are commented out. It would be helpful to add a brief comment explaining why these files are excluded from the active list, especially since you've kept the explanatory URLs.


63-65: Consider using isFileReadable for consistency.

This function uses fs.existsSync(), while other parts of the codebase use the more comprehensive isFileReadable() function. For consistency and to ensure files are not only present but also readable, consider using isFileReadable.

function hasRootFile(root: string): boolean {
-  return ROOT_FILES.some((file) => fs.existsSync(join(root, file)))
+  return ROOT_FILES.some((file) => isFileReadable(join(root, file)))
}

67-70: Add return type and consider using isFileReadable.

This function is missing an explicit return type and uses fs.existsSync() instead of isFileReadable(). Consider adding the return type and using isFileReadable for consistency.

-function hasPackageJSON(root: string) {
+function hasPackageJSON(root: string): boolean {
  const path = join(root, 'package.json')
-  return fs.existsSync(path)
+  return isFileReadable(path)
}

75-83: Consider documenting the root parameter.

The root parameter with its default value of current might be confusing. Consider adding a JSDoc comment explaining that this parameter represents the original starting point which is returned if no package.json is found.

/**
 * Search up for the nearest `package.json`
+ * @param current The directory to start searching from
+ * @param root The fallback directory to return if no package.json is found (defaults to current)
+ * @returns The directory containing package.json or the root directory if none found
 */
export function searchForPackageRoot(current: string, root = current): string {

88-100: Consider documenting the parameters for consistency.

Similar to the recommendation for searchForPackageRoot, adding JSDoc comments for the parameters would improve clarity.

/**
 * Search up for the nearest workspace root
+ * @param current The directory to start searching from
+ * @param root The fallback directory to return if no workspace root is found (defaults to package root)
+ * @returns The directory containing workspace configuration or the root directory if none found
 */
export function searchForWorkspaceRoot(
  current: string,
  root = searchForPackageRoot(current),
): string {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7805365 and e181512.

⛔ Files ignored due to path filters (4)
  • examples/mcp/public/favicon.ico is excluded by !**/*.ico
  • examples/mcp/src/assets/logo.png is excluded by !**/*.png
  • examples/mcp/src/assets/react.svg is excluded by !**/*.svg
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (22)
  • README.md (1 hunks)
  • examples/mcp/README.md (1 hunks)
  • examples/mcp/farm.config.ts (1 hunks)
  • examples/mcp/index.html (1 hunks)
  • examples/mcp/index.js (1 hunks)
  • examples/mcp/package.json (1 hunks)
  • examples/mcp/src/index.css (1 hunks)
  • examples/mcp/src/index.tsx (1 hunks)
  • examples/mcp/src/main.css (1 hunks)
  • examples/mcp/src/main.tsx (1 hunks)
  • examples/mcp/src/typings.d.ts (1 hunks)
  • examples/mcp/tsconfig.json (1 hunks)
  • examples/mcp/tsconfig.node.json (1 hunks)
  • js-plugins/mcp/.gitignore (1 hunks)
  • js-plugins/mcp/farm.config.ts (1 hunks)
  • js-plugins/mcp/package.json (1 hunks)
  • js-plugins/mcp/src/connect.ts (1 hunks)
  • js-plugins/mcp/src/index.ts (1 hunks)
  • js-plugins/mcp/src/search-root.ts (1 hunks)
  • js-plugins/mcp/src/server.ts (1 hunks)
  • js-plugins/mcp/src/types.ts (1 hunks)
  • js-plugins/mcp/tsconfig.json (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
examples/mcp/src/main.tsx (1)
examples/babel-react-compiler/src/App.jsx (1)
  • count (4-4)
examples/mcp/src/index.tsx (1)
examples/mcp/src/main.tsx (1)
  • Main (5-32)
js-plugins/mcp/src/index.ts (4)
js-plugins/mcp/src/types.ts (1)
  • FarmMcpOptions (10-71)
js-plugins/mcp/src/server.ts (1)
  • createMcpDefaultServer (8-59)
js-plugins/mcp/src/connect.ts (1)
  • setupRoutes (7-58)
js-plugins/mcp/src/search-root.ts (1)
  • searchForWorkspaceRoot (88-100)
🪛 Biome (1.9.4)
examples/mcp/src/main.tsx

[error] 11-11: Avoid using target="_blank" without rel="noreferrer".

Opening external links in new tabs without rel="noreferrer" is a security risk. See the explanation for more details.
Safe fix: Add the rel="noreferrer" attribute.

(lint/a11y/noBlankTarget)


[error] 14-14: Avoid using target="_blank" without rel="noreferrer".

Opening external links in new tabs without rel="noreferrer" is a security risk. See the explanation for more details.
Safe fix: Add the rel="noreferrer" attribute.

(lint/a11y/noBlankTarget)


[error] 20-20: Provide an explicit type prop for the button element.

The default type of a button is submit, which causes the submission of a form when placed inside a form element. This is likely not the behaviour that you want inside a React application.
Allowed button types are: submit, button or reset

(lint/a11y/useButtonType)

js-plugins/mcp/src/types.ts

[error] 37-37: void is confusing inside a union type.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)


[error] 3-3: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

js-plugins/mcp/src/index.ts

[error] 7-7: A Node.js builtin module should be imported with the node: protocol.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.
Unsafe fix: Add the node: protocol.

(lint/style/useNodejsImportProtocol)


[error] 8-8: A Node.js builtin module should be imported with the node: protocol.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.
Unsafe fix: Add the node: protocol.

(lint/style/useNodejsImportProtocol)


[error] 9-9: A Node.js builtin module should be imported with the node: protocol.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.
Unsafe fix: Add the node: protocol.

(lint/style/useNodejsImportProtocol)


[error] 19-19: Use === instead of ==. == is only allowed when comparing against null

== is only allowed when comparing against null

Using == may be unsafe if you are relying on type coercion
Unsafe fix: Use ===

(lint/suspicious/noDoubleEquals)


[error] 23-23: Use === instead of ==. == is only allowed when comparing against null

== is only allowed when comparing against null

Using == may be unsafe if you are relying on type coercion
Unsafe fix: Use ===

(lint/suspicious/noDoubleEquals)


[error] 30-30: config is assigned to itself.

This is where is assigned.

(lint/correctness/noSelfAssign)


[error] 2-2: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)


[error] 26-26: This let declares a variable that is only assigned once.

'farmConfig' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


[error] 30-30: Reassigning a function parameter is confusing.

The parameter is declared here:

Use a local variable instead.

(lint/style/noParameterAssign)

js-plugins/mcp/src/server.ts

[error] 41-41: This let declares a variable that is only assigned once.

'resource' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)

js-plugins/mcp/src/connect.ts

[error] 4-4: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

🔇 Additional comments (20)
examples/mcp/index.js (1)

1-1: Simple entry point implementation.

The file logs "lib" as its sole action, serving as a minimal entry point for the "mcp" plugin. If you plan to expand functionality here later, consider adding inline comments or additional context.

README.md (1)

35-35: Addition of mcp plugin documentation entry.

The new table entry for [mcp](js-plugins/mcp) clearly conveys that this plugin is inspired by nuxt-mcp. Please verify that the table’s formatting remains consistent with the rest of the document.

examples/mcp/tsconfig.node.json (1)

1-11: TypeScript configuration is well defined.

The compiler options (e.g., "composite", "skipLibCheck", and "moduleResolution": "bundler") are properly set up for a Node environment. Ensure that the referenced "farm.config.ts" is present in the expected directory.

examples/mcp/src/typings.d.ts (1)

1-3: Asset type declarations added.

Declaring modules for *.svg, *.png, and *.css files is a good move to enable proper type-checking when importing these assets in a TypeScript project.

examples/mcp/README.md (2)

9-11: LGTM! Clear installation instructions

The installation instructions are clear and concise.


17-19: LGTM! Development command is clear

The development command is well-documented.

examples/mcp/farm.config.ts (3)

1-3: LGTM! Imports look good

The imports for defineConfig and farmPluginMcp are correctly defined.


5-11: LGTM! Compilation configuration is clear

The compilation settings are well-defined with clear input and cache options.


12-15: LGTM! Plugin configuration

Both plugins are properly configured, with React set to use automatic runtime.

js-plugins/mcp/package.json (4)

5-15: LGTM! Export configuration

The package exports configuration is correctly set up for both CommonJS and ESM formats with proper type definitions.


26-29: LGTM! Dependencies

The dependencies look appropriate for an MCP plugin, including the MCP SDK and zod for schema validation.


30-37: LGTM! Development dependencies

The development dependencies include all necessary Farm-related packages and TypeScript types.


38-40: LGTM! Files configuration

Correctly limiting published files to just the build directory.

examples/mcp/src/index.tsx (2)

1-4: LGTM! Imports

All necessary imports are correctly defined.


10-10: LGTM! Root rendering

The Main component is correctly rendered into the root.

examples/mcp/src/main.css (1)

1-42: CSS looks well-structured with good accessibility practices

The CSS styling is well-organized and follows best practices:

  • Good use of classes for specific styling
  • Respects user preferences with the prefers-reduced-motion media query
  • Proper use of will-change for performance optimization
  • Clean transitions and animations
  • Logical structure and organization
js-plugins/mcp/.gitignore (1)

1-198: Well-structured and comprehensive .gitignore file

The .gitignore file covers all necessary exclusions for:

  • Node.js development artifacts
  • OS-specific files (macOS, Windows)
  • Build tools (Cargo, Yarn)
  • Project-specific patterns (*.farm, build)

The file is well-organized with clear section headers and comprehensive coverage of files that should not be tracked in version control.

js-plugins/mcp/farm.config.ts (1)

4-5: LGTM: Environment variable handling is well implemented

The format selection with fallback to 'esm' and file extension determination is a clean approach.

examples/mcp/tsconfig.json (1)

1-25: Well-configured TypeScript setup following best practices

The TypeScript configuration is comprehensive and follows best practices:

  • Uses appropriate ECMAScript target (ES2020)
  • Includes necessary libraries
  • Enables strict type checking and linting options
  • Configures for bundler mode with React JSX support
  • References a node-specific configuration

This provides a solid foundation for the project.

js-plugins/mcp/src/index.ts (1)

1-1: 🛠️ Refactor suggestion

Use 'import type' for type imports

When importing symbols only used as types, use the import type syntax to ensure they're removed during compilation.

-import type { JsPlugin, ResolvedUserConfig } from '@farmfe/core';
+import type { JsPlugin, ResolvedUserConfig } from '@farmfe/core';

Likely an incorrect or invalid review comment.

Comment on lines +7 to +8
const container = document.querySelector('#root');
const root = createRoot(container);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add null check for root element

There's no check to ensure the root element exists before creating the React root. This could cause runtime errors if the HTML doesn't contain an element with id 'root'.

-const container = document.querySelector('#root');
-const root = createRoot(container);
+const container = document.querySelector('#root');
+if (!container) {
+  throw new Error("Root element not found. Make sure there is an element with id 'root' in your HTML.");
+}
+const root = createRoot(container);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const container = document.querySelector('#root');
const root = createRoot(container);
const container = document.querySelector('#root');
if (!container) {
throw new Error("Root element not found. Make sure there is an element with id 'root' in your HTML.");
}
const root = createRoot(container);

Comment on lines +11 to +16
<a href="https://farmfe.org/" target="_blank">
<img src={FarmLogo} className="logo" alt="Farm logo" />
</a>
<a href="https://react.dev" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add rel="noreferrer" to external links for security

Links using target="_blank" without rel="noreferrer" can expose your site to performance and security issues. The new tab can access your window object via window.opener, potentially enabling a phishing attack.

-        <a href="https://farmfe.org/" target="_blank">
+        <a href="https://farmfe.org/" target="_blank" rel="noreferrer">
           <img src={FarmLogo} className="logo" alt="Farm logo" />
         </a>
-        <a href="https://react.dev" target="_blank">
+        <a href="https://react.dev" target="_blank" rel="noreferrer">
           <img src={reactLogo} className="logo react" alt="React logo" />
         </a>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<a href="https://farmfe.org/" target="_blank">
<img src={FarmLogo} className="logo" alt="Farm logo" />
</a>
<a href="https://react.dev" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
<a href="https://farmfe.org/" target="_blank" rel="noreferrer">
<img src={FarmLogo} className="logo" alt="Farm logo" />
</a>
<a href="https://react.dev" target="_blank" rel="noreferrer">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
🧰 Tools
🪛 Biome (1.9.4)

[error] 11-11: Avoid using target="_blank" without rel="noreferrer".

Opening external links in new tabs without rel="noreferrer" is a security risk. See the explanation for more details.
Safe fix: Add the rel="noreferrer" attribute.

(lint/a11y/noBlankTarget)


[error] 14-14: Avoid using target="_blank" without rel="noreferrer".

Opening external links in new tabs without rel="noreferrer" is a security risk. See the explanation for more details.
Safe fix: Add the rel="noreferrer" attribute.

(lint/a11y/noBlankTarget)

Comment on lines +20 to +22
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add explicit type="button" attribute to the button element

The default type of a button is "submit", which could cause unintended form submissions if the button is ever placed inside a form. Best practice is to always specify the button type explicitly.

-        <button onClick={() => setCount((count) => count + 1)}>
+        <button type="button" onClick={() => setCount((count) => count + 1)}>
           count is {count}
         </button>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
<button type="button" onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
🧰 Tools
🪛 Biome (1.9.4)

[error] 20-20: Provide an explicit type prop for the button element.

The default type of a button is submit, which causes the submission of a form when placed inside a form element. This is likely not the behaviour that you want inside a React application.
Allowed button types are: submit, button or reset

(lint/a11y/useButtonType)

* Setup the MCP server, this is called when the MCP server is created
* You may also return a new MCP server to replace the default one
*/
mcpServerSetup?: (server: McpServer, farmServer: Compiler) => Awaitable<void | McpServer>
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Replace void with undefined in union type

Using void in a union type can be confusing since void represents the absence of a return value rather than an actual value. It's clearer to use undefined for this purpose.

-  mcpServerSetup?: (server: McpServer, farmServer: Compiler) => Awaitable<void | McpServer>
+  mcpServerSetup?: (server: McpServer, farmServer: Compiler) => Awaitable<undefined | McpServer>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
mcpServerSetup?: (server: McpServer, farmServer: Compiler) => Awaitable<void | McpServer>
mcpServerSetup?: (server: McpServer, farmServer: Compiler) => Awaitable<undefined | McpServer>
🧰 Tools
🪛 Biome (1.9.4)

[error] 37-37: void is confusing inside a union type.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)

@@ -0,0 +1,71 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { Implementation as McpServerInfo } from '@modelcontextprotocol/sdk/types.js'
import { Compiler, type Server } from "@farmfe/core"
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use import type for type-only imports

When importing entities that are only used as types, it's better to use import type to ensure they're removed during compilation, resulting in smaller bundle sizes.

-import { Compiler, type Server } from "@farmfe/core"
+import type { Compiler, Server } from "@farmfe/core"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import { Compiler, type Server } from "@farmfe/core"
import type { Compiler, Server } from "@farmfe/core"
🧰 Tools
🪛 Biome (1.9.4)

[error] 3-3: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

Comment on lines +56 to +69
if (vscodeMcpOptions.enabled) {
const vscodeConfig = join(root, '.vscode/settings.json')
if (existsSync(vscodeConfig)) {
const mcp = existsSync(join(root, '.vscode/mcp.json'))
? JSON.parse(await fs.readFile(join(root, '.vscode/mcp.json'), 'utf-8') || '{}')
: {}
mcp.servers ||= {}
mcp.servers[vscodeMcpOptions.serverName || 'farm'] = {
type: 'sse',
url: sseUrl,
}
await fs.writeFile(join(root, '.vscode/mcp.json'), `${JSON.stringify(mcp, null, 2)}\n`)
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for VSCode config operations

Similar to the Cursor config, VSCode config operations need error handling.

       if (vscodeMcpOptions.enabled) {
         const vscodeConfig = join(root, '.vscode/settings.json')
         if (existsSync(vscodeConfig)) {
-          const mcp = existsSync(join(root, '.vscode/mcp.json'))
-            ? JSON.parse(await fs.readFile(join(root, '.vscode/mcp.json'), 'utf-8') || '{}')
-            : {}
-          mcp.servers ||= {}
-          mcp.servers[vscodeMcpOptions.serverName || 'farm'] = {
-            type: 'sse',
-            url: sseUrl,
-          }
-          await fs.writeFile(join(root, '.vscode/mcp.json'), `${JSON.stringify(mcp, null, 2)}\n`)
+          try {
+            const mcp = existsSync(join(root, '.vscode/mcp.json'))
+              ? JSON.parse(await fs.readFile(join(root, '.vscode/mcp.json'), 'utf-8') || '{}')
+              : {}
+            mcp.servers ||= {}
+            mcp.servers[vscodeMcpOptions.serverName || 'farm'] = {
+              type: 'sse',
+              url: sseUrl,
+            }
+            await fs.writeFile(join(root, '.vscode/mcp.json'), `${JSON.stringify(mcp, null, 2)}\n`)
+          } catch (error) {
+            console.error('Error updating VSCode MCP configuration:', error);
+          }
         }
       }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (vscodeMcpOptions.enabled) {
const vscodeConfig = join(root, '.vscode/settings.json')
if (existsSync(vscodeConfig)) {
const mcp = existsSync(join(root, '.vscode/mcp.json'))
? JSON.parse(await fs.readFile(join(root, '.vscode/mcp.json'), 'utf-8') || '{}')
: {}
mcp.servers ||= {}
mcp.servers[vscodeMcpOptions.serverName || 'farm'] = {
type: 'sse',
url: sseUrl,
}
await fs.writeFile(join(root, '.vscode/mcp.json'), `${JSON.stringify(mcp, null, 2)}\n`)
}
}
if (vscodeMcpOptions.enabled) {
const vscodeConfig = join(root, '.vscode/settings.json')
if (existsSync(vscodeConfig)) {
try {
const mcp = existsSync(join(root, '.vscode/mcp.json'))
? JSON.parse(await fs.readFile(join(root, '.vscode/mcp.json'), 'utf-8') || '{}')
: {}
mcp.servers ||= {}
mcp.servers[vscodeMcpOptions.serverName || 'farm'] = {
type: 'sse',
url: sseUrl,
}
await fs.writeFile(join(root, '.vscode/mcp.json'), `${JSON.stringify(mcp, null, 2)}\n`)
} catch (error) {
console.error('Error updating VSCode MCP configuration:', error);
}
}
}

import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { Server } from '@farmfe/core'
import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js'
import { Context, Next } from "koa"
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use 'import type' for Koa types

When importing symbols only used as types, use the import type syntax.

-import { Context, Next } from "koa"
+import type { Context, Next } from "koa"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import { Context, Next } from "koa"
import type { Context, Next } from "koa"
🧰 Tools
🪛 Biome (1.9.4)

[error] 4-4: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

Comment on lines +53 to +54
await transport.handlePostMessage(ctx.req, ctx.res)
next()
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for handlePostMessage

The handlePostMessage method is awaited but doesn't have error handling.

-      await transport.handlePostMessage(ctx.req, ctx.res)
-      next()
+      try {
+        await transport.handlePostMessage(ctx.req, ctx.res)
+        next()
+      } catch (error) {
+        console.error('Error handling post message:', error);
+        ctx.status = 500;
+        ctx.body = 'Internal Server Error';
+      }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
await transport.handlePostMessage(ctx.req, ctx.res)
next()
try {
await transport.handlePostMessage(ctx.req, ctx.res)
next()
} catch (error) {
console.error('Error handling post message:', error);
ctx.status = 500;
ctx.body = 'Internal Server Error';
}

Comment on lines +37 to +38
const query = new URLSearchParams(ctx.url?.split('?').pop() || '')
const clientId = query.get('sessionId')
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add safeguard for URL parsing

The URL parsing logic could be more robust to handle malformed URLs.

-      const query = new URLSearchParams(ctx.url?.split('?').pop() || '')
-      const clientId = query.get('sessionId')
+      const urlParts = ctx.url?.split('?') || [];
+      const queryString = urlParts.length > 1 ? urlParts[1] : '';
+      const query = new URLSearchParams(queryString)
+      const clientId = query.get('sessionId')
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const query = new URLSearchParams(ctx.url?.split('?').pop() || '')
const clientId = query.get('sessionId')
const urlParts = ctx.url?.split('?') || [];
const queryString = urlParts.length > 1 ? urlParts[1] : '';
const query = new URLSearchParams(queryString)
const clientId = query.get('sessionId')

Comment on lines +1 to +4
// copy form vite https://github.com/vitejs/vite/blob/e360f0a65426f576cd25f14cafbd6005df78dbf0/packages/vite/src/node/server/searchRoot.ts#L63
import fs from 'node:fs'
import { dirname, join } from 'node:path'

Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify license compliance for Vite code.

The file indicates it's copied from Vite. Please ensure you have verified that using this code complies with Vite's license terms and that appropriate attribution is maintained.


🏁 Script executed:

#!/bin/bash
# Check Vite's license
curl -s https://raw.githubusercontent.com/vitejs/vite/main/LICENSE | head -n 20
echo "\n--- Checking if license is included in your project ---"
find . -type f -name "LICENSE*" -o -name "license*" | xargs cat | grep -i "vite" || echo "No mention of Vite found in license files"

Length of output: 1471


Ensure Proper Attribution for Vite Code Usage

It looks like the Vite code is copied under the MIT License, which requires that the original copyright and permission notices be included with every copy of the software. However, our project's LICENSE files do not reference Vite. Please verify that proper attribution is maintained—either by including Vite’s copyright and permission notice in this file or by updating the project’s LICENSE file to reflect the usage of Vite code.

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