MCP Support in NextChat: Enabling Model Context Protocol for AI Tool Integration

NextChat implements MCP (Model Context Protocol) support as an optional feature that allows AI models to invoke external tools—such as file systems, web search, or custom services—through a JSON-RPC interface defined in the MCP specification.

The ChatGPTNextWeb/NextChat repository includes a complete MCP implementation that bridges AI conversations with external capabilities. This protocol enables the assistant to execute real-world actions by communicating with configured MCP servers during active chat sessions.

How MCP Works in NextChat

NextChat follows the official MCP specification to create a standardized tool-calling layer. The implementation spans configuration management, message parsing, and JSON-RPC execution across multiple core modules.

Enabling MCP via Environment Variables

MCP is disabled by default and requires explicit activation through environment configuration. Set ENABLE_MCP=true in your environment file (as shown in .env.template at lines 13-16) to activate the feature globally.

When the application initializes, isMcpEnabled() in app/config/server.ts (lines 98-100) reads this variable to determine whether to initialize the MCP subsystem. This runtime check guards all MCP-related functionality, ensuring zero overhead when the feature is inactive.

MCP Configuration and Client Lifecycle

MCP servers are defined in app/mcp/mcp_config.json, referenced as CONFIG_PATH in app/mcp/actions.ts (lines 22-23). The system boots these connections through initializeMcpSystem(), which iterates through the configuration and spawns individual clients via initializeSingleClient() (lines 41-56 in app/mcp/actions.ts).

Each client maintains a persistent connection to its respective MCP server, handling the transport layer for JSON-RPC requests. The addMcpServer() function allows dynamic addition of new servers programmatically, updating the configuration file and initializing clients without restarting the application.

System Prompt Generation for Tool Discovery

When MCP is active, getMcpSystemPrompt() constructs a specialized system message that enumerates all available tools to the AI model. This function utilizes the templates MCP_TOOLS_TEMPLATE and MCP_SYSTEM_TEMPLATE defined in app/constant.ts (lines 299-307).

The generated prompt instructs the model on how to format tool requests using specific markdown code blocks, ensuring the assistant knows exactly which capabilities are available and how to invoke them.

Detecting and Executing MCP Requests

The chat store in app/store/chat.ts handles the detection and execution pipeline through two critical phases:

  1. Detection: The isMcpJson() and extractMcpJson() utilities in app/mcp/utils.ts (lines 1-8) scan assistant messages for markdown blocks formatted as json:mcp:<clientId>.

  2. Execution: When detected, checkMcpJson() (lines 826-851 in app/store/chat.ts) parses the JSON-RPC request and calls executeMcpAction() to forward the command to the appropriate MCP client.

The result returns as a json:mcp-response:<clientId> block injected back into the conversation as a user message, allowing the assistant to read the tool output and continue the dialogue.

Key Implementation Files

The MCP architecture relies on these specific source files in the ChatGPTNextWeb/NextChat repository:

  • app/mcp/types.ts – Contains Zod schemas and TypeScript definitions for all MCP request/response shapes (lines 15-48), ensuring strict JSON-RPC compliance with the MCP specification header (lines 1-4).

  • app/mcp/actions.ts – Manages client lifecycle, request forwarding, and configuration I/O including initializeMcpSystem() and the CONFIG_PATH reference.

  • app/store/chat.ts – Core chat store implementing checkMcpJson() for MCP detection and response handling during active conversations.

  • app/mcp/utils.ts – Utility functions isMcpJson() and extractMcpJson() for parsing MCP markdown blocks using regex patterns.

  • app/constant.ts – Defines MCP_TOOLS_TEMPLATE and MCP_SYSTEM_TEMPLATE for generating tool-discovery system prompts.

  • app/config/server.ts – Implements isMcpEnabled() to read the ENABLE_MCP environment variable.

  • .env.template – Documents the ENABLE_MCP configuration option (lines 13-16).

Practical Examples

Enabling MCP in Your Environment

Create or modify your local environment file to activate the protocol:


# .env.local

ENABLE_MCP=true

Upon restart, isMcpEnabled() will return true and the MCP initialization sequence will begin.

Configuring MCP Servers

Define your tool providers in app/mcp/mcp_config.json. Here is a sample configuration for a filesystem server:

{
  "filesystem": {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user"],
    "env": {},
    "status": "active"
  }
}

The system automatically instantiates this client when initializeMcpSystem() runs.

Tool Invocation Flow

When the AI needs to use a tool, it generates a specific markdown block:


```json:mcp:filesystem
{
  "method": "tools/call",
  "params": {
    "name": "list_allowed_directories",
    "arguments": {}
  }
}

NextChat detects this block via `extractMcpJson()`, executes the call through `executeMcpAction()`, and injects the response:

```markdown

```json:mcp-response:filesystem
{
  "result": {
    "directories": ["/home/user", "/home/user/Documents"]
  }
}


The assistant then processes this result as standard conversation text.

## Summary

- **MCP support in NextChat** enables AI models to invoke external tools through a standardized JSON-RPC interface defined in [`app/mcp/types.ts`](https://github.com/ChatGPTNextWeb/NextChat/blob/main/app/mcp/types.ts).

- The feature requires setting `ENABLE_MCP=true` in your environment, checked by `isMcpEnabled()` in [`app/config/server.ts`](https://github.com/ChatGPTNextWeb/NextChat/blob/main/app/config/server.ts).

- MCP clients are configured via [`app/mcp/mcp_config.json`](https://github.com/ChatGPTNextWeb/NextChat/blob/main/app/mcp/mcp_config.json) and initialized through `initializeMcpSystem()` in [`app/mcp/actions.ts`](https://github.com/ChatGPTNextWeb/NextChat/blob/main/app/mcp/actions.ts).

- Tool discovery happens through dynamically generated system prompts using templates from [`app/constant.ts`](https://github.com/ChatGPTNextWeb/NextChat/blob/main/app/constant.ts).

- Request detection uses `isMcpJson()` in [`app/mcp/utils.ts`](https://github.com/ChatGPTNextWeb/NextChat/blob/main/app/mcp/utils.ts), while execution flows through `checkMcpJson()` in [`app/store/chat.ts`](https://github.com/ChatGPTNextWeb/NextChat/blob/main/app/store/chat.ts).

## Frequently Asked Questions

### What is MCP in NextChat?

MCP (Model Context Protocol) in NextChat is an implementation of the Model Context Protocol specification that allows AI assistants to execute external tools during conversations. It works by detecting special markdown code blocks in assistant messages, forwarding JSON-RPC requests to configured MCP servers, and injecting the results back into the chat as response blocks.

### How do I enable MCP support in my NextChat deployment?

Set the environment variable `ENABLE_MCP=true` in your `.env.local` or deployment environment. The application checks this via `isMcpEnabled()` in [`app/config/server.ts`](https://github.com/ChatGPTNextWeb/NextChat/blob/main/app/config/server.ts) and initializes the MCP subsystem only when this variable is present. Without this setting, all MCP functionality remains disabled to conserve resources.

### Where are MCP servers configured in NextChat?

MCP servers are configured in [`app/mcp/mcp_config.json`](https://github.com/ChatGPTNextWeb/NextChat/blob/main/app/mcp/mcp_config.json), with the path defined as `CONFIG_PATH` in [`app/mcp/actions.ts`](https://github.com/ChatGPTNextWeb/NextChat/blob/main/app/mcp/actions.ts). Each entry specifies the command, arguments, environment variables, and status for a client connection. The system reads this file during `initializeMcpSystem()` to spawn client processes that communicate with external tool providers.

### How does NextChat handle MCP tool execution?

The chat store ([`app/store/chat.ts`](https://github.com/ChatGPTNextWeb/NextChat/blob/main/app/store/chat.ts)) scans every assistant message using `isMcpJson()` and `extractMcpJson()` from [`app/mcp/utils.ts`](https://github.com/ChatGPTNextWeb/NextChat/blob/main/app/mcp/utils.ts) to find blocks formatted as ```json:mcp:<clientId>```. When found, `checkMcpJson()` extracts the JSON-RPC payload and calls `executeMcpAction()` to route the request to the appropriate client. The response is wrapped in a ```json:mcp-response:<clientId>``` block and added to the conversation history for the AI to process.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →